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,345 @@
|
||||
// Canais de publicação (no banco e nas rotas: "accounts"): cada canal tem perfis em redes sociais (TikTok,
|
||||
// Instagram, YouTube) e quantas histórias e fontes do Clipador quiser, ao mesmo tempo, com histórico das encerradas.
|
||||
// Uma história também pode sair em vários canais.
|
||||
//
|
||||
// A conexão com cada rede é feita pelo Publicador (lib/publisher.ts), perfil a perfil, em um de dois modos
|
||||
// escolhidos pelo usuário: API oficial ou sessão logada. O estado do perfil (`Profile` do Publicador) é espelhado
|
||||
// em account_networks; tokens e sessões ficam só no Publicador (nunca neste banco nem no navegador).
|
||||
import { all, get, now, run } from "./db";
|
||||
import { SLUG_RE, slugify } from "./paths";
|
||||
import {
|
||||
checkSession, connectProfile, deleteProfile, getProfile, openSession, pasteToken, profileIdFor, tiktokCreatorInfo,
|
||||
type PublisherProfile, type TiktokCreatorInfo,
|
||||
} from "./publisher";
|
||||
import { UserError, getStory } from "./stories";
|
||||
import {
|
||||
NETWORK_STATUSES, PLATFORMS,
|
||||
type Account, type AccountChannel, type AccountNetwork, type AccountStory, type AiLabel, type ApprovalMode, type ConnectNext,
|
||||
type ConnectionMode, type Platform, type Privacy, type PublishTiming, type Story, type TiktokMode,
|
||||
} from "./types";
|
||||
|
||||
const HANDLE_RE = /^@?[A-Za-z0-9._-]{2,40}$/;
|
||||
|
||||
export type AccountView = Account & {
|
||||
networks: AccountNetwork[];
|
||||
stories: (AccountStory & { title: string; kind: Story["kind"] })[];
|
||||
/** Canais de live do Clipador ligados a esta conta (nome e plataforma vêm do serviço do Clipador). */
|
||||
channels: AccountChannel[];
|
||||
};
|
||||
|
||||
export function listAccounts(): AccountView[] {
|
||||
return all<Account>("SELECT * FROM accounts ORDER BY name").map(view);
|
||||
}
|
||||
|
||||
export function getAccount(id: string): AccountView | undefined {
|
||||
const account = get<Account>("SELECT * FROM accounts WHERE id = ?", id);
|
||||
return account ? view(account) : undefined;
|
||||
}
|
||||
|
||||
function view(account: Account): AccountView {
|
||||
return {
|
||||
...account,
|
||||
networks: all<AccountNetwork>("SELECT * FROM account_networks WHERE account_id = ? ORDER BY platform", account.id),
|
||||
stories: all<AccountStory & { title: string; kind: Story["kind"] }>(
|
||||
`SELECT l.*, s.title, s.kind FROM account_stories l JOIN stories s ON s.id = l.story_id
|
||||
WHERE l.account_id = ? ORDER BY l.status, l.linked_at DESC`, account.id),
|
||||
channels: all<AccountChannel>(
|
||||
"SELECT * FROM account_channels WHERE account_id = ? ORDER BY status, linked_at DESC", account.id),
|
||||
};
|
||||
}
|
||||
|
||||
export function createAccount(input: { name: string; niche?: string; notes?: string }): AccountView {
|
||||
const name = input.name.trim();
|
||||
if (name.length < 2 || name.length > 60) throw new UserError("Nome do canal precisa ter entre 2 e 60 caracteres.");
|
||||
const base = slugify(name);
|
||||
if (!SLUG_RE.test(base)) throw new UserError("Nome precisa ter letras ou números.");
|
||||
let id = base;
|
||||
for (let n = 2; get("SELECT 1 FROM accounts WHERE id = ?", id); n++) id = `${base.slice(0, 44)}-${n}`;
|
||||
const ts = now();
|
||||
run("INSERT INTO accounts (id, name, niche, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
id, name, (input.niche ?? "").trim().slice(0, 60), (input.notes ?? "").trim().slice(0, 500), ts, ts);
|
||||
return getAccount(id)!;
|
||||
}
|
||||
|
||||
const APPROVAL_MODES: ApprovalMode[] = ["manual", "auto"];
|
||||
const TIMINGS: PublishTiming[] = ["now", "best_slot"];
|
||||
const AI_LABELS: AiLabel[] = ["auto", "always", "never"];
|
||||
|
||||
/** Edita nome, nicho, notas e as regras de publicação (aprovação, quando publicar, rótulo de IA). */
|
||||
export function updateAccount(id: string, input: {
|
||||
name?: string; niche?: string; notes?: string; approvalMode?: unknown; timing?: unknown; aiLabel?: unknown;
|
||||
}): AccountView {
|
||||
const account = mustGet(id);
|
||||
const name = (input.name ?? account.name).trim();
|
||||
if (name.length < 2 || name.length > 60) throw new UserError("Nome do canal precisa ter entre 2 e 60 caracteres.");
|
||||
const approvalMode = (input.approvalMode ?? account.approval_mode) as ApprovalMode;
|
||||
if (!APPROVAL_MODES.includes(approvalMode)) throw new UserError("Aprovação inválida: use manual ou auto.");
|
||||
const timing = (input.timing ?? account.timing) as PublishTiming;
|
||||
if (!TIMINGS.includes(timing)) throw new UserError("Quando publicar inválido: use now ou best_slot.");
|
||||
const aiLabel = (input.aiLabel ?? account.ai_label) as AiLabel;
|
||||
if (!AI_LABELS.includes(aiLabel)) throw new UserError("Rótulo de IA inválido: use auto, always ou never.");
|
||||
// Ligar o automático vale daqui para a frente: cortes que já estavam prontos continuam esperando você.
|
||||
const autoSince = approvalMode === "auto" ? (account.approval_mode === "auto" ? account.auto_since : now()) : null;
|
||||
run(`UPDATE accounts SET name = ?, niche = ?, notes = ?, approval_mode = ?, timing = ?, ai_label = ?, auto_since = ?, updated_at = ?
|
||||
WHERE id = ?`,
|
||||
name, (input.niche ?? account.niche).trim().slice(0, 60), (input.notes ?? account.notes).trim().slice(0, 500),
|
||||
approvalMode, timing, aiLabel, autoSince, now(), id);
|
||||
return getAccount(id)!;
|
||||
}
|
||||
|
||||
export function deleteAccount(id: string): void {
|
||||
mustGet(id);
|
||||
run("DELETE FROM accounts WHERE id = ?", id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda o @ de um perfil sem conectar (rota antiga POST /networks). A conexão real é `connectNetwork`.
|
||||
* Linha nova nasce `disconnected`; numa existente só troca o @.
|
||||
*/
|
||||
export function linkNetwork(accountId: string, platform: string, handle: string): AccountView {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
const clean = handle.trim();
|
||||
if (!HANDLE_RE.test(clean)) throw new UserError("Perfil inválido: use @usuario (letras, números, ponto, _ ou -).");
|
||||
const at = clean.startsWith("@") ? clean : `@${clean}`;
|
||||
run(`INSERT INTO account_networks (account_id, platform, handle, status) VALUES (?, ?, ?, 'disconnected')
|
||||
ON CONFLICT (account_id, platform) DO UPDATE SET handle = excluded.handle`, accountId, p, at);
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
// ---------- conexão real com as redes (pelo Publicador) ----------
|
||||
export function getNetwork(accountId: string, platform: Platform): AccountNetwork | undefined {
|
||||
return get<AccountNetwork>("SELECT * FROM account_networks WHERE account_id = ? AND platform = ?", accountId, platform);
|
||||
}
|
||||
|
||||
function ensureNetwork(accountId: string, platform: Platform): AccountNetwork {
|
||||
run("INSERT INTO account_networks (account_id, platform, status) VALUES (?, ?, 'disconnected') ON CONFLICT (account_id, platform) DO NOTHING",
|
||||
accountId, platform);
|
||||
return getNetwork(accountId, platform)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Espelha o `Profile` do Publicador na linha da rede. O @ e o nome só são trocados quando a rede informa;
|
||||
* ao desconectar, saem também (o perfil pode ser outro na próxima conexão).
|
||||
*/
|
||||
export function mirrorProfile(accountId: string, platform: Platform, profile: PublisherProfile): AccountNetwork {
|
||||
ensureNetwork(accountId, platform);
|
||||
const status = NETWORK_STATUSES.includes(profile.status) ? profile.status : "error";
|
||||
const mode = profile.mode === "official" || profile.mode === "session" ? profile.mode : null;
|
||||
const clear = status === "disconnected" ? 1 : 0;
|
||||
run(`UPDATE account_networks SET status = ?, mode = ?,
|
||||
handle = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, handle) END,
|
||||
display_name = CASE WHEN ? = 1 THEN NULL ELSE COALESCE(?, display_name) END,
|
||||
connected_at = ?, expires_at = ?, checked_at = ?, last_error = ?
|
||||
WHERE account_id = ? AND platform = ?`,
|
||||
status, mode, clear, profile.handle ?? null, clear, profile.displayName ?? null,
|
||||
profile.connectedAt ?? null, profile.expiresAt ?? null, profile.lastCheckAt ?? now(), profile.lastError ?? null,
|
||||
accountId, platform);
|
||||
return getNetwork(accountId, platform)!;
|
||||
}
|
||||
|
||||
/** Marca o perfil como "precisa entrar de novo" (o Publicador parou um envio na tela de login). */
|
||||
export function markNetworkNeedsLogin(accountId: string, platform: Platform, error: string | null): void {
|
||||
run("UPDATE account_networks SET status = 'needs_login', last_error = ?, checked_at = ? WHERE account_id = ? AND platform = ?",
|
||||
error, now(), accountId, platform);
|
||||
}
|
||||
|
||||
const PRIVACY_BY_PLATFORM: Record<Platform, Privacy[]> = {
|
||||
youtube: ["public", "unlisted", "private"],
|
||||
tiktok: ["public", "private"],
|
||||
instagram: ["public"],
|
||||
};
|
||||
|
||||
/** Ajustes da rede no canal (cria a linha se faltar): {enabled?, dailyLimit?, privacy?, tiktokMode?}. */
|
||||
export function updateNetworkSettings(accountId: string, platform: string, input: {
|
||||
enabled?: unknown; dailyLimit?: unknown; privacy?: unknown; tiktokMode?: unknown;
|
||||
}): AccountNetwork {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
// Valida tudo antes de criar a linha: pedido inválido não deixa rede nova para trás.
|
||||
const current = getNetwork(accountId, p) ?? { enabled: 1, daily_limit: 3, privacy: "public" as Privacy, tiktok_mode: "direct" as TiktokMode };
|
||||
let enabled = current.enabled;
|
||||
if (input.enabled !== undefined) {
|
||||
if (typeof input.enabled !== "boolean") throw new UserError("enabled precisa ser verdadeiro ou falso.");
|
||||
enabled = input.enabled ? 1 : 0;
|
||||
}
|
||||
let dailyLimit = current.daily_limit;
|
||||
if (input.dailyLimit !== undefined) {
|
||||
dailyLimit = Number(input.dailyLimit);
|
||||
if (!Number.isInteger(dailyLimit) || dailyLimit < 1 || dailyLimit > 20) throw new UserError("Máximo por dia precisa ser de 1 a 20.");
|
||||
}
|
||||
let privacy = current.privacy;
|
||||
if (input.privacy !== undefined) {
|
||||
privacy = input.privacy as Privacy;
|
||||
if (!PRIVACY_BY_PLATFORM[p].includes(privacy)) {
|
||||
throw new UserError(`Privacidade inválida para esta rede: use ${PRIVACY_BY_PLATFORM[p].join(", ")}.`);
|
||||
}
|
||||
}
|
||||
let tiktokMode = current.tiktok_mode;
|
||||
if (input.tiktokMode !== undefined) {
|
||||
tiktokMode = input.tiktokMode as TiktokMode;
|
||||
if (tiktokMode !== "direct" && tiktokMode !== "draft") throw new UserError("Modo do TikTok inválido: use direct ou draft.");
|
||||
}
|
||||
ensureNetwork(accountId, p);
|
||||
run("UPDATE account_networks SET enabled = ?, daily_limit = ?, privacy = ?, tiktok_mode = ? WHERE account_id = ? AND platform = ?",
|
||||
enabled, dailyLimit, privacy, tiktokMode, accountId, p);
|
||||
touch(accountId);
|
||||
return getNetwork(accountId, p)!;
|
||||
}
|
||||
|
||||
/** Começa a conexão no modo escolhido. Devolve o próximo passo (abrir login, colar token, "Já entrei"). */
|
||||
export async function connectNetwork(accountId: string, platform: string, mode: unknown): Promise<{ network: AccountNetwork; next: ConnectNext }> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
if (mode !== "official" && mode !== "session") throw new UserError("Escolha o modo: official (API oficial) ou session (sessão logada).");
|
||||
ensureNetwork(accountId, p);
|
||||
const result = await connectProfile(profileIdFor(accountId, p), p, mode as ConnectionMode);
|
||||
touch(accountId);
|
||||
return { network: mirrorProfile(accountId, p, result.profile), next: result.next };
|
||||
}
|
||||
|
||||
/** Instagram oficial: token gerado no painel da Meta, colado pelo usuário. Vai direto ao cofre do Publicador. */
|
||||
export async function pasteNetworkToken(accountId: string, platform: string, accessToken: unknown): Promise<AccountNetwork> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
const token = typeof accessToken === "string" ? accessToken.trim() : "";
|
||||
if (token.length < 20 || token.length > 4096 || /\s/.test(token)) throw new UserError("Cole o token inteiro (um texto longo, sem espaços).");
|
||||
ensureNetwork(accountId, p);
|
||||
return mirrorProfile(accountId, p, await pasteToken(profileIdFor(accountId, p), token));
|
||||
}
|
||||
|
||||
/** Confere a conexão: sessão logada abre a página de envio e vê se está logado; API oficial relê o perfil. */
|
||||
export async function checkNetwork(accountId: string, platform: string): Promise<AccountNetwork> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
const network = ensureNetwork(accountId, p);
|
||||
const profileId = profileIdFor(accountId, p);
|
||||
const profile = network.mode === "session" ? await checkSession(profileId) : await getProfile(profileId);
|
||||
return mirrorProfile(accountId, p, profile);
|
||||
}
|
||||
|
||||
/** Relê o perfil no Publicador sem abrir nada (o despachante usa para acompanhar OAuth e validade). */
|
||||
export async function refreshNetwork(accountId: string, platform: Platform): Promise<AccountNetwork> {
|
||||
return mirrorProfile(accountId, platform, await getProfile(profileIdFor(accountId, platform)));
|
||||
}
|
||||
|
||||
/** Modo sessão: reabre a janela do navegador para o usuário entrar de novo. */
|
||||
export async function reopenNetwork(accountId: string, platform: string): Promise<{ network: AccountNetwork; next: ConnectNext }> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
const network = ensureNetwork(accountId, p);
|
||||
if (network.mode !== "session") throw new UserError("Reabrir o navegador só vale para o modo sessão logada. Na API oficial, conecte de novo.");
|
||||
const result = await openSession(profileIdFor(accountId, p));
|
||||
return { network: mirrorProfile(accountId, p, result.profile), next: result.next };
|
||||
}
|
||||
|
||||
/**
|
||||
* Desconecta: o Publicador apaga tokens e o perfil de navegador. A linha fica (com os ajustes de limite,
|
||||
* privacidade etc.), em `disconnected`. Rede que nunca foi conectada não precisa do Publicador.
|
||||
*/
|
||||
export async function disconnectNetwork(accountId: string, platform: string): Promise<AccountView> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
const network = getNetwork(accountId, p);
|
||||
if (network && (network.mode !== null || network.status !== "disconnected")) {
|
||||
await deleteProfile(profileIdFor(accountId, p));
|
||||
}
|
||||
run(`UPDATE account_networks SET status = 'disconnected', mode = NULL, handle = NULL, display_name = NULL, connected_at = NULL,
|
||||
expires_at = NULL, last_error = NULL, checked_at = ? WHERE account_id = ? AND platform = ?`, now(), accountId, p);
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
/** TikTok oficial: opções de privacidade e limites da conta (o TikTok exige mostrar antes de publicar). */
|
||||
export async function networkCreatorInfo(accountId: string, platform: string): Promise<TiktokCreatorInfo> {
|
||||
mustGet(accountId);
|
||||
const p = mustPlatform(platform);
|
||||
if (p !== "tiktok") throw new UserError("Só o TikTok tem essas informações do criador.");
|
||||
return tiktokCreatorInfo(profileIdFor(accountId, p));
|
||||
}
|
||||
|
||||
/** Liga uma história à conta (várias ativas ao mesmo tempo). Religar uma encerrada reativa. */
|
||||
export function linkStory(accountId: string, storyId: string): AccountView {
|
||||
mustGet(accountId);
|
||||
if (!getStory(storyId)) throw new UserError("História não encontrada.");
|
||||
// Religar um vínculo encerrado recomeça a contagem (linked_at = agora): nada do intervalo desligado é aprovado sozinho.
|
||||
run(`INSERT INTO account_stories (account_id, story_id, status, linked_at) VALUES (?, ?, 'active', ?)
|
||||
ON CONFLICT (account_id, story_id) DO UPDATE SET status = 'active', ended_at = NULL,
|
||||
linked_at = CASE WHEN account_stories.status = 'ended' THEN excluded.linked_at ELSE account_stories.linked_at END`,
|
||||
accountId, storyId, now());
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
/** Encerra o vínculo (a história sai das ativas da conta, mas fica no histórico e nas métricas). */
|
||||
export function endStory(accountId: string, storyId: string): AccountView {
|
||||
mustGet(accountId);
|
||||
const r = run("UPDATE account_stories SET status = 'ended', ended_at = ? WHERE account_id = ? AND story_id = ? AND status = 'active'",
|
||||
now(), accountId, storyId);
|
||||
if (r.changes === 0) throw new UserError("Essa história não está ativa nesta conta.");
|
||||
// Episódios dessa história que ainda não saíram por este canal são cancelados.
|
||||
run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'unlinked', step = 'Cancelado: a história foi desligada deste canal.', updated_at = ?
|
||||
WHERE account_id = ? AND source_kind = 'episode' AND status IN ('awaiting_approval', 'scheduled', 'queued') AND publisher_job_id IS NULL
|
||||
AND CAST(source_id AS INTEGER) IN (SELECT id FROM episodes WHERE story_id = ?)`, now(), accountId, storyId);
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
const CHANNEL_ID_RE = /^(twitch|youtube|kick)-[a-z0-9._-]{2,60}$/;
|
||||
|
||||
/** Liga um canal de live (Clipador) à conta: os cortes dele vão para as redes desta conta. Religar reativa. */
|
||||
export function linkChannel(accountId: string, channelId: string): AccountView {
|
||||
mustGet(accountId);
|
||||
if (!CHANNEL_ID_RE.test(channelId)) throw new UserError("Canal inválido.");
|
||||
// Religar uma fonte encerrada recomeça a contagem (linked_at = agora): a aprovação automática não pega cortes
|
||||
// feitos enquanto a fonte estava desligada.
|
||||
run(`INSERT INTO account_channels (account_id, channel_id, status, linked_at) VALUES (?, ?, 'active', ?)
|
||||
ON CONFLICT (account_id, channel_id) DO UPDATE SET status = 'active', ended_at = NULL,
|
||||
linked_at = CASE WHEN account_channels.status = 'ended' THEN excluded.linked_at ELSE account_channels.linked_at END`,
|
||||
accountId, channelId, now());
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
/** Encerra o vínculo (fica no histórico). */
|
||||
export function endChannel(accountId: string, channelId: string): AccountView {
|
||||
mustGet(accountId);
|
||||
const r = run("UPDATE account_channels SET status = 'ended', ended_at = ? WHERE account_id = ? AND channel_id = ? AND status = 'active'",
|
||||
now(), accountId, channelId);
|
||||
if (r.changes === 0) throw new UserError("Esse canal não está ativo nesta conta.");
|
||||
// Cortes dessa fonte que ainda não saíram por este canal são cancelados (renascem se a fonte for religada).
|
||||
// Os publicados à mão pelo cartão do corte (origin = 'manual') ficam: não dependem do vínculo.
|
||||
run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'unlinked', step = 'Cancelado: a fonte foi desligada deste canal.', updated_at = ?
|
||||
WHERE account_id = ? AND source_kind = 'clip' AND source_label = ? AND status IN ('awaiting_approval', 'scheduled', 'queued')
|
||||
AND publisher_job_id IS NULL AND origin = 'link'`, now(), accountId, channelId);
|
||||
touch(accountId);
|
||||
return getAccount(accountId)!;
|
||||
}
|
||||
|
||||
/** Contas ativas que recebem os cortes de um canal (para a fila de publicação). */
|
||||
export function accountsForChannel(channelId: string): (AccountChannel & { name: string })[] {
|
||||
return all<AccountChannel & { name: string }>(
|
||||
`SELECT l.*, a.name FROM account_channels l JOIN accounts a ON a.id = l.account_id
|
||||
WHERE l.channel_id = ? AND l.status = 'active' ORDER BY a.name`, channelId);
|
||||
}
|
||||
|
||||
export function accountsForStory(storyId: string): (AccountStory & { name: string })[] {
|
||||
return all<AccountStory & { name: string }>(
|
||||
`SELECT l.*, a.name FROM account_stories l JOIN accounts a ON a.id = l.account_id WHERE l.story_id = ? ORDER BY a.name`, storyId);
|
||||
}
|
||||
|
||||
function mustGet(id: string): Account {
|
||||
const account = get<Account>("SELECT * FROM accounts WHERE id = ?", id);
|
||||
if (!account) throw new UserError("Canal de publicação não encontrado.");
|
||||
return account;
|
||||
}
|
||||
|
||||
function mustPlatform(platform: string): Platform {
|
||||
if (!PLATFORMS.includes(platform as Platform)) throw new UserError("Rede social inválida.");
|
||||
return platform as Platform;
|
||||
}
|
||||
|
||||
function touch(id: string): void {
|
||||
run("UPDATE accounts SET updated_at = ? WHERE id = ?", now(), id);
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
// Agentes de código (Claude Code e Codex) chamados pela CLI, como no VS Code.
|
||||
//
|
||||
// Segurança (decisão do usuário: "edita sozinho no projeto"):
|
||||
// - roda com cwd = raiz do repositório; edições automáticas só dentro dele;
|
||||
// - Bash só para os comandos liberados abaixo (render, testes, scripts da skill);
|
||||
// - o pedido vai como argumento (sem shell); stdin fechado;
|
||||
// - um agente por vez; cancelar encerra a árvore de processos.
|
||||
// Comentários do público NUNCA entram no prompt: só a decisão A/B já fechada.
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { DATA_DIR, REPO_ROOT, rel } from "./paths";
|
||||
import { buildPrompt } from "./prompts";
|
||||
import { findOnPath, killTree, lineSplitter } from "./proc";
|
||||
import { onAgentRunClosed } from "./branches";
|
||||
import { UserError, getEpisodeById, getStory, syncStoryMeta } from "./stories";
|
||||
import { AGENT_KINDS, type AgentEvent, type AgentKind, type AgentRun, type Provider } from "./types";
|
||||
|
||||
const SKILL_SCRIPTS = "python .claude/skills/cenaforge/scripts";
|
||||
export const CLAUDE_ALLOWED_TOOLS = [
|
||||
"Read", "Edit", "Write", "Glob", "Grep", "Agent", "Skill", "TodoWrite",
|
||||
"Bash(pnpm render:*)", "Bash(pnpm verify:*)", "Bash(pnpm test:*)", "Bash(pnpm typecheck)",
|
||||
"Bash(pnpm run doctor)", "Bash(pnpm prepare-assets)",
|
||||
`Bash(${SKILL_SCRIPTS}/new_scene.py:*)`, `Bash(${SKILL_SCRIPTS}/runs_summary.py:*)`,
|
||||
`Bash(${SKILL_SCRIPTS}/inspect_strip.py:*)`, `Bash(${SKILL_SCRIPTS}/check_skill.py:*)`, `Bash(${SKILL_SCRIPTS}/godot_api.py:*)`,
|
||||
`Bash(${SKILL_SCRIPTS}/frame_check.py:*)`, `Bash(${SKILL_SCRIPTS}/check_script.py:*)`,
|
||||
].join(",");
|
||||
|
||||
/**
|
||||
* Economia de tokens: sem estas flags, o `claude -p` do painel carregava a cada turno os plugins,
|
||||
* MCPs, hooks, skills e agentes da instalação do usuário (61 ferramentas, 310 skills, 78 agentes).
|
||||
* Medido com o mesmo prompt trivial (17/11/2026): 62,4 mil → 14,9 mil tokens de entrada no 1º turno,
|
||||
* partida de 8,0 s → 4,3 s. Valem só para os agentes do painel; a config global não muda.
|
||||
* - `--setting-sources project,local`: ignora ~/.claude/settings.json (plugins e hooks do usuário).
|
||||
* O login não depende dele. O .claude/ do projeto (skills, subagentes) continua valendo.
|
||||
* - `--strict-mcp-config` sem `--mcp-config`: nenhum servidor MCP.
|
||||
* - `--tools`: só as ferramentas que as tarefas usam (Agent = subagente roteirista; Skill = cenaforge).
|
||||
*/
|
||||
const CLAUDE_TOOLS = "Read,Edit,Write,Glob,Grep,Bash,Agent,Skill,TodoWrite";
|
||||
const CLAUDE_LEAN_FLAGS = ["--setting-sources", "project,local", "--strict-mcp-config", "--tools", CLAUDE_TOOLS];
|
||||
|
||||
/**
|
||||
* Teto de gasto por execução do Claude (US$), proteção contra laço. Folgado: a cena no Godot
|
||||
* custou US$ 3,09 no Opus e o padrão agora é o Sonnet. Ao atingir, a CLI encerra a execução e o
|
||||
* usuário pode continuar a conversa pelo painel.
|
||||
*/
|
||||
export const CLAUDE_BUDGET_USD: Record<AgentKind, number> = { story: 1.5, script: 1.5, branches: 2.5, scene: 1, godot: 3, free: 3 };
|
||||
|
||||
export type ModelOption = { id: string; label: string };
|
||||
|
||||
/** Modelos do Claude Code (ids aceitos por `claude --model`). "" = o padrão configurado na CLI. */
|
||||
const CLAUDE_MODELS: ModelOption[] = [
|
||||
{ id: "", label: "Padrão da CLI" },
|
||||
{ id: "claude-fable-5-2", label: "Fable 5.2" },
|
||||
{ id: "claude-opus-5-5", label: "Opus 5.5: mais capaz, mais caro" },
|
||||
{ id: "claude-sonnet-5-5", label: "Sonnet 5.5: equilíbrio entre roteiro e cena" },
|
||||
{ id: "claude-haiku-5-5", label: "Haiku 5.5: mais barato, para variações e resumos" },
|
||||
];
|
||||
/** Apelidos que execuções antigas gravaram; continuam aceitos ao retomar uma conversa. */
|
||||
const CLAUDE_ALIASES = ["opus", "sonnet", "haiku"];
|
||||
|
||||
const CODEX_HOME = process.env.CODEX_HOME || path.join(process.env.USERPROFILE || process.env.HOME || "", ".codex");
|
||||
|
||||
/**
|
||||
* Modelos do Codex: a própria CLI guarda em ~/.codex/models_cache.json os modelos que a conta
|
||||
* enxerga (atualizado a cada uso da CLI). Só os visíveis no seletor da CLI ("list"), na ordem dela.
|
||||
* O padrão é o `model = "..."` do config.toml.
|
||||
*/
|
||||
function codexModels(): ModelOption[] {
|
||||
let configured = "";
|
||||
try {
|
||||
configured = /^\s*model\s*=\s*"([^"]+)"/m.exec(fs.readFileSync(path.join(CODEX_HOME, "config.toml"), "utf8"))?.[1] ?? "";
|
||||
} catch { /* sem config: a CLI usa o padrão dela */ }
|
||||
type CachedModel = { slug?: unknown; display_name?: unknown; description?: unknown; visibility?: unknown; priority?: unknown };
|
||||
let cached: CachedModel[] = [];
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(path.join(CODEX_HOME, "models_cache.json"), "utf8")) as { models?: unknown };
|
||||
if (Array.isArray(parsed.models)) cached = parsed.models as CachedModel[];
|
||||
} catch { /* cache ausente: só o padrão */ }
|
||||
const listed = cached
|
||||
.filter((m) => typeof m.slug === "string" && m.visibility === "list")
|
||||
.sort((a, b) => Number(a.priority ?? 99) - Number(b.priority ?? 99))
|
||||
.map((m) => {
|
||||
const name = typeof m.display_name === "string" ? m.display_name : String(m.slug);
|
||||
const about = typeof m.description === "string" && m.description ? `: ${m.description}` : "";
|
||||
return { id: String(m.slug), label: `${name}${about}` };
|
||||
});
|
||||
const defaultName = listed.find((m) => m.id === configured)?.label.split(":")[0] ?? configured;
|
||||
return [{ id: "", label: defaultName ? `Padrão da CLI (${defaultName})` : "Padrão da CLI" }, ...listed];
|
||||
}
|
||||
|
||||
/** Modelos que o seletor oferece por agente. */
|
||||
export function models(): Record<Provider, ModelOption[]> {
|
||||
return { claude: CLAUDE_MODELS, codex: codexModels() };
|
||||
}
|
||||
|
||||
/** Modelo sugerido por tipo de tarefa (economia de tokens). */
|
||||
// Vertentes: roteiro + cena de 2–4 episódios numa execução só → Sonnet (qualidade de roteiro sem o custo do Opus).
|
||||
// Cena no Godot: Sonnet (a cena dos náufragos no Opus custou US$ 3,09 e esgotou o limite de 5 h em 11 min).
|
||||
export const DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "", script: "", scene: "claude-sonnet-5-5", branches: "claude-sonnet-5-5", godot: "claude-sonnet-5-5" };
|
||||
|
||||
/**
|
||||
* Agente preferido por tarefa (decisão do usuário: enredo e roteiro com GPT, via Codex).
|
||||
* Se o preferido não estiver disponível, cai para o outro.
|
||||
*/
|
||||
export const PREFERRED_PROVIDER: Record<AgentKind, Provider> = { free: "claude", story: "codex", script: "codex", scene: "claude", branches: "codex", godot: "claude" };
|
||||
|
||||
export function defaultProviderFor(kind: AgentKind): Provider {
|
||||
const list = providers();
|
||||
const preferred = PREFERRED_PROVIDER[kind];
|
||||
if (list.find((p) => p.id === preferred)?.available) return preferred;
|
||||
return list.find((p) => p.available)?.id ?? preferred;
|
||||
}
|
||||
|
||||
/** Modelo padrão: o do tipo de tarefa só vale para o Claude; no Codex, o do config.toml. */
|
||||
export function defaultModelFor(kind: AgentKind, provider: Provider): string {
|
||||
return provider === "claude" ? DEFAULT_MODEL[kind] : CODEX_DEFAULT_MODEL[kind];
|
||||
}
|
||||
|
||||
/**
|
||||
* Codex por tarefa (economia): texto e roteiro com o modelo de uso geral (GPT-6.1-Sol), não o
|
||||
* "frontier" do config.toml (GPT-6-Astra, o mais caro). "" = o padrão do config.toml. Só vale se o
|
||||
* modelo existir na lista da CLI; senão cai no padrão.
|
||||
*/
|
||||
const CODEX_DEFAULT_MODEL: Record<AgentKind, string> = { free: "", story: "gpt-6.1-sol", script: "gpt-6.1-sol", branches: "gpt-6.1-sol", scene: "", godot: "" };
|
||||
|
||||
/** `command` + `prefixArgs` é o que de fato executamos (ex.: node + codex.js no Windows). */
|
||||
type ProviderInfo = {
|
||||
id: Provider; available: boolean; path: string | null; version: string | null; note: string;
|
||||
command: string | null; prefixArgs: string[];
|
||||
};
|
||||
/**
|
||||
* Execução em andamento. `followUp`: mensagem do usuário enviada durante a execução; quando ela
|
||||
* fecha (sozinha ou interrompida), a mesma sessão é retomada com essa mensagem.
|
||||
*/
|
||||
type ActiveRun = {
|
||||
child: ChildProcess;
|
||||
listeners: Set<(e: AgentEvent | null) => void>;
|
||||
emit: (e: Omit<AgentEvent, "at">) => void;
|
||||
followUp: string | null;
|
||||
/** O agente já deu um passo (texto ou ferramenta). Antes disso a sessão ainda não guardou o pedido. */
|
||||
progressed: boolean;
|
||||
};
|
||||
const g = globalThis as unknown as { __cenaforgeAgents?: Map<number, ActiveRun>; __cenaforgeProviders?: { at: number; list: ProviderInfo[] } };
|
||||
const active = (g.__cenaforgeAgents ??= new Map());
|
||||
|
||||
/** Há um agente trabalhando? (o executor roda um por vez) */
|
||||
export function busy(): boolean {
|
||||
return active.size > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executável de um provedor. No Windows o npm instala o Codex como `codex.cmd` (que o Node
|
||||
* não executa sem shell); nesse caso rodamos o `codex.js` do pacote diretamente pelo Node.
|
||||
*/
|
||||
function resolveCommand(id: Provider, envVar: string): { path: string; command: string; prefixArgs: string[] } | null {
|
||||
const fromEnv = process.env[envVar];
|
||||
if (fromEnv) {
|
||||
return fromEnv.endsWith(".js")
|
||||
? { path: fromEnv, command: process.execPath, prefixArgs: [fromEnv] }
|
||||
: { path: fromEnv, command: fromEnv, prefixArgs: [] };
|
||||
}
|
||||
const exe = findOnPath(id);
|
||||
if (exe) return { path: exe, command: exe, prefixArgs: [] };
|
||||
if (id === "codex") {
|
||||
for (const dir of (process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
||||
const js = path.join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
||||
if (fs.existsSync(path.join(dir, "codex.cmd")) && fs.existsSync(js)) {
|
||||
return { path: js, command: process.execPath, prefixArgs: [js] };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function providers(): ProviderInfo[] {
|
||||
// Cache curto: instalar ou remover uma CLI aparece sem reiniciar o painel.
|
||||
if (g.__cenaforgeProviders && Date.now() - g.__cenaforgeProviders.at < 60_000) return g.__cenaforgeProviders.list;
|
||||
const detect = (id: Provider, envVar: string, note: string): ProviderInfo => {
|
||||
const resolved = resolveCommand(id, envVar);
|
||||
let version: string | null = null;
|
||||
if (resolved) {
|
||||
const r = spawnSync(resolved.command, [...resolved.prefixArgs, "--version"], { encoding: "utf8", timeout: 20_000, windowsHide: true, shell: false });
|
||||
version = r.status === 0 ? r.stdout.trim().split(/\r?\n/)[0] : null;
|
||||
}
|
||||
return {
|
||||
id, available: !!resolved && version !== null, path: resolved?.path ?? null, version,
|
||||
note: resolved ? note : `${note} Não encontrado: instale e faça login${id === "codex" ? " (npm install -g @openai/codex; codex login)" : ""}.`,
|
||||
command: resolved?.command ?? null, prefixArgs: resolved?.prefixArgs ?? [],
|
||||
};
|
||||
};
|
||||
const list = [
|
||||
detect("claude", "CLAUDE_BIN", "Claude Code CLI em modo não interativo (-p, stream-json); edição automática dentro do projeto e comandos liberados."),
|
||||
detect("codex", "CODEX_BIN", "Codex CLI (codex exec --json) com sandbox workspace-write: escreve só dentro do projeto."),
|
||||
];
|
||||
g.__cenaforgeProviders = { at: Date.now(), list };
|
||||
return list;
|
||||
}
|
||||
|
||||
export function listRuns(limit = 30): AgentRun[] {
|
||||
return all<AgentRun>("SELECT * FROM agent_runs ORDER BY id DESC LIMIT ?", limit);
|
||||
}
|
||||
|
||||
export function getRun(id: number): AgentRun | undefined {
|
||||
return get<AgentRun>("SELECT * FROM agent_runs WHERE id = ?", id);
|
||||
}
|
||||
|
||||
export function startRun(input: {
|
||||
provider: Provider; model: string; kind: AgentKind; request: string;
|
||||
storyId?: string | null; episodeId?: number | null; resumeRunId?: number | null;
|
||||
}): AgentRun {
|
||||
const info = providers().find((p) => p.id === input.provider);
|
||||
if (!info?.available || !info.command) throw new UserError(`${input.provider} não está disponível neste computador.`);
|
||||
if (active.size > 0) throw new UserError("Já existe um agente trabalhando. Aguarde ou cancele antes de enviar outro pedido.");
|
||||
const request = input.request.trim();
|
||||
if (request.length < 2) throw new UserError("Escreva o pedido.");
|
||||
if (request.length > 20_000) throw new UserError("Pedido longo demais (máx. 20 mil caracteres).");
|
||||
if (!AGENT_KINDS.includes(input.kind)) throw new UserError("Tipo de tarefa inválido.");
|
||||
const knownModel = models()[input.provider].some((m) => m.id === input.model) ||
|
||||
(input.provider === "claude" && CLAUDE_ALIASES.includes(input.model));
|
||||
if (input.model && !knownModel) throw new UserError("Modelo inválido para este agente.");
|
||||
|
||||
const story = input.storyId ? getStory(input.storyId) : undefined;
|
||||
if (input.storyId && !story) throw new UserError("História não encontrada.");
|
||||
const episode = input.episodeId ? getEpisodeById(input.episodeId) : undefined;
|
||||
if (input.episodeId && (!episode || episode.story_id !== story?.id)) throw new UserError("Episódio não pertence à história.");
|
||||
const resume = input.resumeRunId ? getRun(input.resumeRunId) : undefined;
|
||||
if (input.resumeRunId && (!resume?.session_id || resume.provider !== input.provider)) {
|
||||
throw new UserError("Só é possível continuar uma conversa do mesmo agente, com sessão registrada.");
|
||||
}
|
||||
|
||||
const prompt = resume ? request : buildPrompt({ kind: input.kind, provider: input.provider, request, story, episode });
|
||||
const logDir = path.join(DATA_DIR, "logs", "agents");
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
const row = run(`INSERT INTO agent_runs (provider, model, kind, prompt, story_id, episode_id, resume_of, status, log_path, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'running', '', ?)`,
|
||||
input.provider, input.model, input.kind, request, story?.id ?? null, episode?.id ?? null, resume?.id ?? null, now());
|
||||
const id = Number(row.lastInsertRowid);
|
||||
const logPath = path.join(logDir, `${id}.jsonl`);
|
||||
run("UPDATE agent_runs SET log_path = ? WHERE id = ?", rel(logPath), id);
|
||||
|
||||
const args = input.provider === "claude"
|
||||
? ["-p", prompt, "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits",
|
||||
...(input.model ? ["--model", input.model] : []),
|
||||
...(resume?.session_id ? ["--resume", resume.session_id] : []),
|
||||
...CLAUDE_LEAN_FLAGS, "--max-budget-usd", String(CLAUDE_BUDGET_USD[input.kind]),
|
||||
"--allowedTools", CLAUDE_ALLOWED_TOOLS]
|
||||
: codexArgs(prompt, input.model, resume?.session_id ?? null, input.kind);
|
||||
|
||||
const child = spawn(info.command, [...info.prefixArgs, ...args], { cwd: REPO_ROOT, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
||||
const listeners = new Set<(e: AgentEvent | null) => void>();
|
||||
const log = fs.createWriteStream(logPath);
|
||||
const emit = (e: Omit<AgentEvent, "at">) => {
|
||||
if (e.kind !== "system" && e.kind !== "stderr" && e.kind !== "error") entry.progressed = true;
|
||||
const event = { ...e, at: now() } as AgentEvent;
|
||||
log.write(JSON.stringify(event) + "\n");
|
||||
for (const l of listeners) l(event);
|
||||
};
|
||||
const entry: ActiveRun = { child, listeners, emit, followUp: null, progressed: false };
|
||||
active.set(id, entry);
|
||||
emit({ kind: "system", text: `${input.provider}${input.model ? ` · ${input.model}` : ""} · tarefa "${input.kind}"${resume ? ` · continua a execução #${resume.id}` : ""}` });
|
||||
|
||||
child.stdout.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||||
let obj: Record<string, unknown>;
|
||||
try {
|
||||
obj = JSON.parse(line);
|
||||
} catch {
|
||||
emit({ kind: "text", text: line.slice(0, 2000) });
|
||||
return;
|
||||
}
|
||||
const events = input.provider === "claude" ? normalizeClaude(obj, id) : normalizeCodex(obj, id);
|
||||
events.forEach(emit);
|
||||
}));
|
||||
child.stderr.setEncoding("utf8").on("data", lineSplitter((line) => {
|
||||
if (!STDERR_NOISE.some((re) => re.test(line))) emit({ kind: "stderr", text: line.slice(0, 1000) });
|
||||
}));
|
||||
child.on("error", (error) => emit({ kind: "error", text: `não iniciou: ${error.message}`, isError: true }));
|
||||
child.on("close", (code) => {
|
||||
// Tarefa "criar história": a IA grava meta.json com título e premissa definitivos.
|
||||
if (input.kind === "story" && story && code === 0) syncStoryMeta(story.id);
|
||||
const current = getRun(id);
|
||||
if (current?.status === "running") {
|
||||
const ok = code === 0 && !current.error;
|
||||
run("UPDATE agent_runs SET status = ?, error = COALESCE(error, ?), finished_at = ? WHERE id = ?",
|
||||
ok ? "success" : "error", ok ? null : `saiu com código ${code}`, now(), id);
|
||||
}
|
||||
active.delete(id);
|
||||
// Vertentes: fecha o preparo desta execução e começa o próximo da fila (o executor já está livre).
|
||||
try {
|
||||
onAgentRunClosed(id, getRun(id)?.status === "success");
|
||||
} catch (error) {
|
||||
console.warn(`vertentes após a execução #${id}: ${(error as Error).message}`);
|
||||
}
|
||||
// Mensagem enviada durante a execução: retoma a mesma sessão com ela. Começa ANTES de avisar
|
||||
// os ouvintes, para o evento "end" já levar o id da continuação (o console segue para ela).
|
||||
if (entry.followUp) {
|
||||
const closed = getRun(id);
|
||||
try {
|
||||
if (!closed?.session_id) throw new UserError("o agente não registrou a sessão, então não dá para continuar a conversa");
|
||||
startRun({
|
||||
provider: closed.provider, model: closed.model, kind: closed.kind, request: entry.followUp,
|
||||
storyId: closed.story_id, episodeId: closed.episode_id, resumeRunId: id,
|
||||
});
|
||||
} catch (error) {
|
||||
emit({ kind: "error", text: `Sua mensagem não foi enviada: ${(error as Error).message}. Copie-a e envie de novo.`, isError: true });
|
||||
}
|
||||
}
|
||||
for (const l of listeners) l(null);
|
||||
log.end();
|
||||
});
|
||||
return getRun(id)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mensagem do usuário durante a execução.
|
||||
* - "now": interrompe o agente e retoma a mesma sessão com a correção (ele vê o que já fez);
|
||||
* - "queue": espera o agente terminar e então continua a conversa com a mensagem.
|
||||
* Uma mensagem por vez: a nova substitui a que estava na fila.
|
||||
*/
|
||||
export function sendFollowUp(id: number, text: string, mode: "now" | "queue"): void {
|
||||
const entry = active.get(id);
|
||||
if (!entry) throw new UserError("Esta execução já terminou. Use \"Continuar esta conversa\".");
|
||||
const message = text.trim();
|
||||
if (message.length < 2) throw new UserError("Escreva a mensagem.");
|
||||
if (message.length > 20_000) throw new UserError("Mensagem longa demais (máx. 20 mil caracteres).");
|
||||
const current = getRun(id);
|
||||
// Testado com o Codex: interrompido antes do primeiro passo, a sessão retomada não tem o pedido original.
|
||||
if (mode === "now" && (!current?.session_id || !entry.progressed)) {
|
||||
throw new UserError("O agente ainda está começando. Aguarde o primeiro passo dele ou use \"Enviar ao terminar\".");
|
||||
}
|
||||
entry.followUp = mode === "now"
|
||||
? `O usuário interrompeu você para corrigir o rumo. Considere o que já foi feito até aqui e siga esta orientação:\n\n${message}`
|
||||
: `Mensagem do usuário enviada enquanto você trabalhava:\n\n${message}`;
|
||||
entry.emit({ kind: "system", text: mode === "now" ? "Interrompido para receber sua correção." : "Sua mensagem será enviada quando o agente terminar." });
|
||||
if (mode === "now") {
|
||||
run("UPDATE agent_runs SET status = 'cancelled', error = COALESCE(error, ?), finished_at = ? WHERE id = ?", "interrompida para correção", now(), id);
|
||||
killTree(entry.child);
|
||||
}
|
||||
}
|
||||
|
||||
/** A execução que continuou esta (mensagem enviada durante ela ou "Continuar esta conversa"). */
|
||||
export function followUpRunOf(id: number): number | null {
|
||||
return get<{ id: number }>("SELECT id FROM agent_runs WHERE resume_of = ? ORDER BY id DESC LIMIT 1", id)?.id ?? null;
|
||||
}
|
||||
|
||||
export function cancelRun(id: number): void {
|
||||
const entry = active.get(id);
|
||||
if (!entry) throw new UserError("Esta execução não está em andamento.");
|
||||
run("UPDATE agent_runs SET status = 'cancelled', finished_at = ? WHERE id = ?", now(), id);
|
||||
killTree(entry.child);
|
||||
}
|
||||
|
||||
export function isActive(id: number): boolean {
|
||||
return active.has(id);
|
||||
}
|
||||
|
||||
/** Inscreve-se nos eventos ao vivo; o callback recebe null quando termina. */
|
||||
export function subscribe(id: number, listener: (e: AgentEvent | null) => void): () => void {
|
||||
const entry = active.get(id);
|
||||
if (!entry) return () => {};
|
||||
entry.listeners.add(listener);
|
||||
return () => entry.listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function readEvents(id: number): AgentEvent[] {
|
||||
const r = getRun(id);
|
||||
if (!r) return [];
|
||||
try {
|
||||
return fs.readFileSync(path.join(REPO_ROOT, r.log_path), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as AgentEvent);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// --- Codex ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Esforço de raciocínio por tarefa (o config.toml do usuário usa "high"). Medido: o roteiro (#6)
|
||||
* gastou só 857 tokens de raciocínio, então "low" quase não economizaria e arriscaria a pesquisa
|
||||
* de fatos; fica "medium". A cena no Godot (#8) gastou 14,5 mil: "medium". A cena JSON só roda
|
||||
* um script: "low". "" = o do config.toml.
|
||||
*/
|
||||
const CODEX_EFFORT: Record<AgentKind, string> = { story: "medium", script: "medium", branches: "medium", godot: "medium", scene: "low", free: "" };
|
||||
|
||||
/** Plugins do Codex que não servem ao repositório: o de computer-use põe a ferramenta `cua_repl` (~6,5 mil caracteres) em todo turno. */
|
||||
const CODEX_UNUSED_PLUGINS = ["computer-use@openai-bundled", "unified-computer-use@openai-bundled"];
|
||||
|
||||
/**
|
||||
* Overrides `-c` só para as execuções do painel (a config global não muda): esforço por tarefa,
|
||||
* servidores MCP pessoais do config.toml desligados e plugins de computer-use fora.
|
||||
* Obs.: `-c mcp_servers={}` não funciona (o Codex mescla tabelas); é preciso `enabled=false` por servidor.
|
||||
*/
|
||||
function codexLeanOverrides(kind: AgentKind): string[] {
|
||||
const overrides: string[] = [];
|
||||
if (CODEX_EFFORT[kind]) overrides.push(`model_reasoning_effort="${CODEX_EFFORT[kind]}"`);
|
||||
let config = "";
|
||||
try { config = fs.readFileSync(path.join(CODEX_HOME, "config.toml"), "utf8"); } catch { /* sem config: nada a desligar */ }
|
||||
const servers = new Set([...config.matchAll(/^\s*\[mcp_servers\.("?)([A-Za-z0-9_-]+)\1\]\s*$/gm)].map((m) => m[2]));
|
||||
for (const name of servers) overrides.push(`mcp_servers.${name}.enabled=false`);
|
||||
for (const plugin of CODEX_UNUSED_PLUGINS) {
|
||||
if (config.includes(`[plugins."${plugin}"]`)) overrides.push(`plugins."${plugin}".enabled=false`);
|
||||
}
|
||||
return overrides.flatMap((o) => ["-c", o]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flags reais do codex-cli 0.169.0. O repositório não é Git, por isso --skip-git-repo-check.
|
||||
* A retomada (`exec resume`) não aceita --sandbox nem -C: o sandbox vai por -c e o diretório
|
||||
* é o cwd do processo (raiz do repositório).
|
||||
*/
|
||||
function codexArgs(prompt: string, model: string, sessionId: string | null, kind: AgentKind): string[] {
|
||||
const common = ["--json", "--skip-git-repo-check", ...(model ? ["-m", model] : []), ...codexLeanOverrides(kind)];
|
||||
return sessionId
|
||||
? ["exec", "resume", ...common, "-c", 'sandbox_mode="workspace-write"', sessionId, prompt]
|
||||
: ["exec", ...common, "--sandbox", "workspace-write", "-C", REPO_ROOT, prompt];
|
||||
}
|
||||
|
||||
/** Linhas de stderr que não ajudam o usuário (aviso de stdin, MCP pessoal do Codex fora do ar, config pessoal do Codex). */
|
||||
const STDERR_NOISE = [/no stdin data received/, /Reading additional input from stdin/, /rmcp::transport/, /Codex is ignoring \d+ unrecognized configuration setting/,
|
||||
// O Claude Code avisa de id fora da lista interna dele, mas roda o modelo normalmente (testado com claude-fable-5-2).
|
||||
/\[claude-code:unrecognized_model\]/];
|
||||
|
||||
// --- normalização ---------------------------------------------------------------
|
||||
|
||||
type Block = { type?: string; text?: string; name?: string; input?: Record<string, unknown>; content?: unknown; is_error?: boolean };
|
||||
|
||||
function normalizeClaude(o: Record<string, unknown>, runId: number): Omit<AgentEvent, "at">[] {
|
||||
switch (o.type) {
|
||||
case "system":
|
||||
if (o.subtype === "init") {
|
||||
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.session_id), runId);
|
||||
return [{ kind: "system", text: `sessão iniciada · modelo ${o.model}` }];
|
||||
}
|
||||
return [];
|
||||
case "assistant":
|
||||
return ((o.message as { content?: Block[] })?.content ?? []).flatMap((c): Omit<AgentEvent, "at">[] => {
|
||||
if (c.type === "text" && c.text?.trim()) return [{ kind: "text", text: c.text }];
|
||||
if (c.type === "tool_use") return [{ kind: "tool", text: `${c.name} ${summarizeInput(c.input)}` }];
|
||||
return [];
|
||||
});
|
||||
case "user":
|
||||
return ((o.message as { content?: Block[] | string })?.content instanceof Array
|
||||
? (o.message as { content: Block[] }).content : [])
|
||||
.filter((c) => c.type === "tool_result")
|
||||
.map((c) => ({ kind: "tool_result" as const, text: truncate(stringify(c.content), 1500), isError: !!c.is_error }));
|
||||
case "result": {
|
||||
const denials = (o.permission_denials as unknown[] | undefined)?.length ?? 0;
|
||||
run(`UPDATE agent_runs SET cost_usd = ?, num_turns = ?, result = ?, error = ?, session_id = COALESCE(session_id, ?)
|
||||
WHERE id = ?`, Number(o.total_cost_usd ?? 0), Number(o.num_turns ?? 0), String(o.result ?? "").slice(0, 20_000),
|
||||
// Erro com subtype "success" (ex.: limite de uso) traz o motivo em "result": guarde o texto.
|
||||
o.is_error
|
||||
? (o.subtype === "error_max_budget_usd"
|
||||
? "Parou no teto de gasto desta tarefa (--max-budget-usd). Continue a conversa para seguir."
|
||||
: o.subtype && o.subtype !== "success" ? String(o.subtype) : String(o.result ?? "erro").slice(0, 500))
|
||||
: null,
|
||||
String(o.session_id ?? ""), runId);
|
||||
return [{
|
||||
kind: "result", text: `${o.is_error ? "Terminou com erro" : "Concluído"} · ${o.num_turns} turnos · US$ ${Number(o.total_cost_usd ?? 0).toFixed(4)}` +
|
||||
(denials ? ` · ${denials} ação(ões) bloqueada(s) pelas permissões` : ""),
|
||||
isError: !!o.is_error, costUsd: Number(o.total_cost_usd ?? 0), turns: Number(o.num_turns ?? 0),
|
||||
}];
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
type CodexItem = {
|
||||
type?: string; text?: string; message?: string; command?: string; aggregated_output?: string;
|
||||
exit_code?: number | null; status?: string; changes?: { path?: string; kind?: string }[];
|
||||
server?: string; tool?: string; query?: string;
|
||||
};
|
||||
|
||||
/** Eventos JSONL do `codex exec --json` (formato verificado com codex-cli 0.169.0). */
|
||||
function normalizeCodex(o: Record<string, unknown>, runId: number): Omit<AgentEvent, "at">[] {
|
||||
const item = (o.item ?? {}) as CodexItem;
|
||||
switch (o.type) {
|
||||
case "thread.started":
|
||||
run("UPDATE agent_runs SET session_id = ? WHERE id = ?", String(o.thread_id), runId);
|
||||
return [{ kind: "system", text: "sessão iniciada" }];
|
||||
case "item.started":
|
||||
return item.type === "command_execution" ? [{ kind: "tool", text: `$ ${truncate(stripShell(item.command ?? ""), 200)}` }] : [];
|
||||
case "item.completed":
|
||||
switch (item.type) {
|
||||
case "agent_message":
|
||||
run("UPDATE agent_runs SET result = ? WHERE id = ?", String(item.text ?? "").slice(0, 20_000), runId);
|
||||
return item.text?.trim() ? [{ kind: "text", text: item.text }] : [];
|
||||
case "command_execution":
|
||||
return [{ kind: "tool_result", text: truncate(item.aggregated_output ?? "", 1500) || "(sem saída)", isError: (item.exit_code ?? 0) !== 0 }];
|
||||
case "file_change":
|
||||
return [{ kind: "tool", text: `arquivos: ${(item.changes ?? []).map((c) => `${c.kind ?? "edit"} ${String(c.path ?? "").replace(REPO_ROOT, ".")}`).join(", ")}` }];
|
||||
case "mcp_tool_call":
|
||||
return [{ kind: "tool", text: `MCP ${item.server ?? ""} ${item.tool ?? ""}` }];
|
||||
case "web_search":
|
||||
return [{ kind: "tool", text: `busca: ${item.query ?? ""}` }];
|
||||
case "error":
|
||||
// Avisos de configuração do usuário chegam como "error" mas não interrompem.
|
||||
return [{ kind: "system", text: truncate(item.message ?? "", 300) }];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
case "turn.completed": {
|
||||
const u = (o.usage ?? {}) as { input_tokens?: number; cached_input_tokens?: number; output_tokens?: number };
|
||||
run("UPDATE agent_runs SET num_turns = COALESCE(num_turns, 0) + 1 WHERE id = ?", runId);
|
||||
return [{ kind: "result", text: `Concluído · ${u.input_tokens ?? 0} tokens de entrada (${u.cached_input_tokens ?? 0} em cache) · ${u.output_tokens ?? 0} de saída · Codex não informa custo em US$` }];
|
||||
}
|
||||
case "turn.failed":
|
||||
case "error": {
|
||||
const message = String((o.error as { message?: string } | undefined)?.message ?? o.message ?? "falha");
|
||||
run("UPDATE agent_runs SET error = ? WHERE id = ?", message.slice(0, 2000), runId);
|
||||
return [{ kind: "result", text: `Terminou com erro: ${truncate(message, 300)}`, isError: true }];
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function stripShell(command: string): string {
|
||||
// `"...powershell.exe" -Command '...'` → só o comando interno
|
||||
const m = /-Command '([\s\S]*)'$/.exec(command);
|
||||
return m ? m[1] : command;
|
||||
}
|
||||
|
||||
function summarizeInput(input: Record<string, unknown> | undefined): string {
|
||||
if (!input) return "";
|
||||
const v = input.file_path ?? input.path ?? input.pattern ?? input.command ?? input.description ?? input.skill;
|
||||
return v ? truncate(String(v).replace(REPO_ROOT, "."), 200) : truncate(JSON.stringify(input), 200);
|
||||
}
|
||||
|
||||
function stringify(content: unknown): string {
|
||||
if (typeof content === "string") return content;
|
||||
if (Array.isArray(content)) return content.map((c) => (typeof c === "object" && c && "text" in c ? String((c as { text: unknown }).text) : "")).join("\n");
|
||||
return JSON.stringify(content ?? "");
|
||||
}
|
||||
|
||||
function truncate(s: string, n: number): string {
|
||||
return s.length > n ? s.slice(0, n) + "…" : s;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Repositório de assets em dois níveis:
|
||||
// - da história: stories/<história>/assets/<tipo>/<asset-id>/ (só aquela história usa)
|
||||
// - biblioteca: assets/library/<tipo>/<asset-id>/ (qualquer história usa)
|
||||
// Cada pasta de asset tem o arquivo e um asset.json com os metadados. Um asset da história
|
||||
// pode ser promovido para a biblioteca (a pasta é movida e o registro atualizado).
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { LIBRARY_DIR, REPO_ROOT, rel, slugify, storyAssetsDir } from "./paths";
|
||||
import { UserError, getStory, touchStory } from "./stories";
|
||||
import type { Asset, AssetKind } from "./types";
|
||||
|
||||
export const ASSET_KINDS: { id: AssetKind; label: string; extensions: string[] }[] = [
|
||||
{ id: "model", label: "Modelo 3D", extensions: [".glb", ".gltf"] },
|
||||
{ id: "texture", label: "Textura", extensions: [".png", ".jpg", ".jpeg", ".webp"] },
|
||||
{ id: "background", label: "Fundo / fachada", extensions: [".png", ".jpg", ".jpeg", ".webp"] },
|
||||
{ id: "image", label: "Imagem (foto, ilustração)", extensions: [".png", ".jpg", ".jpeg", ".webp"] },
|
||||
{ id: "video", label: "Clipe de vídeo", extensions: [".mp4", ".mov", ".webm", ".mkv"] },
|
||||
{ id: "audio", label: "Áudio", extensions: [".wav", ".mp3", ".ogg", ".m4a", ".flac"] },
|
||||
{ id: "other", label: "Outro", extensions: [".png", ".jpg", ".jpeg", ".webp", ".glb", ".gltf", ".wav", ".mp3", ".json", ".txt"] },
|
||||
];
|
||||
const MAX_BYTES = 300 * 1024 * 1024;
|
||||
|
||||
export function listAssets(filter: { storyId?: string; scope?: "library" | "story" } = {}): Asset[] {
|
||||
if (filter.storyId) {
|
||||
return all<Asset>("SELECT * FROM assets WHERE scope = 'library' OR story_id = ? ORDER BY scope, kind, name", filter.storyId);
|
||||
}
|
||||
if (filter.scope) return all<Asset>("SELECT * FROM assets WHERE scope = ? ORDER BY kind, name", filter.scope);
|
||||
return all<Asset>("SELECT * FROM assets ORDER BY scope, story_id, kind, name");
|
||||
}
|
||||
|
||||
export async function createAsset(input: {
|
||||
file: File; name: string; kind: AssetKind; scope: "library" | "story"; storyId?: string;
|
||||
license: string; source: string; notes: string;
|
||||
}): Promise<Asset> {
|
||||
const kind = ASSET_KINDS.find((k) => k.id === input.kind);
|
||||
if (!kind) throw new UserError("Tipo de asset inválido.");
|
||||
const name = input.name.trim();
|
||||
if (name.length < 2 || name.length > 80) throw new UserError("Nome precisa ter entre 2 e 80 caracteres.");
|
||||
const ext = path.extname(input.file.name).toLowerCase();
|
||||
if (!kind.extensions.includes(ext)) throw new UserError(`Extensão ${ext || "(nenhuma)"} não aceita para ${kind.label}: ${kind.extensions.join(", ")}.`);
|
||||
if (input.file.size === 0 || input.file.size > MAX_BYTES) throw new UserError("Arquivo vazio ou maior que 300 MB.");
|
||||
if (input.scope === "story" && (!input.storyId || !getStory(input.storyId))) throw new UserError("Escolha a história do asset.");
|
||||
if (!input.license.trim()) throw new UserError("Informe a licença/origem de uso (ex.: próprio, CC0, gerado no Meshy).");
|
||||
|
||||
const base = slugify(name) || "asset";
|
||||
let id = base;
|
||||
for (let n = 2; get("SELECT 1 FROM assets WHERE id = ?", id); n++) id = `${base}-${n}`;
|
||||
|
||||
const dir = assetDir(input.scope, input.storyId ?? null, input.kind, id);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
// Caminho decidido em tempo de execução (upload do usuário): fora do rastreamento do build.
|
||||
const target = path.join(/*turbopackIgnore: true*/ dir, `${id}${ext}`);
|
||||
fs.writeFileSync(target, Buffer.from(await input.file.arrayBuffer()));
|
||||
const ts = now();
|
||||
run(`INSERT INTO assets (id, scope, story_id, kind, name, version, file_path, license, source, notes, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)`,
|
||||
id, input.scope, input.scope === "story" ? input.storyId! : null, input.kind, name, rel(target),
|
||||
input.license.trim().slice(0, 200), input.source.trim().slice(0, 200), input.notes.trim().slice(0, 1000), ts, ts);
|
||||
if (input.storyId) touchStory(input.storyId);
|
||||
const asset = get<Asset>("SELECT * FROM assets WHERE id = ?", id)!;
|
||||
writeManifest(dir, asset);
|
||||
return asset;
|
||||
}
|
||||
|
||||
/** Move um asset da história para a biblioteca compartilhada. */
|
||||
export function promoteAsset(id: string): Asset {
|
||||
const asset = get<Asset>("SELECT * FROM assets WHERE id = ?", id);
|
||||
if (!asset) throw new UserError("Asset não encontrado.");
|
||||
if (asset.scope === "library") throw new UserError("Este asset já está na biblioteca.");
|
||||
const from = path.dirname(path.join(REPO_ROOT, asset.file_path));
|
||||
const to = assetDir("library", null, asset.kind, asset.id);
|
||||
if (fs.existsSync(to)) throw new UserError(`Já existe ${rel(to)} na biblioteca.`);
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true });
|
||||
fs.renameSync(from, to);
|
||||
const filePath = rel(path.join(to, path.basename(asset.file_path)));
|
||||
run("UPDATE assets SET scope = 'library', story_id = NULL, file_path = ?, updated_at = ? WHERE id = ?", filePath, now(), id);
|
||||
const updated = get<Asset>("SELECT * FROM assets WHERE id = ?", id)!;
|
||||
writeManifest(to, { ...updated, notes: `${updated.notes}\nPromovido da história ${asset.story_id} em ${updated.updated_at}.`.trim() });
|
||||
return updated;
|
||||
}
|
||||
|
||||
function assetDir(scope: "library" | "story", storyId: string | null, kind: AssetKind, id: string): string {
|
||||
return scope === "library" ? path.join(LIBRARY_DIR, kind, id) : path.join(storyAssetsDir(storyId!), kind, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* asset.json acompanha o arquivo para que agentes e a Godot leiam os metadados sem o banco.
|
||||
* Escala, orientação e capacidades ficam "a definir" até o asset ser testado num render
|
||||
* (um modelo com rig de andar não está automaticamente pronto para pilotar moto).
|
||||
*/
|
||||
function writeManifest(dir: string, a: Asset): void {
|
||||
const manifest = {
|
||||
id: a.id, version: a.version, kind: a.kind, name: a.name,
|
||||
file: path.basename(a.file_path), scope: a.scope, story: a.story_id,
|
||||
license: a.license, source: a.source, notes: a.notes,
|
||||
scale: "a definir", orientation: "a definir", capabilities: [], testedInRender: false,
|
||||
createdAt: a.created_at, updatedAt: a.updated_at,
|
||||
};
|
||||
fs.writeFileSync(path.join(dir, "asset.json"), JSON.stringify(manifest, null, 2) + "\n");
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Preparo das vertentes de um episódio pela IA ("só o próximo nível").
|
||||
//
|
||||
// Uma única execução de agente escreve TODAS as vertentes do nível seguinte (contexto compartilhado,
|
||||
// menos tokens que N execuções): o texto de cada opção em <file_key>.choices.json, e o roteiro e a cena
|
||||
// de cada vertente. O vídeo não é gerado aqui.
|
||||
//
|
||||
// O executor de agentes roda um por vez: se estiver ocupado, o episódio fica `queued` e começa quando
|
||||
// a execução atual terminar (onAgentRunClosed).
|
||||
import { busy, defaultModelFor, defaultProviderFor, startRun } from "./agents";
|
||||
import { all, get, run } from "./db";
|
||||
import { episodeChoicesPath, readTextIfExists } from "./paths";
|
||||
import { UserError, childEpisodes, ensureCandidates, getEpisodeById, getStory, touchStory } from "./stories";
|
||||
import type { Episode } from "./types";
|
||||
|
||||
const MAX_LABEL = 60; // cabe no overlay vertical (o roteirista já respeita o limite)
|
||||
|
||||
export function prepareBranches(episodeId: number, options: { auto?: boolean; regenerate?: boolean } = {}): Episode {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Episódio não encontrado.");
|
||||
const story = getStory(ep.story_id)!;
|
||||
if (story.kind !== "interactive") throw new UserError("Só histórias interativas têm vertentes.");
|
||||
if (story.status === "finished") throw new UserError("A história foi encerrada.");
|
||||
if (ep.status !== "main") throw new UserError("Só o episódio do caminho principal prepara vertentes (próximo nível).");
|
||||
if (ep.decision) throw new UserError("A votação deste episódio já foi fechada.");
|
||||
if (!ep.hasScript) throw new UserError("Escreva o roteiro deste episódio antes de preparar as vertentes.");
|
||||
if (ep.branches_status === "running" || ep.branches_status === "queued") {
|
||||
if (options.auto) return get<Episode>("SELECT * FROM episodes WHERE id = ?", episodeId)!;
|
||||
throw new UserError("As vertentes deste episódio já estão sendo preparadas.");
|
||||
}
|
||||
if (ep.branches_status === "ready" && !options.regenerate) {
|
||||
throw new UserError("As vertentes já estão prontas. Use 'gerar de novo' para refazer.");
|
||||
}
|
||||
ensureCandidates(episodeId);
|
||||
if (busy()) {
|
||||
run("UPDATE episodes SET branches_status = 'queued' WHERE id = ?", episodeId);
|
||||
} else {
|
||||
start(episodeId);
|
||||
}
|
||||
touchStory(story.id);
|
||||
return get<Episode>("SELECT * FROM episodes WHERE id = ?", episodeId)!;
|
||||
}
|
||||
|
||||
function start(episodeId: number): void {
|
||||
const ep = getEpisodeById(episodeId)!;
|
||||
const story = getStory(ep.story_id)!;
|
||||
const provider = defaultProviderFor("branches");
|
||||
try {
|
||||
const agent = startRun({
|
||||
provider,
|
||||
model: defaultModelFor("branches", provider),
|
||||
kind: "branches",
|
||||
request: `Prepare as ${story.branch_count} vertentes do episódio ${ep.file_key} ("${ep.title || "sem título"}").`,
|
||||
storyId: story.id,
|
||||
episodeId,
|
||||
});
|
||||
run("UPDATE episodes SET branches_status = 'running', branches_run_id = ? WHERE id = ?", agent.id, episodeId);
|
||||
} catch (error) {
|
||||
run("UPDATE episodes SET branches_status = 'error' WHERE id = ?", episodeId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Chamado pelo executor quando qualquer execução termina: fecha o preparo dela e puxa a fila. */
|
||||
export function onAgentRunClosed(runId: number, ok: boolean): void {
|
||||
const owner = get<Episode>("SELECT * FROM episodes WHERE branches_run_id = ? AND branches_status = 'running'", runId);
|
||||
if (owner) {
|
||||
const ready = ok && syncBranchLabels(owner);
|
||||
run("UPDATE episodes SET branches_status = ? WHERE id = ?", ready ? "ready" : "error", owner.id);
|
||||
touchStory(owner.story_id);
|
||||
}
|
||||
const next = all<Episode>("SELECT * FROM episodes WHERE branches_status = 'queued' ORDER BY id LIMIT 1")[0];
|
||||
if (next && !busy()) {
|
||||
try {
|
||||
start(next.id);
|
||||
} catch (error) {
|
||||
console.warn(`fila de vertentes: ${next.file_key} não começou: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lê <file_key>.choices.json ({"A": "texto", ...}) e grava o texto em cada vertente filha.
|
||||
* Pronto = todas as vertentes têm texto e roteiro.
|
||||
*/
|
||||
function syncBranchLabels(parent: Episode): boolean {
|
||||
const text = readTextIfExists(episodeChoicesPath(parent.story_id, parent.file_key));
|
||||
let labels: Record<string, unknown> = {};
|
||||
try {
|
||||
labels = text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
labels = {};
|
||||
}
|
||||
let complete = true;
|
||||
for (const child of childEpisodes(parent.id)) {
|
||||
const raw = labels[child.parent_choice ?? ""];
|
||||
const label = typeof raw === "string" ? raw.trim().replace(/\s+/g, " ").slice(0, MAX_LABEL) : "";
|
||||
if (label) run("UPDATE episodes SET branch_label = ? WHERE id = ?", label, child.id);
|
||||
const view = getEpisodeById(child.id);
|
||||
if (!label || !view?.hasScript) complete = false;
|
||||
}
|
||||
return complete;
|
||||
}
|
||||
@@ -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." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
// SQLite local (node:sqlite, embutido no Node 24 — sem dependência nativa).
|
||||
// O banco guarda metadados e estado; conteúdo (roteiros, cenas JSON, arquivos de asset,
|
||||
// vídeos) fica em arquivos no repositório, referenciados por caminho relativo.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync, type SQLInputValue } from "node:sqlite";
|
||||
import { DATA_DIR } from "./paths";
|
||||
|
||||
export const MIGRATIONS: string[] = [
|
||||
// v1
|
||||
`
|
||||
CREATE TABLE stories (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
logline TEXT NOT NULL DEFAULT '',
|
||||
kind TEXT NOT NULL CHECK (kind IN ('interactive', 'linear')),
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE episodes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
story_id TEXT NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
|
||||
number INTEGER NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
parent_episode_id INTEGER REFERENCES episodes(id),
|
||||
parent_choice TEXT CHECK (parent_choice IN ('A', 'B')),
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE (story_id, number)
|
||||
);
|
||||
CREATE TABLE renders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
episode_id INTEGER REFERENCES episodes(id) ON DELETE SET NULL,
|
||||
config_path TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
run_dir TEXT,
|
||||
mp4 TEXT,
|
||||
error TEXT,
|
||||
log_path TEXT,
|
||||
started_at TEXT NOT NULL,
|
||||
finished_at TEXT
|
||||
);
|
||||
CREATE TABLE assets (
|
||||
id TEXT PRIMARY KEY,
|
||||
scope TEXT NOT NULL CHECK (scope IN ('library', 'story')),
|
||||
story_id TEXT REFERENCES stories(id) ON DELETE SET NULL,
|
||||
kind TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
file_path TEXT NOT NULL,
|
||||
license TEXT NOT NULL DEFAULT '',
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE comments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
episode_id INTEGER NOT NULL REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
source TEXT NOT NULL,
|
||||
external_id TEXT NOT NULL,
|
||||
author_id TEXT NOT NULL,
|
||||
author_name TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
choice TEXT CHECK (choice IN ('A', 'B')),
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE (episode_id, source, external_id)
|
||||
);
|
||||
CREATE TABLE decisions (
|
||||
episode_id INTEGER PRIMARY KEY REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
closed_at TEXT NOT NULL,
|
||||
votes_a INTEGER NOT NULL,
|
||||
votes_b INTEGER NOT NULL,
|
||||
winner TEXT NOT NULL CHECK (winner IN ('A', 'B')),
|
||||
method TEXT NOT NULL CHECK (method IN ('votes', 'manual')),
|
||||
rule TEXT NOT NULL,
|
||||
snapshot_json TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE agent_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider TEXT NOT NULL,
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
kind TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
story_id TEXT REFERENCES stories(id) ON DELETE SET NULL,
|
||||
episode_id INTEGER REFERENCES episodes(id) ON DELETE SET NULL,
|
||||
resume_of INTEGER REFERENCES agent_runs(id),
|
||||
status TEXT NOT NULL,
|
||||
session_id TEXT,
|
||||
cost_usd REAL,
|
||||
num_turns INTEGER,
|
||||
result TEXT,
|
||||
error TEXT,
|
||||
log_path TEXT NOT NULL,
|
||||
started_at TEXT NOT NULL,
|
||||
finished_at TEXT
|
||||
);
|
||||
`,
|
||||
// v2 — fluxo de vertentes (1–4 opções por decisão), contas vinculadas e métricas de publicação.
|
||||
// SQLite não altera CHECK: episodes, comments e decisions são reconstruídas (ids preservados).
|
||||
`
|
||||
ALTER TABLE stories ADD COLUMN branch_count INTEGER NOT NULL DEFAULT 2 CHECK (branch_count BETWEEN 1 AND 4);
|
||||
ALTER TABLE stories ADD COLUMN status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'finished'));
|
||||
|
||||
CREATE TABLE episodes_v2 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
story_id TEXT NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
|
||||
number INTEGER NOT NULL, -- nível na história (1 = início)
|
||||
file_key TEXT NOT NULL, -- nome dos arquivos: ep01, ep02-b
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
parent_episode_id INTEGER REFERENCES episodes_v2(id),
|
||||
parent_choice TEXT CHECK (parent_choice IN ('A', 'B', 'C', 'D')),
|
||||
branch_label TEXT NOT NULL DEFAULT '', -- texto da opção que leva a este episódio
|
||||
status TEXT NOT NULL DEFAULT 'main' CHECK (status IN ('main', 'candidate', 'discarded')),
|
||||
branches_status TEXT NOT NULL DEFAULT 'none'
|
||||
CHECK (branches_status IN ('none', 'queued', 'running', 'ready', 'error')),
|
||||
branches_run_id INTEGER,
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE (story_id, file_key)
|
||||
);
|
||||
INSERT INTO episodes_v2 (id, story_id, number, file_key, title, parent_episode_id, parent_choice, created_at)
|
||||
SELECT id, story_id, number, printf('ep%02d', number), title, parent_episode_id, parent_choice, created_at FROM episodes;
|
||||
DROP TABLE episodes;
|
||||
ALTER TABLE episodes_v2 RENAME TO episodes;
|
||||
CREATE INDEX episodes_parent ON episodes(parent_episode_id);
|
||||
|
||||
CREATE TABLE comments_v2 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
episode_id INTEGER NOT NULL REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
source TEXT NOT NULL,
|
||||
external_id TEXT NOT NULL,
|
||||
author_id TEXT NOT NULL,
|
||||
author_name TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
choice TEXT CHECK (choice IN ('A', 'B', 'C', 'D')),
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE (episode_id, source, external_id)
|
||||
);
|
||||
INSERT INTO comments_v2 SELECT * FROM comments;
|
||||
DROP TABLE comments;
|
||||
ALTER TABLE comments_v2 RENAME TO comments;
|
||||
|
||||
CREATE TABLE decisions_v2 (
|
||||
episode_id INTEGER PRIMARY KEY REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
closed_at TEXT NOT NULL,
|
||||
votes_json TEXT NOT NULL, -- {"A": 3, "B": 5, ...}
|
||||
winner TEXT NOT NULL CHECK (winner IN ('A', 'B', 'C', 'D')),
|
||||
method TEXT NOT NULL CHECK (method IN ('votes', 'manual')),
|
||||
rule TEXT NOT NULL,
|
||||
snapshot_json TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO decisions_v2 (episode_id, closed_at, votes_json, winner, method, rule, snapshot_json)
|
||||
SELECT episode_id, closed_at, json_object('A', votes_a, 'B', votes_b), winner, method, rule, snapshot_json FROM decisions;
|
||||
DROP TABLE decisions;
|
||||
ALTER TABLE decisions_v2 RENAME TO decisions;
|
||||
|
||||
CREATE TABLE accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
niche TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE account_networks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
handle TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'mock' CHECK (status IN ('mock', 'connected', 'error')),
|
||||
connected_at TEXT NOT NULL,
|
||||
UNIQUE (account_id, platform)
|
||||
);
|
||||
CREATE TABLE account_stories (
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
story_id TEXT NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'ended')),
|
||||
linked_at TEXT NOT NULL,
|
||||
ended_at TEXT,
|
||||
PRIMARY KEY (account_id, story_id)
|
||||
);
|
||||
CREATE TABLE publications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
episode_id INTEGER NOT NULL REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
url TEXT NOT NULL DEFAULT '',
|
||||
published_at TEXT NOT NULL,
|
||||
simulated INTEGER NOT NULL DEFAULT 1,
|
||||
UNIQUE (episode_id, account_id, platform)
|
||||
);
|
||||
CREATE TABLE publication_metrics (
|
||||
publication_id INTEGER NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
|
||||
captured_at TEXT NOT NULL,
|
||||
views INTEGER NOT NULL DEFAULT 0,
|
||||
likes INTEGER NOT NULL DEFAULT 0,
|
||||
comments INTEGER NOT NULL DEFAULT 0,
|
||||
shares INTEGER NOT NULL DEFAULT 0,
|
||||
saves INTEGER NOT NULL DEFAULT 0,
|
||||
avg_watch_s REAL,
|
||||
completion_rate REAL,
|
||||
simulated INTEGER NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (publication_id, captured_at)
|
||||
);
|
||||
`,
|
||||
// v3: canais de live do Clipador ligados às contas, como as histórias. O canal vive no banco do Clipador
|
||||
// (data/clipper/clipper.db, id "twitch-alanzoka"): aqui fica só o vínculo, sem chave estrangeira.
|
||||
`
|
||||
CREATE TABLE account_channels (
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
channel_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'ended')),
|
||||
linked_at TEXT NOT NULL,
|
||||
ended_at TEXT,
|
||||
PRIMARY KEY (account_id, channel_id)
|
||||
);
|
||||
`,
|
||||
// v4: formato "documentary" (vídeo único sobre fatos reais). SQLite não altera CHECK: stories é
|
||||
// reconstruída com as mesmas colunas e ids; as chaves estrangeiras das outras tabelas apontam pelo nome.
|
||||
`
|
||||
CREATE TABLE stories_v4 (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
logline TEXT NOT NULL DEFAULT '',
|
||||
kind TEXT NOT NULL CHECK (kind IN ('interactive', 'linear', 'documentary')),
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
branch_count INTEGER NOT NULL DEFAULT 2 CHECK (branch_count BETWEEN 1 AND 4),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'finished'))
|
||||
);
|
||||
INSERT INTO stories_v4 (id, title, logline, kind, created_at, updated_at, branch_count, status)
|
||||
SELECT id, title, logline, kind, created_at, updated_at, branch_count, status FROM stories;
|
||||
DROP TABLE stories;
|
||||
ALTER TABLE stories_v4 RENAME TO stories;
|
||||
`,
|
||||
// v5: publicação real (doc/publicacao/PLANO.md, seção 4). account_networks e publications são reconstruídas
|
||||
// (SQLite não altera CHECK/NOT NULL); ids preservados, então publication_metrics continua apontando certo.
|
||||
// Perfis que eram só "simulados" (mock) — ou marcados conectados sem integração — voltam a "disconnected".
|
||||
`
|
||||
CREATE TABLE account_networks_v5 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
handle TEXT, -- NULL até a rede informar
|
||||
status TEXT NOT NULL DEFAULT 'disconnected'
|
||||
CHECK (status IN ('disconnected', 'connecting', 'connected', 'needs_login', 'expired', 'error')),
|
||||
connected_at TEXT,
|
||||
mode TEXT CHECK (mode IN ('official', 'session')),
|
||||
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)),
|
||||
daily_limit INTEGER NOT NULL DEFAULT 3 CHECK (daily_limit BETWEEN 1 AND 20),
|
||||
privacy TEXT NOT NULL DEFAULT 'public' CHECK (privacy IN ('public', 'unlisted', 'private')),
|
||||
tiktok_mode TEXT NOT NULL DEFAULT 'direct' CHECK (tiktok_mode IN ('direct', 'draft')),
|
||||
display_name TEXT,
|
||||
last_error TEXT,
|
||||
checked_at TEXT,
|
||||
expires_at TEXT,
|
||||
UNIQUE (account_id, platform)
|
||||
);
|
||||
INSERT INTO account_networks_v5 (id, account_id, platform, handle, status, connected_at)
|
||||
SELECT id, account_id, platform, handle, 'disconnected', NULL FROM account_networks;
|
||||
DROP TABLE account_networks;
|
||||
ALTER TABLE account_networks_v5 RENAME TO account_networks;
|
||||
|
||||
ALTER TABLE accounts ADD COLUMN approval_mode TEXT NOT NULL DEFAULT 'manual' CHECK (approval_mode IN ('manual', 'auto'));
|
||||
ALTER TABLE accounts ADD COLUMN timing TEXT NOT NULL DEFAULT 'best_slot' CHECK (timing IN ('now', 'best_slot'));
|
||||
ALTER TABLE accounts ADD COLUMN ai_label TEXT NOT NULL DEFAULT 'auto' CHECK (ai_label IN ('auto', 'always', 'never'));
|
||||
-- Quando a aprovação automática foi ligada: cortes mais antigos que isso nunca são aprovados sozinhos.
|
||||
ALTER TABLE accounts ADD COLUMN auto_since TEXT;
|
||||
|
||||
ALTER TABLE episodes ADD COLUMN approved_at TEXT;
|
||||
ALTER TABLE episodes ADD COLUMN approved_render_id INTEGER REFERENCES renders(id) ON DELETE SET NULL;
|
||||
ALTER TABLE episodes ADD COLUMN publish_title TEXT;
|
||||
ALTER TABLE episodes ADD COLUMN publish_caption TEXT;
|
||||
|
||||
CREATE TABLE publish_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
source_kind TEXT NOT NULL CHECK (source_kind IN ('clip', 'episode')),
|
||||
source_id TEXT NOT NULL, -- id do corte no Clipador ou id do episódio
|
||||
source_label TEXT NOT NULL DEFAULT '', -- fonte do corte (twitch-alanzoka) ou história/episódio
|
||||
file TEXT NOT NULL, -- MP4, relativo à raiz do repositório
|
||||
cover TEXT,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
caption TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL CHECK (status IN ('awaiting_approval', 'scheduled', 'queued', 'publishing', 'published', 'failed', 'needs_login', 'canceled')),
|
||||
scheduled_at TEXT,
|
||||
publisher_job_id TEXT,
|
||||
step TEXT NOT NULL DEFAULT '',
|
||||
progress REAL NOT NULL DEFAULT 0,
|
||||
remote_id TEXT,
|
||||
url TEXT,
|
||||
draft INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
cancel_reason TEXT CHECK (cancel_reason IN ('user', 'source_changed', 'unapproved')),
|
||||
published_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
UNIQUE (account_id, platform, source_kind, source_id)
|
||||
);
|
||||
CREATE INDEX publish_jobs_status ON publish_jobs(status, scheduled_at);
|
||||
|
||||
CREATE TABLE publications_v5 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
episode_id INTEGER REFERENCES episodes(id) ON DELETE CASCADE,
|
||||
clip_id INTEGER, -- corte do Clipador (vive no banco dele, sem chave estrangeira)
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
url TEXT NOT NULL DEFAULT '',
|
||||
published_at TEXT NOT NULL,
|
||||
simulated INTEGER NOT NULL DEFAULT 1,
|
||||
job_id INTEGER REFERENCES publish_jobs(id) ON DELETE SET NULL,
|
||||
CHECK (episode_id IS NOT NULL OR clip_id IS NOT NULL),
|
||||
UNIQUE (episode_id, account_id, platform)
|
||||
);
|
||||
INSERT INTO publications_v5 (id, episode_id, account_id, platform, url, published_at, simulated)
|
||||
SELECT id, episode_id, account_id, platform, url, published_at, simulated FROM publications;
|
||||
DROP TABLE publications;
|
||||
ALTER TABLE publications_v5 RENAME TO publications;
|
||||
CREATE UNIQUE INDEX publications_clip ON publications(clip_id, account_id, platform) WHERE clip_id IS NOT NULL;
|
||||
|
||||
CREATE TABLE app_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO app_settings (key, value) VALUES
|
||||
('publishing_paused', '0'),
|
||||
('slots', '{"youtube":["12:00","15:00","19:00"],"tiktok":["08:00","12:00","19:00","21:00"],"instagram":["12:00","19:00","21:00"]}'),
|
||||
('timezone', 'America/Sao_Paulo');
|
||||
|
||||
-- Cortes que o PRÓPRIO despachante aprovou no Clipador (canal com aprovação automática). Servem para não
|
||||
-- confundir essa aprovação com a de um humano: canais manuais continuam esperando você.
|
||||
CREATE TABLE clip_auto_approvals (
|
||||
clip_id INTEGER PRIMARY KEY,
|
||||
approved_at TEXT NOT NULL
|
||||
);
|
||||
`,
|
||||
// v6: publish_jobs reconstruída (SQLite não altera CHECK) para o motivo de cancelamento 'unlinked' (fonte ou
|
||||
// história desligada do canal) e a origem do horário: auto (agenda do despachante — pode ser reencaixado se o
|
||||
// painel ficou fechado), manual (escolhido por você) ou now ("Publicar agora"/"Tentar de novo"). Ids preservados.
|
||||
`
|
||||
CREATE TABLE publish_jobs_v6 (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
source_kind TEXT NOT NULL CHECK (source_kind IN ('clip', 'episode')),
|
||||
source_id TEXT NOT NULL,
|
||||
source_label TEXT NOT NULL DEFAULT '',
|
||||
file TEXT NOT NULL,
|
||||
cover TEXT,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
caption TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL CHECK (status IN ('awaiting_approval', 'scheduled', 'queued', 'publishing', 'published', 'failed', 'needs_login', 'canceled')),
|
||||
scheduled_at TEXT,
|
||||
schedule_source TEXT NOT NULL DEFAULT 'auto' CHECK (schedule_source IN ('auto', 'manual', 'now')),
|
||||
publisher_job_id TEXT,
|
||||
step TEXT NOT NULL DEFAULT '',
|
||||
progress REAL NOT NULL DEFAULT 0,
|
||||
remote_id TEXT,
|
||||
url TEXT,
|
||||
draft INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT,
|
||||
attempts INTEGER NOT NULL DEFAULT 0, -- sobe só em nova tentativa explícita; clientRef = "<id>:<attempts>"
|
||||
cancel_reason TEXT CHECK (cancel_reason IN ('user', 'source_changed', 'unapproved', 'unlinked')),
|
||||
published_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
UNIQUE (account_id, platform, source_kind, source_id)
|
||||
);
|
||||
INSERT INTO publish_jobs_v6 (id, account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status,
|
||||
scheduled_at, publisher_job_id, step, progress, remote_id, url, draft, error, attempts, cancel_reason, published_at, created_at, updated_at)
|
||||
SELECT id, account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status,
|
||||
scheduled_at, publisher_job_id, step, progress, remote_id, url, draft, error, attempts, cancel_reason, published_at, created_at, updated_at
|
||||
FROM publish_jobs;
|
||||
DROP TABLE publish_jobs;
|
||||
ALTER TABLE publish_jobs_v6 RENAME TO publish_jobs;
|
||||
CREATE INDEX publish_jobs_status ON publish_jobs(status, scheduled_at);
|
||||
`,
|
||||
// v7: origem do job. 'link' = criado pelo despachante (fonte ou história ligada ao canal); 'manual' = você mandou
|
||||
// publicar este corte neste canal ("Publicar" no cartão do Clipador) — não é cancelado por "fonte desligada".
|
||||
`
|
||||
ALTER TABLE publish_jobs ADD COLUMN origin TEXT NOT NULL DEFAULT 'link' CHECK (origin IN ('link', 'manual'));
|
||||
`,
|
||||
// v8: última leitura dos números (views, curtidas, comentários) de cada rede de cada canal, pelo Publicador
|
||||
// (lib/metrics-sync.ts). Os números em si vão para publication_metrics (simulated = 0).
|
||||
`
|
||||
CREATE TABLE metric_syncs (
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
platform TEXT NOT NULL CHECK (platform IN ('tiktok', 'instagram', 'youtube')),
|
||||
last_run_at TEXT,
|
||||
last_ok_at TEXT,
|
||||
last_error TEXT,
|
||||
read_count INTEGER NOT NULL DEFAULT 0,
|
||||
missing_count INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (account_id, platform)
|
||||
);
|
||||
`,
|
||||
];
|
||||
|
||||
const g = globalThis as unknown as { __cenaforgeDb?: DatabaseSync };
|
||||
|
||||
// O banco aberto fica no globalThis e sobrevive ao recarregamento do código (HMR do `pnpm dev`). Esta marca é do
|
||||
// MÓDULO: some a cada recarga, então a primeira chamada depois de uma atualização confere se há migração nova e
|
||||
// aplica no banco já aberto — sem precisar reiniciar o painel.
|
||||
let checkedThisModule = false;
|
||||
|
||||
export function db(): DatabaseSync {
|
||||
if (g.__cenaforgeDb && !checkedThisModule) {
|
||||
migrate(g.__cenaforgeDb);
|
||||
checkedThisModule = true;
|
||||
}
|
||||
if (!g.__cenaforgeDb) {
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
const database = new DatabaseSync(path.join(DATA_DIR, "cenaforge.db"));
|
||||
database.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 3000;");
|
||||
migrate(database);
|
||||
// Processos que estavam rodando quando o servidor caiu não terminam mais.
|
||||
database.exec(`UPDATE renders SET status = 'interrupted', finished_at = '${now()}' WHERE status = 'running';
|
||||
UPDATE agent_runs SET status = 'interrupted', finished_at = '${now()}' WHERE status = 'running';`);
|
||||
g.__cenaforgeDb = database;
|
||||
checkedThisModule = true;
|
||||
}
|
||||
return g.__cenaforgeDb;
|
||||
}
|
||||
|
||||
function migrate(database: DatabaseSync): void {
|
||||
const current = (database.prepare("PRAGMA user_version").get() as { user_version: number }).user_version;
|
||||
if (current >= MIGRATIONS.length) return;
|
||||
// Banco com dados: cópia antes de migrar (data/backups/), porque algumas migrações reconstroem tabelas.
|
||||
if (current > 0) {
|
||||
const backups = path.join(DATA_DIR, "backups");
|
||||
fs.mkdirSync(backups, { recursive: true });
|
||||
const file = path.join(backups, `cenaforge-v${current}-${now().replace(/[:.]/g, "-")}.db`);
|
||||
database.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`);
|
||||
}
|
||||
// Reconstruir tabela exige as chaves estrangeiras desligadas, e esse PRAGMA não vale dentro de transação.
|
||||
// A integridade é conferida (foreign_key_check) antes do COMMIT de cada versão.
|
||||
database.exec("PRAGMA foreign_keys = OFF");
|
||||
try {
|
||||
for (let v = current; v < MIGRATIONS.length; v++) {
|
||||
database.exec("BEGIN");
|
||||
try {
|
||||
database.exec(MIGRATIONS[v]);
|
||||
const broken = database.prepare("PRAGMA foreign_key_check").all();
|
||||
if (broken.length > 0) throw new Error(`migração v${v + 1}: ${broken.length} chave(s) estrangeira(s) quebrada(s)`);
|
||||
database.exec(`PRAGMA user_version = ${v + 1}`);
|
||||
database.exec("COMMIT");
|
||||
} catch (error) {
|
||||
database.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
database.exec("PRAGMA foreign_keys = ON");
|
||||
}
|
||||
}
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
// node:sqlite devolve objetos sem protótipo; convertemos para objetos simples, que podem
|
||||
// ser passados a componentes cliente.
|
||||
export function all<T>(sql: string, ...params: SQLInputValue[]): T[] {
|
||||
return db().prepare(sql).all(...params).map((row) => ({ ...row }) as T);
|
||||
}
|
||||
|
||||
export function get<T>(sql: string, ...params: SQLInputValue[]): T | undefined {
|
||||
const row = db().prepare(sql).get(...params);
|
||||
return row ? ({ ...row } as T) : undefined;
|
||||
}
|
||||
|
||||
export function run(sql: string, ...params: SQLInputValue[]) {
|
||||
return db().prepare(sql).run(...params);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Comentários e decisão de um episódio (1–4 vertentes: A, B, C, D).
|
||||
//
|
||||
// Comentário é conteúdo externo NÃO confiável: só extraímos dele um voto explícito
|
||||
// (uma das letras em jogo). O texto nunca entra em prompt de agente nem vira comando.
|
||||
import crypto from "node:crypto";
|
||||
import { prepareBranches } from "./branches";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { UserError, getEpisodeById, promoteWinner, touchStory } from "./stories";
|
||||
import type { Choice, Comment, Decision } from "./types";
|
||||
|
||||
export const DECISION_RULE =
|
||||
"1 voto por conta (vale o último voto explícito); só contam comentários que começam com uma das letras em jogo " +
|
||||
"(\"A\", \"opção B\", \"C!\"); comentário que cita duas opções é ambíguo e não conta; " +
|
||||
"empate ou zero votos exigem decisão manual com justificativa registrada.";
|
||||
|
||||
const VOTE_RE = /^\s*(?:op[cç][aã]o\s+|escolho\s+|voto\s+(?:na\s+|no\s+)?)?([A-D])(?=$|[\s!.,:;—–-])/i;
|
||||
|
||||
/** Voto explícito em uma das `letters` (padrão A/B). Letra fora do jogo ou texto ambíguo = sem voto. */
|
||||
export function parseVote(text: string, letters: Choice[] = ["A", "B"]): Choice | null {
|
||||
const m = VOTE_RE.exec(text);
|
||||
if (!m) return null;
|
||||
const choice = m[1].toUpperCase() as Choice;
|
||||
if (!letters.includes(choice)) return null;
|
||||
// "A ou B?" e similares: outra letra em jogo isolada no resto do texto = ambíguo.
|
||||
const rest = text.slice(m[0].length);
|
||||
for (const other of letters) {
|
||||
if (other !== choice && new RegExp(`(^|[^\\p{L}])${other}([^\\p{L}]|$)`, "u").test(rest)) return null;
|
||||
}
|
||||
return choice;
|
||||
}
|
||||
|
||||
/** Letras em jogo no episódio (story.branch_count). */
|
||||
function lettersFor(episodeId: number): Choice[] {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Episódio não encontrado.");
|
||||
return ep.choices.length > 0 ? ep.choices.map((c) => c.letter) : ["A", "B"];
|
||||
}
|
||||
|
||||
export function listComments(episodeId: number): Comment[] {
|
||||
return all<Comment>("SELECT * FROM comments WHERE episode_id = ? ORDER BY id", episodeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Entrada manual: uma linha por comentário, no formato "autor: texto". O par autor+texto
|
||||
* gera um ID estável, então colar a mesma lista duas vezes não duplica votos.
|
||||
*/
|
||||
export function addManualComments(episodeId: number, block: string): { added: number; duplicates: number; rejected: string[] } {
|
||||
assertOpen(episodeId);
|
||||
const letters = lettersFor(episodeId);
|
||||
let added = 0;
|
||||
let duplicates = 0;
|
||||
const rejected: string[] = [];
|
||||
for (const raw of block.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line) continue;
|
||||
const sep = line.indexOf(":");
|
||||
if (sep <= 0 || sep === line.length - 1) {
|
||||
rejected.push(line);
|
||||
continue;
|
||||
}
|
||||
const author = line.slice(0, sep).trim().slice(0, 60);
|
||||
const text = line.slice(sep + 1).trim().slice(0, 1000);
|
||||
const authorId = author.toLowerCase().replace(/^@/, "");
|
||||
const externalId = crypto.createHash("sha1").update(`${authorId}\n${text}`).digest("hex");
|
||||
const r = run(`INSERT OR IGNORE INTO comments (episode_id, source, external_id, author_id, author_name, text, choice, created_at)
|
||||
VALUES (?, 'manual', ?, ?, ?, ?, ?, ?)`, episodeId, externalId, authorId, author, text, parseVote(text, letters), now());
|
||||
if (r.changes > 0) added++;
|
||||
else duplicates++;
|
||||
}
|
||||
return { added, duplicates, rejected };
|
||||
}
|
||||
|
||||
export type Tally = {
|
||||
/** Votos por letra em jogo (todas presentes, mesmo com 0). */
|
||||
votes: Partial<Record<Choice, number>>;
|
||||
/** Mantidos para a tela antiga de A/B. */
|
||||
votesA: number;
|
||||
votesB: number;
|
||||
ambiguousOrNoVote: number;
|
||||
totalComments: number;
|
||||
voters: { authorId: string; authorName: string; choice: Choice; commentId: number }[];
|
||||
};
|
||||
|
||||
export function tally(episodeId: number): Tally {
|
||||
const letters = lettersFor(episodeId);
|
||||
const comments = listComments(episodeId);
|
||||
const lastVote = new Map<string, Comment>();
|
||||
for (const c of comments) if (c.choice && letters.includes(c.choice)) lastVote.set(c.author_id, c);
|
||||
const voters = [...lastVote.values()].map((c) => ({ authorId: c.author_id, authorName: c.author_name, choice: c.choice!, commentId: c.id }));
|
||||
const votes = Object.fromEntries(letters.map((l) => [l, voters.filter((v) => v.choice === l).length])) as Partial<Record<Choice, number>>;
|
||||
return {
|
||||
votes,
|
||||
votesA: votes.A ?? 0,
|
||||
votesB: votes.B ?? 0,
|
||||
ambiguousOrNoVote: comments.filter((c) => !c.choice || !letters.includes(c.choice)).length,
|
||||
totalComments: comments.length,
|
||||
voters,
|
||||
};
|
||||
}
|
||||
|
||||
/** Letra com mais votos; empate no topo ou zero votos = null (decisão manual). */
|
||||
export function leader(votes: Partial<Record<Choice, number>>): Choice | null {
|
||||
const entries = Object.entries(votes) as [Choice, number][];
|
||||
const top = Math.max(0, ...entries.map(([, n]) => n));
|
||||
const winners = entries.filter(([, n]) => n === top);
|
||||
return top > 0 && winners.length === 1 ? winners[0][0] : null;
|
||||
}
|
||||
|
||||
export function decisionVotes(decision: Decision): Partial<Record<Choice, number>> {
|
||||
try {
|
||||
return JSON.parse(decision.votes_json) as Partial<Record<Choice, number>>;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fecha a votação com uma fotografia imutável. Depois de fechada, não reabre.
|
||||
* A vertente vencedora vira o caminho principal (as outras são descartadas) e, se ela já
|
||||
* existe, a IA começa a preparar as vertentes do nível seguinte.
|
||||
*/
|
||||
export function closeDecision(episodeId: number, manual?: { winner: Choice; reason: string }): Decision {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Episódio não encontrado.");
|
||||
assertOpen(episodeId);
|
||||
const letters = lettersFor(episodeId);
|
||||
const t = tally(episodeId);
|
||||
let winner = leader(t.votes);
|
||||
let method: Decision["method"] = "votes";
|
||||
if (!winner) {
|
||||
const total = Object.values(t.votes).reduce((a, n) => a + (n ?? 0), 0);
|
||||
if (!manual || manual.reason.trim().length < 5) {
|
||||
throw new UserError(total === 0
|
||||
? "Nenhum voto válido. Escolha manualmente e escreva a justificativa."
|
||||
: `Empate (${letters.map((l) => `${l}: ${t.votes[l] ?? 0}`).join(" × ")}). Escolha manualmente e escreva a justificativa.`);
|
||||
}
|
||||
if (!letters.includes(manual.winner)) throw new UserError("Escolha manual fora das vertentes deste episódio.");
|
||||
winner = manual.winner;
|
||||
method = "manual";
|
||||
}
|
||||
const closedAt = now();
|
||||
const snapshot = {
|
||||
closedAt, rule: DECISION_RULE, method, winner,
|
||||
choices: Object.fromEntries(ep.choices.map((c) => [c.letter, c.label])),
|
||||
tally: t,
|
||||
manualReason: method === "manual" ? manual!.reason.trim() : null,
|
||||
};
|
||||
run(`INSERT INTO decisions (episode_id, closed_at, votes_json, winner, method, rule, snapshot_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, episodeId, closedAt, JSON.stringify(t.votes), winner, method, DECISION_RULE, JSON.stringify(snapshot));
|
||||
touchStory(ep.story_id);
|
||||
const promoted = promoteWinner(episodeId, winner);
|
||||
// "Só o próximo nível": a vencedora já tem roteiro e cena; a IA prepara as vertentes dela agora.
|
||||
if (promoted) {
|
||||
try {
|
||||
prepareBranches(promoted.id, { auto: true });
|
||||
} catch (error) {
|
||||
console.warn(`vertentes do episódio ${promoted.file_key} não foram preparadas: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
return get<Decision>("SELECT * FROM decisions WHERE episode_id = ?", episodeId)!;
|
||||
}
|
||||
|
||||
function assertOpen(episodeId: number): void {
|
||||
if (get("SELECT 1 FROM decisions WHERE episode_id = ?", episodeId)) {
|
||||
throw new UserError("A votação deste episódio já foi fechada e não pode ser alterada.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// Laço do despachante de publicação: um único `setInterval` por processo do painel (guardado em globalThis,
|
||||
// para o HMR do `next dev` não criar outro), a cada 20 s. Um ciclo nunca começa com o anterior ainda rodando;
|
||||
// pedidos de "rode já" (kick) durante um ciclo viram um ciclo logo depois. Erro num ciclo é registrado e o laço
|
||||
// segue. O trabalho de cada ciclo está em lib/publishing.ts (dispatcherTick) — aqui é só o relógio.
|
||||
//
|
||||
// O painel precisa estar aberto para publicar/agendar (não há agendador fora dele).
|
||||
|
||||
export type DispatcherState = {
|
||||
timer: ReturnType<typeof setInterval> | null;
|
||||
tick: (() => Promise<void>) | null;
|
||||
running: boolean;
|
||||
pending: boolean;
|
||||
lastTickAt: string | null;
|
||||
lastError: string | null;
|
||||
publisherOnline: boolean | null;
|
||||
clipperOnline: boolean | null;
|
||||
/** Última mensagem registrada por assunto (não repetir o mesmo aviso a cada 20 s). */
|
||||
logged: Record<string, string>;
|
||||
};
|
||||
|
||||
export const TICK_INTERVAL_MS = 20_000;
|
||||
|
||||
const g = globalThis as unknown as { __cenaforgeDispatcher?: DispatcherState };
|
||||
|
||||
export function dispatcherState(): DispatcherState {
|
||||
return (g.__cenaforgeDispatcher ??= {
|
||||
timer: null, tick: null, running: false, pending: false, lastTickAt: null, lastError: null,
|
||||
publisherOnline: null, clipperOnline: null, logged: {},
|
||||
});
|
||||
}
|
||||
|
||||
/** Registra no terminal só quando a mensagem do assunto muda (e avisa quando volta ao normal). */
|
||||
export function logChange(topic: string, message: string | null): void {
|
||||
const state = dispatcherState();
|
||||
const previous = state.logged[topic] ?? null;
|
||||
if (previous === message) return;
|
||||
if (message) {
|
||||
state.logged[topic] = message;
|
||||
console.warn(`[publicação] ${topic}: ${message}`);
|
||||
} else {
|
||||
delete state.logged[topic];
|
||||
if (previous) console.info(`[publicação] ${topic}: normalizado.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Liga o laço (idempotente). `tick` é trocado a cada chamada; o intervalo é um só. */
|
||||
export function startDispatcher(tick: () => Promise<void>, intervalMs = TICK_INTERVAL_MS): void {
|
||||
const state = dispatcherState();
|
||||
state.tick = tick;
|
||||
if (state.timer) return;
|
||||
state.timer = setInterval(() => void runDispatcherOnce(), intervalMs);
|
||||
state.timer.unref?.();
|
||||
// Primeiro ciclo logo depois de subir (o painel termina de iniciar antes).
|
||||
setTimeout(() => void runDispatcherOnce(), 5_000).unref?.();
|
||||
console.info(`[publicação] despachante ligado (a cada ${Math.round(intervalMs / 1000)} s).`);
|
||||
}
|
||||
|
||||
export function stopDispatcher(): void {
|
||||
const state = dispatcherState();
|
||||
if (state.timer) clearInterval(state.timer);
|
||||
state.timer = null;
|
||||
}
|
||||
|
||||
/** Roda um ciclo agora, se nenhum estiver rodando; senão marca para rodar logo depois do atual. */
|
||||
export async function runDispatcherOnce(): Promise<void> {
|
||||
const state = dispatcherState();
|
||||
if (!state.tick) return;
|
||||
if (state.running) {
|
||||
state.pending = true;
|
||||
return;
|
||||
}
|
||||
state.running = true;
|
||||
try {
|
||||
await state.tick();
|
||||
state.lastError = null;
|
||||
logChange("ciclo", null);
|
||||
} catch (error) {
|
||||
state.lastError = error instanceof Error ? error.message : String(error);
|
||||
logChange("ciclo", state.lastError);
|
||||
} finally {
|
||||
state.running = false;
|
||||
state.lastTickAt = new Date().toISOString();
|
||||
if (state.pending) {
|
||||
state.pending = false;
|
||||
setTimeout(() => void runDispatcherOnce(), 1_000).unref?.();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pede um ciclo já (depois de aprovar, publicar agora, tentar de novo…), sem esperar os 20 s. */
|
||||
export function kickDispatcher(): void {
|
||||
if (!dispatcherState().tick) return;
|
||||
setTimeout(() => void runDispatcherOnce(), 250).unref?.();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Fluxo da história (estilo n8n): a árvore de episódios vira nós e arestas para o editor visual.
|
||||
// Só leitura: as ações (preparar vertentes, fechar votação, abrir episódio) usam as rotas de sempre.
|
||||
import { decisionVotes } from "./decisions";
|
||||
import { getStory, listAllEpisodes } from "./stories";
|
||||
import type { BranchesStatus, Choice, EpisodeStage, EpisodeStatus, StoryKind } from "./types";
|
||||
|
||||
export type FlowNode = {
|
||||
id: string; // "ep-<id>"
|
||||
episodeId: number;
|
||||
fileKey: string;
|
||||
number: number;
|
||||
title: string;
|
||||
status: EpisodeStatus;
|
||||
stage: EpisodeStage;
|
||||
/** Opção do episódio pai que leva a este (A–D); null no início. */
|
||||
choice: Choice | null;
|
||||
choiceLabel: string;
|
||||
isStart: boolean;
|
||||
hasScript: boolean;
|
||||
hasConfig: boolean;
|
||||
/** Caminhos relativos à raiz (roteiro .md e cena .json). */
|
||||
scriptPath: string;
|
||||
configPath: string;
|
||||
rendered: boolean;
|
||||
branchesStatus: BranchesStatus;
|
||||
branchesRunId: number | null;
|
||||
/** Decisão deste episódio, se fechada. */
|
||||
decision: { winner: Choice; votes: Partial<Record<Choice, number>>; method: "votes" | "manual" } | null;
|
||||
/** Rótulos das opções da decisão deste episódio. */
|
||||
choices: { letter: Choice; label: string }[];
|
||||
};
|
||||
|
||||
export type FlowEdge = {
|
||||
id: string;
|
||||
source: string;
|
||||
target: string;
|
||||
choice: Choice;
|
||||
label: string;
|
||||
/** winner = caminho escolhido; open = votação aberta; lost = vertente descartada. */
|
||||
state: "winner" | "open" | "lost";
|
||||
};
|
||||
|
||||
export type StoryFlow = {
|
||||
storyId: string;
|
||||
title: string;
|
||||
kind: StoryKind;
|
||||
branchCount: number;
|
||||
nodes: FlowNode[];
|
||||
edges: FlowEdge[];
|
||||
};
|
||||
|
||||
export function storyFlow(storyId: string): StoryFlow | undefined {
|
||||
const story = getStory(storyId);
|
||||
if (!story) return undefined;
|
||||
const episodes = listAllEpisodes(storyId);
|
||||
const byId = new Map(episodes.map((e) => [e.id, e]));
|
||||
const nodes: FlowNode[] = episodes.map((e) => ({
|
||||
id: `ep-${e.id}`,
|
||||
episodeId: e.id,
|
||||
fileKey: e.file_key,
|
||||
number: e.number,
|
||||
title: e.title,
|
||||
status: e.status,
|
||||
stage: e.stage,
|
||||
choice: e.parent_choice,
|
||||
choiceLabel: e.branch_label || (e.parent_episode_id ? byId.get(e.parent_episode_id)?.choices.find((c) => c.letter === e.parent_choice)?.label ?? "" : ""),
|
||||
isStart: e.parent_episode_id === null,
|
||||
hasScript: e.hasScript,
|
||||
hasConfig: e.hasConfig,
|
||||
scriptPath: e.scriptPath,
|
||||
configPath: e.configPath,
|
||||
rendered: e.stage === "renderizado" || e.lastRender?.status === "success",
|
||||
branchesStatus: e.branches_status,
|
||||
branchesRunId: e.branches_run_id,
|
||||
decision: e.decision ? { winner: e.decision.winner, votes: decisionVotes(e.decision), method: e.decision.method } : null,
|
||||
choices: e.choices.map((c) => ({ letter: c.letter, label: c.label })),
|
||||
}));
|
||||
const edges: FlowEdge[] = episodes
|
||||
.filter((e) => e.parent_episode_id !== null && byId.has(e.parent_episode_id))
|
||||
.map((e) => {
|
||||
const parent = byId.get(e.parent_episode_id!)!;
|
||||
const state: FlowEdge["state"] = !parent.decision ? "open" : parent.decision.winner === e.parent_choice ? "winner" : "lost";
|
||||
return {
|
||||
id: `edge-${parent.id}-${e.id}`,
|
||||
source: `ep-${parent.id}`,
|
||||
target: `ep-${e.id}`,
|
||||
choice: (e.parent_choice ?? "A") as Choice,
|
||||
label: e.branch_label || parent.choices.find((c) => c.letter === e.parent_choice)?.label || "",
|
||||
state,
|
||||
};
|
||||
});
|
||||
return { storyId, title: story.title, kind: story.kind, branchCount: story.branch_count, nodes, edges };
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { UserError } from "./stories";
|
||||
|
||||
/**
|
||||
* Erro com mensagem para o usuário e status HTTP próprio — usado quando um serviço local (Publicador)
|
||||
* está fora do ar (503) ou recusa o pedido (repassa o 4xx dele). A mensagem vai como está para a UI.
|
||||
*/
|
||||
export class ServiceError extends UserError {
|
||||
constructor(message: string, readonly status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Erro de uso vira 400 com a mensagem; o resto vira 500 com mensagem genérica no corpo. */
|
||||
export function errorResponse(error: unknown): Response {
|
||||
if (error instanceof ServiceError) return Response.json({ error: error.message }, { status: error.status });
|
||||
if (error instanceof UserError) return Response.json({ error: error.message }, { status: 400 });
|
||||
console.error(error);
|
||||
return Response.json({ error: "Erro interno. Veja o terminal do painel." }, { status: 500 });
|
||||
}
|
||||
|
||||
export function parseId(raw: string): number {
|
||||
const id = Number(raw);
|
||||
if (!Number.isInteger(id) || id <= 0) throw new UserError("Identificador inválido.");
|
||||
return id;
|
||||
}
|
||||
|
||||
/** O pedido declara corpo JSON? (`Content-Type: application/json`, com ou sem charset) */
|
||||
export function isJsonRequest(request: Request): boolean {
|
||||
return /^application\/json\s*(;|$)/i.test(request.headers.get("content-type") ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Lê o corpo JSON. Exige `Content-Type: application/json` (um formulário de outro site não consegue mandar isso
|
||||
* sem pré-checagem CORS — defesa extra contra CSRF). Corpo JSON vazio ou inválido vira {} (as validações de cada
|
||||
* campo dizem o que falta).
|
||||
*/
|
||||
export async function readJson<T extends object>(request: Request): Promise<Partial<T>> {
|
||||
if (!isJsonRequest(request)) throw new ServiceError("Envie o corpo como JSON (Content-Type: application/json).", 415);
|
||||
try {
|
||||
const body = (await request.json()) as unknown;
|
||||
return body && typeof body === "object" && !Array.isArray(body) ? (body as Partial<T>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Busca de imagem na internet para a montagem documental: Wikimedia Commons (banco público,
|
||||
// sem chave de API). Devolve fotos grandes (≥ 900 px no menor lado útil), na ordem de relevância
|
||||
// da busca, com autor e página de origem para o crédito do vídeo.
|
||||
// Só os termos de busca saem do computador (nada do usuário ou do projeto).
|
||||
|
||||
export type FoundImage = {
|
||||
title: string; url: string; pageUrl: string; author: string; license: string; width: number; height: number;
|
||||
};
|
||||
|
||||
const API = "https://commons.wikimedia.org/w/api.php";
|
||||
/** O Wikimedia pede um User-Agent identificando o cliente (genérico, sem dados do usuário). */
|
||||
const USER_AGENT = "CenaForge/1.0 (painel local de video; busca de imagem)";
|
||||
|
||||
const stripHtml = (s: string) => s.replace(/<[^>]*>/g, " ").replace(/&/g, "&").replace(/"/g, "\"").replace(/'/g, "'").replace(/\s+/g, " ").trim();
|
||||
|
||||
export async function searchCommons(query: string, limit = 12): Promise<FoundImage[]> {
|
||||
const params = new URLSearchParams({
|
||||
action: "query", format: "json", generator: "search", gsrnamespace: "6",
|
||||
gsrsearch: `${query} filetype:bitmap`, gsrlimit: "30",
|
||||
prop: "imageinfo", iiprop: "url|size|mime|extmetadata", iiurlwidth: "1600",
|
||||
});
|
||||
const r = await fetch(`${API}?${params}`, { headers: { "User-Agent": USER_AGENT }, signal: AbortSignal.timeout(20_000) });
|
||||
if (!r.ok) throw new Error(`busca de imagem respondeu ${r.status}`);
|
||||
const data = (await r.json()) as { query?: { pages?: Record<string, {
|
||||
index?: number; title: string;
|
||||
imageinfo?: { thumburl?: string; url: string; descriptionurl: string; width: number; height: number; mime: string;
|
||||
extmetadata?: Record<string, { value?: string }> }[];
|
||||
}> } };
|
||||
const pages = Object.values(data.query?.pages ?? {}).sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
|
||||
const out: FoundImage[] = [];
|
||||
for (const p of pages) {
|
||||
const info = p.imageinfo?.[0];
|
||||
if (!info || !/^image\/(jpeg|png|webp)$/.test(info.mime)) continue;
|
||||
if (Math.min(info.width, info.height) < 900) continue;
|
||||
// Mapas, diagramas e brasões raramente servem de foto de trecho.
|
||||
if (/\b(map|mapa|diagram|logo|bras[aã]o|coat of arms|flag|bandeira|chart|graph)\b/i.test(p.title)) continue;
|
||||
const meta = info.extmetadata ?? {};
|
||||
out.push({
|
||||
title: p.title.replace(/^File:/, "").replace(/\.[a-z0-9]+$/i, ""),
|
||||
url: info.thumburl ?? info.url,
|
||||
pageUrl: info.descriptionurl,
|
||||
author: stripHtml(meta.Artist?.value ?? "").slice(0, 120) || "Wikimedia Commons",
|
||||
license: stripHtml(meta.LicenseShortName?.value ?? ""),
|
||||
width: info.width, height: info.height,
|
||||
});
|
||||
if (out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Tenta as buscas em ordem até achar imagens (da mais específica para a mais geral). */
|
||||
export async function searchFirst(queries: string[], limit = 12): Promise<{ query: string; images: FoundImage[] } | null> {
|
||||
for (const q of queries) {
|
||||
const images = await searchCommons(q, limit).catch(() => []);
|
||||
if (images.length) return { query: q, images };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function downloadImage(url: string): Promise<{ bytes: Buffer; ext: string }> {
|
||||
const r = await fetch(url, { headers: { "User-Agent": USER_AGENT }, signal: AbortSignal.timeout(60_000) });
|
||||
if (!r.ok) throw new Error(`download da imagem respondeu ${r.status}`);
|
||||
const type = r.headers.get("content-type") ?? "";
|
||||
const ext = type.includes("png") ? ".png" : type.includes("webp") ? ".webp" : ".jpg";
|
||||
const bytes = Buffer.from(await r.arrayBuffer());
|
||||
if (bytes.length < 5_000 || bytes.length > 40 * 1024 * 1024) throw new Error("imagem baixada com tamanho inesperado");
|
||||
return { bytes, ext };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Números reais dos posts (views, curtidas, comentários), lidos pelo Publicador e gravados em publication_metrics
|
||||
// (simulated = 0). Cada leitura é uma "fotografia": o dashboard mostra a mais recente de cada post.
|
||||
//
|
||||
// De onde vem cada rede (publisher/app/platforms/stats.py):
|
||||
// YouTube — página pública do vídeo, sem abrir janela (qualquer modo de conexão);
|
||||
// TikTok — lista "Publicações" do TikTok Studio, na janela logada (só modo sessão);
|
||||
// Instagram — aba Reels do perfil, na janela logada (só modo sessão).
|
||||
// A janela abre por uns 10–20 s e fecha sozinha (se já estava aberta, fica). Se um vídeo estiver sendo enviado, a
|
||||
// leitura espera o envio terminar.
|
||||
//
|
||||
// Quando: sozinho a cada `metricsEveryHours` (Configurações; padrão 6 h; 0 = só pelo botão), puxado pelo ciclo do
|
||||
// despachante, só para posts dos últimos 90 dias; pelo botão "Atualizar números" do dashboard, todos.
|
||||
import { all, run } from "./db";
|
||||
import { ServiceError } from "./http";
|
||||
import { postStats, profileIdFor } from "./publisher";
|
||||
import { parseVideoUrl } from "./publishing-rules";
|
||||
import { getSettings } from "./settings";
|
||||
import type { Platform } from "./types";
|
||||
|
||||
export type MetricSync = {
|
||||
accountId: string;
|
||||
platform: Platform;
|
||||
lastRunAt: string | null;
|
||||
lastOkAt: string | null;
|
||||
lastError: string | null;
|
||||
read: number;
|
||||
missing: number;
|
||||
};
|
||||
|
||||
export type CollectResult = {
|
||||
groups: { accountId: string; platform: Platform; read: number; missing: number; error: string | null }[];
|
||||
snapshots: number;
|
||||
};
|
||||
|
||||
const RECENT_DAYS = 90;
|
||||
const AUTO_CHECK_MS = 10 * 60_000;
|
||||
|
||||
type SyncState = { running: Promise<CollectResult> | null; lastAutoCheck: number };
|
||||
const state: SyncState = ((globalThis as unknown as { __cenaforgeMetricsSync?: SyncState }).__cenaforgeMetricsSync ??=
|
||||
{ running: null, lastAutoCheck: 0 });
|
||||
|
||||
export function isCollecting(): boolean {
|
||||
return state.running !== null;
|
||||
}
|
||||
|
||||
export function listMetricSyncs(accountId?: string): MetricSync[] {
|
||||
return all<{ account_id: string; platform: Platform; last_run_at: string | null; last_ok_at: string | null; last_error: string | null; read_count: number; missing_count: number }>(
|
||||
`SELECT * FROM metric_syncs ${accountId ? "WHERE account_id = ?" : ""} ORDER BY account_id, platform`, ...(accountId ? [accountId] : []))
|
||||
.map((r) => ({
|
||||
accountId: r.account_id, platform: r.platform, lastRunAt: r.last_run_at, lastOkAt: r.last_ok_at,
|
||||
lastError: r.last_error, read: r.read_count, missing: r.missing_count,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Lê agora. Se já houver uma leitura em andamento, devolve a mesma (não abre duas janelas). */
|
||||
export function collectMetrics(opts: { accountId?: string; force?: boolean } = {}): Promise<CollectResult> {
|
||||
if (state.running) return state.running;
|
||||
state.running = collect(opts).finally(() => { state.running = null; });
|
||||
return state.running;
|
||||
}
|
||||
|
||||
/** Chamado a cada ciclo do despachante: lê sozinho as redes vencidas (no máximo uma conferência a cada 10 min). */
|
||||
export function autoCollectMetrics(): void {
|
||||
if (state.running || Date.now() - state.lastAutoCheck < AUTO_CHECK_MS) return;
|
||||
if (getSettings().metricsEveryHours === 0) return;
|
||||
state.lastAutoCheck = Date.now();
|
||||
void collectMetrics().catch((error) => console.warn(`[números] leitura automática falhou: ${error instanceof Error ? error.message : String(error)}`));
|
||||
}
|
||||
|
||||
type Target = { id: number; account_id: string; platform: Platform; url: string };
|
||||
|
||||
async function collect({ accountId, force = false }: { accountId?: string; force?: boolean }): Promise<CollectResult> {
|
||||
const everyMs = getSettings().metricsEveryHours * 3_600_000;
|
||||
const where = ["p.simulated = 0", "p.url != ''"];
|
||||
const params: string[] = [];
|
||||
if (!force) { where.push("p.published_at >= ?"); params.push(new Date(Date.now() - RECENT_DAYS * 86_400_000).toISOString()); }
|
||||
if (accountId) { where.push("p.account_id = ?"); params.push(accountId); }
|
||||
const targets = all<Target>(
|
||||
`SELECT p.id, p.account_id, p.platform, p.url FROM publications p
|
||||
JOIN account_networks n ON n.account_id = p.account_id AND n.platform = p.platform AND n.mode IS NOT NULL
|
||||
WHERE ${where.join(" AND ")}`, ...params);
|
||||
|
||||
const groups = new Map<string, Target[]>();
|
||||
for (const t of targets) groups.set(`${t.account_id}|${t.platform}`, [...(groups.get(`${t.account_id}|${t.platform}`) ?? []), t]);
|
||||
const lastRun = new Map(listMetricSyncs().map((s) => [`${s.accountId}|${s.platform}`, s.lastRunAt]));
|
||||
|
||||
const result: CollectResult = { groups: [], snapshots: 0 };
|
||||
for (const [key, list] of groups) {
|
||||
const { account_id: account, platform } = list[0];
|
||||
const last = lastRun.get(key);
|
||||
if (!force && last && Date.now() - new Date(last).getTime() < everyMs) continue;
|
||||
// remoteId (id do vídeo / código do reel) → publicações com ele.
|
||||
const byRemote = new Map<string, number[]>();
|
||||
for (const t of list) {
|
||||
const remote = parseVideoUrl(platform, t.url)?.remoteId;
|
||||
if (remote) byRemote.set(remote, [...(byRemote.get(remote) ?? []), t.id]);
|
||||
}
|
||||
if (byRemote.size === 0) continue;
|
||||
const startedAt = new Date().toISOString();
|
||||
try {
|
||||
const stats = await postStats(profileIdFor(account, platform), [...byRemote.keys()]);
|
||||
for (const item of stats.items) {
|
||||
for (const publicationId of byRemote.get(item.remoteId) ?? []) {
|
||||
run(`INSERT OR REPLACE INTO publication_metrics (publication_id, captured_at, views, likes, comments, shares, saves, simulated)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0)`, publicationId, stats.capturedAt,
|
||||
item.views ?? 0, item.likes ?? 0, item.comments ?? 0, item.shares ?? 0, item.saves ?? 0);
|
||||
result.snapshots += 1;
|
||||
}
|
||||
}
|
||||
saveSync(account, platform, startedAt, null, stats.items.length, stats.missing.length);
|
||||
result.groups.push({ accountId: account, platform, read: stats.items.length, missing: stats.missing.length, error: null });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
saveSync(account, platform, startedAt, message, 0, byRemote.size);
|
||||
result.groups.push({ accountId: account, platform, read: 0, missing: byRemote.size, error: message });
|
||||
if (error instanceof ServiceError && error.status === 503) break; // Publicador fora: as outras redes também falhariam
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function saveSync(accountId: string, platform: Platform, at: string, error: string | null, read: number, missing: number): void {
|
||||
run(`INSERT INTO metric_syncs (account_id, platform, last_run_at, last_ok_at, last_error, read_count, missing_count)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (account_id, platform) DO UPDATE SET last_run_at = excluded.last_run_at,
|
||||
last_ok_at = COALESCE(excluded.last_ok_at, metric_syncs.last_ok_at), last_error = excluded.last_error,
|
||||
read_count = excluded.read_count, missing_count = excluded.missing_count`,
|
||||
accountId, platform, at, error ? null : at, error, read, missing);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Publicações e métricas (views, curtidas, comentários, compartilhamentos, salvos, retenção).
|
||||
//
|
||||
// Números reais: lidos das redes pelo Publicador (lib/metrics-sync.ts) e gravados com simulated = 0.
|
||||
// `simulateMetrics()` ainda gera dados de EXEMPLO (simulated = 1) para ver o dashboard sem nada publicado; tudo
|
||||
// que é simulado é marcado e sai de uma vez com `clearSimulated()`.
|
||||
import crypto from "node:crypto";
|
||||
import { all, get, run } from "./db";
|
||||
import { listMetricSyncs, type MetricSync } from "./metrics-sync";
|
||||
import type { MetricTotals, Platform } from "./types";
|
||||
|
||||
// Captura "mais recente" de cada publicação (as métricas são fotografias ao longo do tempo).
|
||||
const LATEST = `
|
||||
SELECT m.* FROM publication_metrics m
|
||||
JOIN (SELECT publication_id, MAX(captured_at) AS at FROM publication_metrics GROUP BY publication_id) last
|
||||
ON last.publication_id = m.publication_id AND last.at = m.captured_at`;
|
||||
|
||||
type Row = {
|
||||
views: number; likes: number; comments: number; shares: number; saves: number;
|
||||
publications: number; completion_weighted: number | null; completion_views: number | null;
|
||||
};
|
||||
|
||||
const SUMS = `COALESCE(SUM(m.views), 0) AS views, COALESCE(SUM(m.likes), 0) AS likes, COALESCE(SUM(m.comments), 0) AS comments,
|
||||
COALESCE(SUM(m.shares), 0) AS shares, COALESCE(SUM(m.saves), 0) AS saves, COUNT(DISTINCT p.id) AS publications,
|
||||
SUM(m.completion_rate * m.views) AS completion_weighted, SUM(CASE WHEN m.completion_rate IS NULL THEN 0 ELSE m.views END) AS completion_views`;
|
||||
|
||||
function totals(row: Row | undefined): MetricTotals {
|
||||
const r = row ?? { views: 0, likes: 0, comments: 0, shares: 0, saves: 0, publications: 0, completion_weighted: null, completion_views: null };
|
||||
const interactions = r.likes + r.comments + r.shares + r.saves;
|
||||
return {
|
||||
views: r.views, likes: r.likes, comments: r.comments, shares: r.shares, saves: r.saves, publications: r.publications,
|
||||
completionRate: r.completion_views ? (r.completion_weighted ?? 0) / r.completion_views : null,
|
||||
engagementRate: r.views > 0 ? interactions / r.views : null,
|
||||
};
|
||||
}
|
||||
|
||||
export type Dashboard = {
|
||||
/** Há algum dado simulado no que está sendo mostrado? (o painel mostra o selo "simulado") */
|
||||
simulated: boolean;
|
||||
counts: { accounts: number; activeStories: number; stories: number; episodes: number; networks: number };
|
||||
totals: MetricTotals;
|
||||
byPlatform: (MetricTotals & { platform: Platform })[];
|
||||
byAccount: (MetricTotals & { accountId: string; name: string })[];
|
||||
byStory: (MetricTotals & { storyId: string; title: string })[];
|
||||
/** Episódios ranqueados por engajamento (melhores primeiro); o painel mostra topo e fundo. */
|
||||
byEpisode: (MetricTotals & { episodeId: number; number: number; status: string; storyId: string; storyTitle: string; fileKey: string; title: string })[];
|
||||
/** Views por dia de publicação (últimos 30 dias com dado). */
|
||||
daily: { day: string; views: number; publications: number }[];
|
||||
/** Cada vídeo (corte ou episódio) com o total somado das redes e os números de cada rede. Mais vistos primeiro. */
|
||||
byVideo: VideoMetrics[];
|
||||
/** Última leitura dos números por rede de cada canal (erro, quando falhou). */
|
||||
syncs: (MetricSync & { accountName: string })[];
|
||||
};
|
||||
|
||||
export type VideoNetwork = {
|
||||
platform: Platform; accountId: string; accountName: string; url: string; publishedAt: string;
|
||||
/** null = ainda não lido. */
|
||||
views: number | null; likes: number | null; comments: number | null; capturedAt: string | null;
|
||||
};
|
||||
export type VideoMetrics = {
|
||||
key: string; kind: "clip" | "episode"; title: string; cover: string | null; href: string | null;
|
||||
publishedAt: string; capturedAt: string | null; totals: MetricTotals; networks: VideoNetwork[];
|
||||
};
|
||||
|
||||
type VideoRow = {
|
||||
id: number; platform: Platform; url: string; account_id: string; account_name: string; clip_id: number | null;
|
||||
episode_id: number | null; published_at: string; title: string; cover: string | null; story_id: string | null; file_key: string | null;
|
||||
views: number | null; likes: number | null; comments: number | null; shares: number | null; saves: number | null; captured_at: string | null;
|
||||
};
|
||||
|
||||
function videos(where: string, params: string[], base: string): VideoMetrics[] {
|
||||
const rows = all<VideoRow>(
|
||||
`SELECT p.id, p.platform, p.url, p.account_id, a.name AS account_name, p.clip_id, p.episode_id, p.published_at,
|
||||
COALESCE(NULLIF(j.title, ''), e.title, '') AS title, j.cover, e.story_id, e.file_key,
|
||||
m.views, m.likes, m.comments, m.shares, m.saves, m.captured_at
|
||||
${base} JOIN accounts a ON a.id = p.account_id
|
||||
LEFT JOIN publish_jobs j ON j.id = p.job_id LEFT JOIN episodes e ON e.id = p.episode_id
|
||||
${where} ORDER BY p.published_at`, ...params);
|
||||
const map = new Map<string, VideoRow[]>();
|
||||
for (const r of rows) {
|
||||
const key = r.clip_id !== null ? `clip:${r.clip_id}` : `episode:${r.episode_id}`;
|
||||
map.set(key, [...(map.get(key) ?? []), r]);
|
||||
}
|
||||
return [...map.entries()].map(([key, list]) => {
|
||||
const first = list[0];
|
||||
const sum = (k: "views" | "likes" | "comments" | "shares" | "saves") => list.reduce((n, r) => n + (r[k] ?? 0), 0);
|
||||
const n = first.file_key ? /^ep(d+)/i.exec(first.file_key)?.[1] : undefined;
|
||||
const captured = list.map((r) => r.captured_at).filter((c): c is string => !!c).sort();
|
||||
return {
|
||||
key, kind: first.clip_id !== null ? "clip" as const : "episode" as const,
|
||||
title: list.find((r) => r.title)?.title || (first.clip_id !== null ? `Corte ${first.clip_id}` : "Episódio"),
|
||||
cover: list.find((r) => r.cover)?.cover ?? null,
|
||||
href: first.story_id ? (n ? `/stories/${first.story_id}/episodes/${Number(n)}` : `/stories/${first.story_id}`) : null,
|
||||
publishedAt: first.published_at, capturedAt: captured.at(-1) ?? null,
|
||||
totals: totals({ views: sum("views"), likes: sum("likes"), comments: sum("comments"), shares: sum("shares"), saves: sum("saves"),
|
||||
publications: list.length, completion_weighted: null, completion_views: null }),
|
||||
networks: list.map((r) => ({
|
||||
platform: r.platform, accountId: r.account_id, accountName: r.account_name, url: r.url, publishedAt: r.published_at,
|
||||
views: r.views, likes: r.likes, comments: r.comments, capturedAt: r.captured_at,
|
||||
})),
|
||||
};
|
||||
}).sort((a, b) => b.totals.views - a.totals.views || b.publishedAt.localeCompare(a.publishedAt));
|
||||
}
|
||||
|
||||
export function dashboard(filter: { accountId?: string } = {}): Dashboard {
|
||||
const where = filter.accountId ? "WHERE p.account_id = ?" : "";
|
||||
const params = filter.accountId ? [filter.accountId] : [];
|
||||
const base = `FROM publications p LEFT JOIN (${LATEST}) m ON m.publication_id = p.id`;
|
||||
const simulated = !!get(`SELECT 1 FROM publications p ${where ? `${where} AND` : "WHERE"} p.simulated = 1 LIMIT 1`, ...params);
|
||||
|
||||
const byPlatform = all<Row & { platform: Platform }>(`SELECT p.platform, ${SUMS} ${base} ${where} GROUP BY p.platform`, ...params)
|
||||
.map((r) => ({ platform: r.platform, ...totals(r) }));
|
||||
const byAccount = all<Row & { account_id: string; name: string }>(
|
||||
`SELECT p.account_id, a.name, ${SUMS} ${base} JOIN accounts a ON a.id = p.account_id ${where} GROUP BY p.account_id ORDER BY views DESC`, ...params)
|
||||
.map((r) => ({ accountId: r.account_id, name: r.name, ...totals(r) }));
|
||||
const byStory = all<Row & { story_id: string; title: string }>(
|
||||
`SELECT e.story_id, s.title, ${SUMS} ${base} JOIN episodes e ON e.id = p.episode_id JOIN stories s ON s.id = e.story_id
|
||||
${where} GROUP BY e.story_id ORDER BY views DESC`, ...params)
|
||||
.map((r) => ({ storyId: r.story_id, title: r.title, ...totals(r) }));
|
||||
const byEpisode = all<Row & { episode_id: number; number: number; status: string; story_id: string; story_title: string; file_key: string; title: string }>(
|
||||
`SELECT p.episode_id, e.number, e.status, e.story_id, s.title AS story_title, e.file_key, e.title, ${SUMS} ${base}
|
||||
JOIN episodes e ON e.id = p.episode_id JOIN stories s ON s.id = e.story_id ${where} GROUP BY p.episode_id`, ...params)
|
||||
.map((r) => ({ episodeId: r.episode_id, number: r.number, status: r.status, storyId: r.story_id, storyTitle: r.story_title, fileKey: r.file_key, title: r.title, ...totals(r) }))
|
||||
.sort((a, b) => (b.engagementRate ?? -1) - (a.engagementRate ?? -1));
|
||||
const daily = all<{ day: string; views: number; publications: number }>(
|
||||
`SELECT substr(p.published_at, 1, 10) AS day, COALESCE(SUM(m.views), 0) AS views, COUNT(DISTINCT p.id) AS publications
|
||||
${base} ${where} GROUP BY day ORDER BY day DESC LIMIT 30`, ...params).reverse();
|
||||
|
||||
const accountNames = new Map(all<{ id: string; name: string }>("SELECT id, name FROM accounts").map((a) => [a.id, a.name]));
|
||||
const syncs = listMetricSyncs(filter.accountId).map((s) => ({ ...s, accountName: accountNames.get(s.accountId) ?? s.accountId }));
|
||||
|
||||
const count = (sql: string) => (get<{ n: number }>(sql, ...params) ?? { n: 0 }).n;
|
||||
return {
|
||||
simulated,
|
||||
counts: {
|
||||
accounts: filter.accountId ? 1 : count("SELECT COUNT(*) AS n FROM accounts"),
|
||||
activeStories: count(`SELECT COUNT(DISTINCT story_id) AS n FROM account_stories WHERE status = 'active'${filter.accountId ? " AND account_id = ?" : ""}`),
|
||||
stories: count(filter.accountId ? "SELECT COUNT(DISTINCT story_id) AS n FROM account_stories WHERE account_id = ?" : "SELECT COUNT(*) AS n FROM stories"),
|
||||
episodes: count(`SELECT COUNT(DISTINCT p.episode_id) AS n FROM publications p ${where}`),
|
||||
// Só redes conectadas alguma vez (linha "disconnected" é só configuração guardada).
|
||||
networks: count(`SELECT COUNT(*) AS n FROM account_networks WHERE status != 'disconnected'${filter.accountId ? " AND account_id = ?" : ""}`),
|
||||
},
|
||||
totals: totals(get<Row>(`SELECT ${SUMS} ${base} ${where}`, ...params)),
|
||||
byPlatform, byAccount, byStory, byEpisode, daily,
|
||||
byVideo: videos(where, params, base), syncs,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- dados simulados ----------
|
||||
|
||||
/** Gerador determinístico (mesma publicação → mesmos números), para a tela não "piscar" a cada geração. */
|
||||
function rng(seed: string): () => number {
|
||||
let state = crypto.createHash("sha256").update(seed).digest().readUInt32LE(0) || 1;
|
||||
return () => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return ((state >>> 0) % 1_000_000) / 1_000_000;
|
||||
};
|
||||
}
|
||||
|
||||
const PLATFORM_REACH: Record<Platform, number> = { tiktok: 1.0, instagram: 0.55, youtube: 0.35 };
|
||||
|
||||
/**
|
||||
* Para cada vínculo conta↔história × rede da conta × episódio principal, cria uma publicação simulada
|
||||
* com 3 fotografias de métricas (1 h, 24 h, 72 h). Episódios e redes variam de propósito, para o
|
||||
* dashboard mostrar o que "funciona" e o que não.
|
||||
*/
|
||||
export function simulateMetrics(): { publications: number; snapshots: number } {
|
||||
const targets = all<{ account_id: string; story_id: string; platform: Platform; episode_id: number; number: number; created_at: string }>(
|
||||
`SELECT l.account_id, l.story_id, n.platform, e.id AS episode_id, e.number, e.created_at
|
||||
FROM account_stories l
|
||||
JOIN account_networks n ON n.account_id = l.account_id AND n.status != 'disconnected'
|
||||
JOIN episodes e ON e.story_id = l.story_id AND e.status = 'main'`);
|
||||
let publications = 0;
|
||||
let snapshots = 0;
|
||||
for (const t of targets) {
|
||||
if (get("SELECT 1 FROM publications WHERE episode_id = ? AND account_id = ? AND platform = ?", t.episode_id, t.account_id, t.platform)) continue;
|
||||
const r = rng(`${t.account_id}|${t.platform}|${t.episode_id}`);
|
||||
const daysAgo = Math.max(0, 14 - t.number * 2) + Math.floor(r() * 3);
|
||||
const published = new Date(Date.now() - daysAgo * 86_400_000 - Math.floor(r() * 43_200_000));
|
||||
const res = run(`INSERT INTO publications (episode_id, account_id, platform, url, published_at, simulated) VALUES (?, ?, ?, '', ?, 1)`,
|
||||
t.episode_id, t.account_id, t.platform, published.toISOString());
|
||||
const pubId = Number(res.lastInsertRowid);
|
||||
publications++;
|
||||
// Qualidade do episódio (alguns "pegam", outros não) × alcance da rede.
|
||||
const quality = 0.25 + r() * 1.5;
|
||||
const finalViews = Math.round((2_000 + r() * 60_000) * quality * PLATFORM_REACH[t.platform]);
|
||||
const engagement = 0.02 + r() * 0.09 * quality;
|
||||
const completion = Math.min(0.95, 0.2 + r() * 0.45 * quality);
|
||||
for (const [hours, share] of [[1, 0.12], [24, 0.7], [72, 1]] as const) {
|
||||
const at = new Date(published.getTime() + hours * 3_600_000);
|
||||
if (at.getTime() > Date.now()) continue;
|
||||
const views = Math.round(finalViews * share);
|
||||
const interactions = views * engagement;
|
||||
run(`INSERT INTO publication_metrics (publication_id, captured_at, views, likes, comments, shares, saves, avg_watch_s, completion_rate, simulated)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`, pubId, at.toISOString(), views,
|
||||
Math.round(interactions * 0.72), Math.round(interactions * 0.12), Math.round(interactions * 0.09), Math.round(interactions * 0.07),
|
||||
Math.round(12 * completion * 10) / 10, Math.round(completion * 1000) / 1000);
|
||||
snapshots++;
|
||||
}
|
||||
}
|
||||
return { publications, snapshots };
|
||||
}
|
||||
|
||||
/** Apaga tudo que é simulado (publicações e métricas). Dados reais (simulated = 0) ficam. */
|
||||
export function clearSimulated(): number {
|
||||
return Number(run("DELETE FROM publications WHERE simulated = 1").changes);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// Montagem com FFmpeg, sem banco nem estado do painel (testável sozinho): um segmento por trecho
|
||||
// (visual 1080x1920 + texto na tela + legendas + áudio), cartela de créditos e concatenação.
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { findOnPath } from "./proc";
|
||||
|
||||
export type SegmentVisual = { kind: string; file: string | null };
|
||||
/** Recebe o processo em execução (para poder cancelar) e diz se a montagem foi cancelada. */
|
||||
export type JobHook = { onChild: (child: ChildProcess | null) => void; cancelled: () => boolean };
|
||||
export class MontageError extends Error {}
|
||||
|
||||
export const W = 1080;
|
||||
export const H = 1920;
|
||||
export const FPS = 30;
|
||||
/** Respiro depois da fala de cada trecho; o último ganha mais, para o fecho não cortar seco. */
|
||||
export const PAD_S = 0.35;
|
||||
export const LAST_PAD_S = 0.9;
|
||||
export const CREDITS_S = 3.5;
|
||||
|
||||
|
||||
export function ffmpegBin(name: "ffmpeg" | "ffprobe"): string {
|
||||
const fromEnv = process.env[name === "ffmpeg" ? "FFMPEG_BIN" : "FFPROBE_BIN"];
|
||||
const found = fromEnv || findOnPath(name);
|
||||
if (!found) throw new MontageError(`${name} não encontrado no PATH. Instale o FFmpeg (o render do Godot também usa).`);
|
||||
return found;
|
||||
}
|
||||
|
||||
export function fontFile(): string {
|
||||
const candidates = ["C:/Windows/Fonts/segoeuib.ttf", "C:/Windows/Fonts/arialbd.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/System/Library/Fonts/Supplemental/Arial Bold.ttf"];
|
||||
const found = candidates.find((f) => fs.existsSync(f));
|
||||
if (!found) throw new MontageError("Nenhuma fonte em negrito encontrada para o texto na tela.");
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Caminho dentro de um filtro do FFmpeg: barras normais e ":" escapado ("C\:/Windows/..."). */
|
||||
export const filterPath = (p: string) => p.replace(/\\/g, "/").replace(/:/g, "\\:").replace(/'/g, "\\'");
|
||||
|
||||
/** Largura e altura de uma imagem (ffprobe). */
|
||||
async function probeImage(file: string): Promise<{ width: number; height: number }> {
|
||||
const out = await exec(ffmpegBin("ffprobe"), ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", file], path.dirname(file));
|
||||
const [width, height] = out.trim().split("x").map(Number);
|
||||
if (!(width > 0 && height > 0)) throw new MontageError(`Não consegui ler o tamanho da imagem ${path.basename(file)}.`);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
export async function probeDuration(file: string): Promise<number> {
|
||||
const out = await exec(ffmpegBin("ffprobe"), ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file], path.dirname(file));
|
||||
const seconds = Number(out.trim());
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) throw new MontageError("Não consegui medir a duração do áudio.");
|
||||
return seconds;
|
||||
}
|
||||
|
||||
export function exec(bin: string, args: string[], cwd: string, hook?: JobHook): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(bin, args, { cwd, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
||||
hook?.onChild(child);
|
||||
let out = "";
|
||||
let err = "";
|
||||
child.stdout.on("data", (d) => (out += d));
|
||||
child.stderr.on("data", (d) => (err = (err + d).slice(-4000)));
|
||||
child.on("error", reject);
|
||||
child.on("close", (code) => {
|
||||
hook?.onChild(null);
|
||||
if (hook?.cancelled()) return reject(new MontageError("cancelado pelo painel"));
|
||||
return code === 0 ? resolve(out) : reject(new Error(`${path.basename(bin)} saiu com código ${code}: ${err.split("\n").filter(Boolean).slice(-6).join(" | ")}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Quebra a narração em legendas de até ~30 caracteres, com tempo proporcional ao tamanho. */
|
||||
function captionChunks(text: string, duration: number): { text: string; start: number; end: number }[] {
|
||||
const words = text.replace(/\*\*|[*_`]/g, "").split(/\s+/).filter(Boolean);
|
||||
const chunks: string[] = [];
|
||||
let line = "";
|
||||
for (const w of words) {
|
||||
if (line && (line + " " + w).length > 30) { chunks.push(line); line = w; } else line = line ? `${line} ${w}` : w;
|
||||
if (/[.!?]$/.test(w) && line.length > 12) { chunks.push(line); line = ""; }
|
||||
}
|
||||
if (line) chunks.push(line);
|
||||
// Pedaço curto demais ("quadrado.") sozinho na tela pisca: junta ao anterior se couber.
|
||||
for (let i = chunks.length - 1; i > 0; i--) {
|
||||
if (chunks[i].length < 12 && chunks[i - 1].length + chunks[i].length < 40) chunks.splice(i - 1, 2, `${chunks[i - 1]} ${chunks[i]}`);
|
||||
}
|
||||
const total = chunks.reduce((a, c) => a + c.length, 0) || 1;
|
||||
let t = 0.1;
|
||||
const span = Math.max(0.5, duration - 0.3);
|
||||
return chunks.map((c) => {
|
||||
const len = (c.length / total) * span;
|
||||
const item = { text: c, start: t, end: t + len };
|
||||
t += len;
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
function drawText(textFile: string, font: string, opts: { size: number; y: string; box: string; enable?: string }): string {
|
||||
return `drawtext=fontfile='${filterPath(font)}':textfile='${textFile}':expansion=none:fontsize=${opts.size}:fontcolor=white` +
|
||||
`:box=1:boxcolor=${opts.box}:boxborderw=${Math.round(opts.size * 0.35)}:x=(w-text_w)/2:y=${opts.y}` +
|
||||
(opts.enable ? `:enable='${opts.enable}'` : "");
|
||||
}
|
||||
|
||||
export type SegmentPlan = {
|
||||
visual: SegmentVisual; onScreen: string; narration: string; audio: string | null; duration: number; index: number; captions: boolean;
|
||||
/** Cartão de foto sobre a cena (caminho relativo à raiz e crédito). */
|
||||
inset?: { file: string; credit?: string } | null;
|
||||
};
|
||||
|
||||
/** Um segmento: visual 1080x1920 + texto na tela + legendas + áudio, com a duração da fala. */
|
||||
export async function buildSegment(plan: SegmentPlan, dir: string, font: string, repoRoot: string, hook?: JobHook): Promise<string> {
|
||||
const n = String(plan.index + 1).padStart(2, "0");
|
||||
const out = `seg_${n}.mp4`;
|
||||
const d = plan.duration.toFixed(3);
|
||||
const frames = Math.ceil(plan.duration * FPS);
|
||||
const args: string[] = ["-y", "-hide_banner", "-loglevel", "error"];
|
||||
const file = plan.visual.file ? path.join(repoRoot, plan.visual.file) : null;
|
||||
let base: string;
|
||||
let audioInput = 1;
|
||||
if (plan.visual.kind === "card" || !file) {
|
||||
args.push("-f", "lavfi", "-i", `color=c=0x0d0d10:s=${W}x${H}:r=${FPS}:d=${d}`);
|
||||
base = `[0:v]format=yuv420p[bg]`;
|
||||
} else if (plan.visual.kind === "image") {
|
||||
// Zoom lento: os trechos pares aproximam, os ímpares afastam. Escala em 2x antes do zoompan evita tremido.
|
||||
const zoom = plan.index % 2 === 0 ? `min(1+0.08*on/${frames},1.08)` : `max(1.08-0.08*on/${frames},1.0)`;
|
||||
const size = await probeImage(file);
|
||||
const aspect = size.width / size.height;
|
||||
if (aspect > 0.8) {
|
||||
// Foto horizontal num vídeo em pé: cortar o centro cortaria o assunto (a cobra, o farol).
|
||||
// Fica quase inteira no meio, com zoom lento, sobre a própria foto desfocada.
|
||||
const even = (n: number) => Math.round(n / 2) * 2;
|
||||
let fw = even(W * 1.18);
|
||||
let fh = even(fw / aspect);
|
||||
if (fh > H * 0.62) { fh = even(H * 0.62); fw = even(fh * aspect); }
|
||||
const cw = Math.min(fw, W);
|
||||
const top = Math.round((H - fh) / 2 - H * 0.03);
|
||||
args.push("-loop", "1", "-framerate", String(FPS), "-t", d, "-i", file, "-i", file);
|
||||
base = [
|
||||
`[0:v]scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H},boxblur=32:2,eq=brightness=-0.12:saturation=0.85,fps=${FPS},format=yuv420p[bgb]`,
|
||||
`[1:v]scale=${fw * 2}:${fh * 2},zoompan=z='${zoom}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${fw}x${fh}:fps=${FPS},crop=${cw}:${fh},format=yuv420p[fg]`,
|
||||
`[bgb][fg]overlay=x=(W-w)/2:y=${top}:shortest=1,format=yuv420p[bg]`,
|
||||
].join(";\n");
|
||||
audioInput = 2;
|
||||
} else {
|
||||
args.push("-i", file);
|
||||
base = `[0:v]scale=${W * 2}:${H * 2}:force_original_aspect_ratio=increase,crop=${W * 2}:${H * 2},` +
|
||||
`zoompan=z='${zoom}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${W}x${H}:fps=${FPS},format=yuv420p[bg]`;
|
||||
}
|
||||
} else {
|
||||
args.push("-stream_loop", "-1", "-i", file);
|
||||
base = `[0:v]scale=${W}:${H}:force_original_aspect_ratio=increase,crop=${W}:${H},fps=${FPS},format=yuv420p[bg]`;
|
||||
}
|
||||
if (plan.audio) args.push("-i", path.join(repoRoot, plan.audio));
|
||||
else args.push("-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo");
|
||||
|
||||
const layers: string[] = [];
|
||||
// Cartão de foto sobre a cena (ex.: a foto real da cobra sobre a ilha 3D): borda branca, entra
|
||||
// subindo com fade em 0,35 s e sai no fim; crédito pequeno embaixo.
|
||||
let stage = "bg";
|
||||
if (plan.inset?.file) {
|
||||
const insetFile = path.join(repoRoot, plan.inset.file);
|
||||
const size = await probeImage(insetFile);
|
||||
const cw = Math.round(W * 0.62 / 2) * 2;
|
||||
const ch = Math.round((cw * size.height) / size.width / 2) * 2;
|
||||
const border = 12;
|
||||
const top = Math.round(H * 0.21);
|
||||
const insetInput = audioInput + 1;
|
||||
args.push("-loop", "1", "-framerate", String(FPS), "-t", d, "-i", insetFile);
|
||||
const outAt = Math.max(0.6, plan.duration - 0.4).toFixed(2);
|
||||
base += `;\n[${insetInput}:v]scale=${cw}:${ch},pad=${cw + border * 2}:${ch + border * 2}:${border}:${border}:color=white,format=rgba,` +
|
||||
`fade=in:st=0.3:d=0.35:alpha=1,fade=out:st=${outAt}:d=0.3:alpha=1[card];\n` +
|
||||
`[bg][card]overlay=x=(W-w)/2:y='${top}+50*max(0\\,1-(t-0.3)/0.35)':eval=frame:shortest=1[bgcard]`;
|
||||
stage = "bgcard";
|
||||
if (plan.inset.credit) {
|
||||
fs.writeFileSync(path.join(dir, `t${n}_credito.txt`), `Foto: ${plan.inset.credit}`, "utf8");
|
||||
layers.push(`drawtext=fontfile='${filterPath(font)}':textfile='t${n}_credito.txt':expansion=none:fontsize=24:fontcolor=white@0.85` +
|
||||
`:box=1:boxcolor=black@0.45:boxborderw=8:x=(w-text_w)/2:y=${top + ch + border * 2 + 14}:enable='between(t,0.65,${outAt})'`);
|
||||
}
|
||||
}
|
||||
if (plan.onScreen) {
|
||||
// "A; depois: B; depois: C" = cartões de informação em sequência dentro do trecho.
|
||||
const parts = plan.onScreen.split(/\s*;\s*depois:\s*/i).map((p) => p.trim()).filter(Boolean);
|
||||
const slot = plan.duration / parts.length;
|
||||
parts.forEach((text, k) => {
|
||||
const name = `t${n}_tela${k}.txt`;
|
||||
fs.writeFileSync(path.join(dir, name), text, "utf8");
|
||||
const start = k === 0 ? 0.15 : k * slot;
|
||||
const end = k === parts.length - 1 ? plan.duration + 1 : (k + 1) * slot;
|
||||
const enable = `between(t,${start.toFixed(2)},${end.toFixed(2)})`;
|
||||
layers.push(plan.visual.kind === "card" || !file
|
||||
? drawText(name, font, { size: 84, y: "(h-text_h)/2", box: "0x0d0d10@0", enable })
|
||||
: drawText(name, font, { size: text.length > 26 ? 54 : 66, y: "h*0.13", box: "black@0.62", enable }));
|
||||
});
|
||||
}
|
||||
if (plan.captions && plan.narration) {
|
||||
captionChunks(plan.narration, plan.duration).forEach((c, i) => {
|
||||
const name = `t${n}_leg${i}.txt`;
|
||||
fs.writeFileSync(path.join(dir, name), c.text, "utf8");
|
||||
layers.push(drawText(name, font, { size: 52, y: "h*0.74", box: "black@0.55", enable: `between(t,${c.start.toFixed(2)},${c.end.toFixed(2)})` }));
|
||||
});
|
||||
}
|
||||
const graph = [base, `[${stage}]${layers.length ? layers.join(",") : "null"}[v]`, `[${audioInput}:a]apad,aresample=48000,aformat=channel_layouts=stereo[a]`].join(";\n");
|
||||
fs.writeFileSync(path.join(dir, `seg_${n}.filter`), graph, "utf8");
|
||||
args.push("-filter_complex_script", `seg_${n}.filter`, "-map", "[v]", "-map", "[a]", "-t", d,
|
||||
"-r", String(FPS), "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-ac", "2", out);
|
||||
await exec(ffmpegBin("ffmpeg"), args, dir, hook);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
/** Cartela final com créditos das imagens e fontes do roteiro (texto centralizado, sem áudio). */
|
||||
export async function buildCredits(lines: string[], dir: string, font: string, hook?: JobHook): Promise<string> {
|
||||
fs.writeFileSync(path.join(dir, "creditos.txt"), lines.join("\n"), "utf8");
|
||||
const graph = `[0:v]drawtext=fontfile='${filterPath(font)}':textfile='creditos.txt':expansion=none:fontsize=38:line_spacing=14:fontcolor=white@0.92:x=(w-text_w)/2:y=(h-text_h)/2,format=yuv420p[v]`;
|
||||
fs.writeFileSync(path.join(dir, "creditos.filter"), graph, "utf8");
|
||||
const out = "seg_99_creditos.mp4";
|
||||
await exec(ffmpegBin("ffmpeg"), ["-y", "-hide_banner", "-loglevel", "error",
|
||||
"-f", "lavfi", "-i", `color=c=0x0d0d10:s=${W}x${H}:r=${FPS}:d=${CREDITS_S}`, "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo",
|
||||
"-filter_complex_script", "creditos.filter", "-map", "[v]", "-map", "1:a", "-t", String(CREDITS_S),
|
||||
"-r", String(FPS), "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
|
||||
"-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-ac", "2", out], dir, hook);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Junta os segmentos (mesmo codec e parâmetros) sem recodificar. Devolve a duração final em segundos. */
|
||||
export async function concatSegments(segments: string[], dir: string, finalName: string, hook?: JobHook): Promise<number> {
|
||||
fs.writeFileSync(path.join(dir, "concat.txt"), segments.map((s) => `file '${s}'`).join("\n") + "\n", "utf8");
|
||||
await exec(ffmpegBin("ffmpeg"), ["-y", "-hide_banner", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", "concat.txt",
|
||||
"-c", "copy", "-movflags", "+faststart", finalName], dir, hook);
|
||||
return probeDuration(path.join(dir, finalName));
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Cenas do Godot para a montagem documental (godot/scenes/doc.tscn: 2D e 3D), sem banco:
|
||||
// - planShot: escolhe o visual de cada trecho por regras (sem IA, instantâneo):
|
||||
// lugares/km → mapa 2D; número na tela → contador 2D; animal/objeto real → foto da internet;
|
||||
// ilha/mar/farol/vista aérea → ilha 3D; resto → título 2D;
|
||||
// - planScene: o modelo 2D (mapa, contador ou título) a partir do texto;
|
||||
// - renderGodotScene: grava o JSON da cena e chama o MESMO lançador do `pnpm render`
|
||||
// (scripts/cli.ts), que valida, renderiza, converte e verifica. Devolve o MP4.
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { JobHook } from "./montage-ffmpeg";
|
||||
import { matchLibrary, paramsFor, type LibraryScene } from "./scene-library";
|
||||
|
||||
export type Doc2DTemplate = "title" | "counter" | "map";
|
||||
/** Cena 3D = nome de uma pasta da biblioteca (godot/library/<id>), como "island". */
|
||||
export type Doc3DTemplate = string;
|
||||
/** Cena do Godot: 2D (motion graphics) ou 3D. kind ausente = 2D (dados antigos). */
|
||||
export type Doc2DScene = { kind?: "doc2d" | "doc3d"; template: Doc2DTemplate | Doc3DTemplate; params: Record<string, unknown> };
|
||||
|
||||
|
||||
export const DOC2D_TEMPLATES: { id: Doc2DTemplate; label: string }[] = [
|
||||
{ id: "title", label: "Título animado" },
|
||||
{ id: "counter", label: "Contador / infográfico" },
|
||||
{ id: "map", label: "Mapa" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Lugares que o preset "litoral-sp" do Godot conhece (doc2d_canvas.gd, PRESETS.places).
|
||||
* Mantenha as duas listas iguais: o Godot resolve lat/lon pelo nome.
|
||||
*/
|
||||
export const MAP_PLACES = [
|
||||
"Ilha da Queimada Grande", "Ilha da Queimada Pequena", "São Paulo", "Santos", "Guarujá", "São Vicente",
|
||||
"Praia Grande", "Mongaguá", "Itanhaém", "Peruíbe", "Bertioga",
|
||||
];
|
||||
|
||||
type ShotText = { narration: string; onScreen: string; visualHint: string };
|
||||
|
||||
const clean = (s: string) => s.replace(/\*\*|__|[*_`]/g, "").replace(/\s+/g, " ").trim();
|
||||
|
||||
/** Modelo e parâmetros de um trecho a partir do texto do roteiro. */
|
||||
export function planScene(shot: ShotText): Doc2DScene {
|
||||
const onScreen = clean(shot.onScreen);
|
||||
const all = clean(`${shot.onScreen} ${shot.narration} ${shot.visualHint}`);
|
||||
const lower = all.toLowerCase();
|
||||
|
||||
// Mapa: lugares do dicionário citados no trecho (a ilha conta mesmo citada como "a ilha").
|
||||
// "São Paulo" só como cidade ("cidade de São Paulo", "capital"): "litoral de São Paulo" é o estado.
|
||||
const places = MAP_PLACES.filter((p) => p === "São Paulo"
|
||||
? /cidade de São Paulo|capital paulista|capital/i.test(all)
|
||||
: lower.includes(p.toLowerCase()) || (p === "Ilha da Queimada Grande" && /queimada grande/i.test(all)));
|
||||
const asksMap = /\bmapa\b|litoral|\bkm\b|quil[oô]metros/i.test(all);
|
||||
if (places.length >= 2 || (places.length >= 1 && asksMap)) {
|
||||
const markers = places.map((label) => ({ label }));
|
||||
const island = places.find((p) => p.startsWith("Ilha"));
|
||||
const city = places.find((p) => !p.startsWith("Ilha") && p !== "São Paulo");
|
||||
if (!island && /queimada|ilha/i.test(all)) markers.push({ label: "Ilha da Queimada Grande" });
|
||||
const km = /(\d+(?:[.,]\d+)?)\s*(?:km|quil[oô]metros)/i.exec(all);
|
||||
const target = island ?? (markers.some((m) => m.label === "Ilha da Queimada Grande") ? "Ilha da Queimada Grande" : undefined);
|
||||
return {
|
||||
template: "map",
|
||||
params: {
|
||||
preset: "litoral-sp",
|
||||
title: onScreen || "Litoral de São Paulo",
|
||||
markers,
|
||||
...(city && target ? { route: { from: city, to: target, ...(km ? { label: `${km[1]} km` } : {}) } } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Contador: número no texto na tela ("55 por hectare", "Há cerca de 11 mil anos").
|
||||
const num = /(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?(\s*mil\b)?/.exec(onScreen);
|
||||
if (num) {
|
||||
const value = Number(num[1].replace(/\./g, "") + (num[2] ? `.${num[2]}` : ""));
|
||||
const before = clean(onScreen.slice(0, num.index));
|
||||
let after = clean(onScreen.slice(num.index + num[0].length));
|
||||
// Rótulo mais completo vindo da narração: "55 jararacas por hectare" em vez de "por hectare".
|
||||
const escaped = num[1].replace(/\./g, "\\.");
|
||||
const fuller = new RegExp(`(?<![\\d.,])${escaped}\\s+(\\p{L}+(?:\\s+\\p{L}+){0,3})`, "u").exec(clean(shot.narration));
|
||||
if (fuller && after && fuller[1].toLowerCase().endsWith(after.toLowerCase()) && fuller[1].length > after.length) after = fuller[1];
|
||||
return {
|
||||
template: "counter",
|
||||
params: {
|
||||
value, decimals: num[2] ? num[2].length : 0,
|
||||
suffix: num[3] ? " mil" : "",
|
||||
kicker: after ? before : "",
|
||||
label: after || before,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Título animado com o texto na tela (ou a primeira frase da narração).
|
||||
const firstSentence = clean(shot.narration).split(/(?<=[.!?])\s/)[0] ?? "";
|
||||
return { template: "title", params: { title: onScreen || firstSentence.slice(0, 90) } };
|
||||
}
|
||||
|
||||
/** Chave da cena renderizada: muda se o modelo, os parâmetros ou a duração mudarem. */
|
||||
export function sceneKey(scene: Doc2DScene, durationSeconds: number): string {
|
||||
let h = 0;
|
||||
for (const ch of JSON.stringify([scene.kind ?? "doc2d", scene.template, scene.params, durationSeconds.toFixed(2)])) h = (Math.imul(h, 31) + ch.codePointAt(0)!) | 0;
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza a cena no Godot (perfil final, 1080x1920) pelo lançador do projeto e devolve o MP4
|
||||
* (caminho relativo à raiz). O lançador tem trava própria: um render por vez no computador.
|
||||
*/
|
||||
export async function renderGodotScene(input: {
|
||||
repoRoot: string; configFile: string; id: string; scene: Doc2DScene; durationSeconds: number; hook?: JobHook;
|
||||
}): Promise<string> {
|
||||
const config = {
|
||||
id: input.id, kind: input.scene.kind ?? "doc2d",
|
||||
video: { width: 1080, height: 1920, fps: 30, durationSeconds: Math.round(input.durationSeconds * 1000) / 1000 },
|
||||
template: input.scene.template, params: input.scene.params,
|
||||
};
|
||||
fs.mkdirSync(path.dirname(input.configFile), { recursive: true });
|
||||
fs.writeFileSync(input.configFile, JSON.stringify(config, null, 2) + "\n", "utf8");
|
||||
const tsxCli = path.join(input.repoRoot, "node_modules", "tsx", "dist", "cli.mjs");
|
||||
if (!fs.existsSync(tsxCli)) throw new Error("tsx não encontrado; rode pnpm install na raiz do projeto.");
|
||||
const rel = path.relative(input.repoRoot, input.configFile).split(path.sep).join("/");
|
||||
const output = await new Promise<string>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [tsxCli, "scripts/cli.ts", "render", "--config", rel, "--profile", "final"], {
|
||||
cwd: input.repoRoot, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
input.hook?.onChild(child);
|
||||
let out = "";
|
||||
child.stdout.on("data", (d) => (out += d));
|
||||
child.stderr.on("data", (d) => (out += d));
|
||||
child.on("error", reject);
|
||||
child.on("close", (code) => {
|
||||
input.hook?.onChild(null);
|
||||
if (input.hook?.cancelled()) return reject(new Error("cancelado pelo painel"));
|
||||
if (code !== 0) {
|
||||
const reason = /FALHOU na etapa[^\n]*/.exec(out)?.[0] ?? out.split("\n").filter(Boolean).slice(-4).join(" | ");
|
||||
return reject(new Error(`render Godot da cena ${input.id}: ${reason}`));
|
||||
}
|
||||
resolve(out);
|
||||
});
|
||||
});
|
||||
const mp4 = /MP4: (\S+\.mp4)/.exec(output)?.[1];
|
||||
if (!mp4 || !fs.existsSync(path.join(input.repoRoot, mp4))) throw new Error(`render Godot da cena ${input.id}: MP4 não encontrado na saída do lançador`);
|
||||
return mp4;
|
||||
}
|
||||
|
||||
/** O que o modo automático decide para um trecho. */
|
||||
export type ShotPlan =
|
||||
| { kind: "godot2d"; scene: Doc2DScene }
|
||||
| { kind: "godot3d"; scene: Doc2DScene }
|
||||
| { kind: "image"; queries: string[]; fallback: Doc2DScene };
|
||||
|
||||
/** Nomes do roteiro que viram termo de busca: itálicos (nome científico) e lugares conhecidos. */
|
||||
export function scriptEntities(markdown: string): { species: string[]; places: string[] } {
|
||||
const italics = [...markdown.matchAll(/(?<!\*)\*([A-Z][a-z]+ [a-z]{3,})\*(?!\*)/g)].map((m) => m[1]);
|
||||
const places = MAP_PLACES.filter((p) => markdown.toLowerCase().includes(p.toLowerCase().replace(/^ilha da /, "")));
|
||||
return { species: [...new Set(italics)], places };
|
||||
}
|
||||
|
||||
const ANIMAL = /\b(cobras?|jararacas?(?:-ilhoa)?|serpentes?|ofídio|animal|animais|aves?|pássaros?|bichos?|filhotes?|ninho|espécie)\b/i;
|
||||
const SNAKE = /\b(cobras?|jararacas?(?:-ilhoa)?|serpentes?)\b/i;
|
||||
const REAL_THING = /\b(placa|pesquisador(?:es)?|cientistas?|equipamento|navio|barco|foto|fotografia)\b/i;
|
||||
|
||||
/**
|
||||
* Plano automático de um trecho. A ordem importa: mapa e contador (infográfico) primeiro,
|
||||
* depois foto real (animal ou objeto citado na coluna Imagem), depois a ilha 3D, e título.
|
||||
*/
|
||||
export function planShot(shot: ShotText, ctx: { species: string[]; places: string[]; library?: LibraryScene[] }, variant = 0): ShotPlan {
|
||||
const scene2d = planScene(shot);
|
||||
if (scene2d.template === "map" || scene2d.template === "counter") return { kind: "godot2d", scene: { kind: "doc2d", ...scene2d, params: { ...scene2d.params, variant } } };
|
||||
const hint = clean(shot.visualHint);
|
||||
const island = ctx.places.find((p) => p.startsWith("Ilha"));
|
||||
const firstClause = hint.split(/[;.]/)[0] ?? hint;
|
||||
|
||||
// Foto real: o que o roteiro pede primeiro na coluna Imagem é um animal ou um objeto real.
|
||||
if (ANIMAL.test(firstClause) || REAL_THING.test(firstClause)) {
|
||||
const queries: string[] = [];
|
||||
if (SNAKE.test(hint)) queries.push(...ctx.species);
|
||||
if (/farol/i.test(hint) && island) queries.push(`Farol ${island}`);
|
||||
if (REAL_THING.test(firstClause) && island) queries.push(island);
|
||||
queries.push(...ctx.species, ...(island ? [island] : []));
|
||||
const unique = [...new Set(queries)].filter(Boolean);
|
||||
if (unique.length) return { kind: "image", queries: unique, fallback: { kind: "doc2d", ...scene2d } };
|
||||
}
|
||||
|
||||
// Cena 3D da biblioteca (godot/library): a que mais combina com a coluna Imagem do roteiro.
|
||||
const match = matchLibrary(hint, ctx.library ?? []);
|
||||
if (match) {
|
||||
return { kind: "godot3d", scene: { kind: "doc3d", template: match.scene.id, params: { ...paramsFor(match.scene, hint), variant } } };
|
||||
}
|
||||
return { kind: "godot2d", scene: { kind: "doc2d", ...scene2d, params: { ...scene2d.params, variant } } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plano de um trecho no modo "Tudo em 3D": sempre uma cena 3D da biblioteca (a que mais combina
|
||||
* com o trecho; senão a primeira), com o ângulo variando entre trechos, e um cartão de foto real
|
||||
* por cima quando o roteiro pede (animal/objeto real na coluna Imagem, ou "[foto: termos]").
|
||||
*/
|
||||
export function planShot3d(shot: ShotText, ctx: { species: string[]; places: string[]; library?: LibraryScene[] }, index: number): { scene: Doc2DScene; insetQueries: string[] } | null {
|
||||
const lib3d = (ctx.library ?? []).filter((s) => s.kind === "doc3d");
|
||||
if (!lib3d.length) return null;
|
||||
const hint = clean(shot.visualHint);
|
||||
const text = `${hint} ${clean(shot.narration)}`;
|
||||
const chosen = matchLibrary(hint, lib3d)?.scene ?? matchLibrary(text, lib3d)?.scene ?? lib3d[0];
|
||||
const scene: Doc2DScene = { kind: "doc3d", template: chosen.id, params: { ...paramsFor(chosen, hint), variant: index } };
|
||||
const insetQueries: string[] = [];
|
||||
const tag = /\[?\s*foto:\s*([^\]\n;]+)\]?/i.exec(shot.visualHint);
|
||||
if (tag) insetQueries.push(tag[1].trim());
|
||||
const firstClause = hint.split(/[;.]/)[0] ?? hint;
|
||||
// No 3D o barco, o navio e o personagem são da cena: o cartão de foto fica para animal real
|
||||
// (a cobra) ou quando o roteiro pede explicitamente "[foto: ...]".
|
||||
if (!tag && ANIMAL.test(firstClause)) {
|
||||
if (SNAKE.test(hint)) insetQueries.push(...ctx.species);
|
||||
insetQueries.push(...ctx.species);
|
||||
}
|
||||
return { scene, insetQueries: [...new Set(insetQueries)].filter(Boolean) };
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
// Montagem do vídeo documental. Cada trecho do roteiro (linha da tabela "t (s)") vira:
|
||||
// - um ÁUDIO próprio, gerado parágrafo a parágrafo pelo serviço de voz (frase longa numa
|
||||
// tacada só deixa a voz estranha) a partir do "texto falado" (números por extenso);
|
||||
// - um VISUAL: imagem (com movimento lento), clipe de vídeo, cena 3D renderizada pelo Godot,
|
||||
// ou cartela de texto. O trecho dura o tempo do próprio áudio.
|
||||
// Depois o FFmpeg monta um segmento por trecho (visual + texto na tela + legenda + áudio) e
|
||||
// concatena tudo num MP4 vertical 1080x1920. O estado fica em stories/<id>/<file_key>.montage.json.
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createAsset } from "./assets";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { DATA_DIR, OUTPUT_DIR, REPO_ROOT, STORIES_DIR, readTextIfExists, rel, resolveInside, storyDir } from "./paths";
|
||||
import { LAST_PAD_S, PAD_S, buildCredits, buildSegment, concatSegments, ffmpegBin, fontFile, probeDuration, type JobHook } from "./montage-ffmpeg";
|
||||
import { downloadImage, searchFirst } from "./image-search";
|
||||
import { DOC2D_TEMPLATES, planScene, planShot, planShot3d, renderGodotScene, sceneKey, scriptEntities, type Doc2DScene } from "./montage-godot";
|
||||
import { listLibrary, paramsFor } from "./scene-library";
|
||||
import { killTree } from "./proc";
|
||||
import { parseScript } from "./script-doc";
|
||||
import { toSpokenText } from "./speech-text";
|
||||
import { UserError, getEpisodeById, getStory, touchStory } from "./stories";
|
||||
import type { AssetKind, EpisodeView, RenderJob } from "./types";
|
||||
import { getStatus, synthesize } from "./voice";
|
||||
|
||||
export type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d";
|
||||
|
||||
/** Estilos de visual por trecho (dá para misturar no mesmo vídeo). */
|
||||
export const VISUAL_KINDS: { id: VisualKind; label: string; available: boolean; hint: string }[] = [
|
||||
{ id: "image", label: "Foto", available: true, hint: "Foto da internet (busca automática) ou enviada por você, com zoom lento." },
|
||||
{ id: "godot2d", label: "Animação 2D", available: true, hint: "Mapa, infográfico ou título animados no Godot, com o tempo exato da fala." },
|
||||
{ id: "godot3d", label: "Cena 3D", available: true, hint: "Cena 3D da biblioteca do Godot (ilha, estádio...), com a câmera e as opções da cena." },
|
||||
{ id: "video", label: "Clipe", available: true, hint: "Um clipe enviado por você ou um vídeo já renderizado no painel." },
|
||||
{ id: "card", label: "Cartela", available: true, hint: "Fundo escuro com o texto na tela em destaque." },
|
||||
];
|
||||
|
||||
export type ShotVisual = {
|
||||
kind: VisualKind; file: string | null; credit: string; license: string; sourceUrl: string;
|
||||
/** godot2d: modelo e parâmetros da cena; sceneKey diz com que versão o "file" foi renderizado. */
|
||||
scene?: Doc2DScene; sceneKey?: string;
|
||||
/** Imagem da internet: buscas usadas e qual resultado está em uso ("gerar de novo" pega o próximo). */
|
||||
search?: { queries: string[]; pick: number };
|
||||
/** Cartão de foto por cima da cena (modo 3D): a foto real da cobra sobre a ilha, por exemplo. */
|
||||
inset?: { file: string; credit: string; license: string; sourceUrl: string; search?: { queries: string[]; pick: number } } | null;
|
||||
/** Escolhido pelo modo automático (o "Refazer tudo do zero" replaneja só estes). */
|
||||
auto?: boolean;
|
||||
};
|
||||
export type ShotAudio = { file: string; durationMs: number; key: string };
|
||||
export type MontageShot = {
|
||||
index: number;
|
||||
time: string;
|
||||
narration: string;
|
||||
onScreen: string;
|
||||
/** O que o roteiro pede de imagem (orientação para escolher o visual). */
|
||||
visualHint: string;
|
||||
/** Texto que a voz fala: o editado pelo admin ou o gerado do roteiro (números por extenso). */
|
||||
spoken: string;
|
||||
spokenEdited: boolean;
|
||||
visual: ShotVisual;
|
||||
audio: ShotAudio | null;
|
||||
/** O áudio existe mas foi gerado com outro texto, voz ou velocidade. */
|
||||
audioStale: boolean;
|
||||
};
|
||||
export type Montage = {
|
||||
episodeId: number;
|
||||
voiceId: string;
|
||||
speed: number;
|
||||
captions: boolean;
|
||||
style: "mixed" | "3d";
|
||||
shots: MontageShot[];
|
||||
/** Fontes do roteiro (domínios), para a cartela final. */
|
||||
sourceHosts: string[];
|
||||
};
|
||||
|
||||
type SavedShot = { spoken?: string; visual?: ShotVisual; audio?: ShotAudio };
|
||||
/** style: "mixed" (foto, 2D e 3D, o que combinar) ou "3d" (tudo em cena 3D; fotos em cartão por cima). */
|
||||
type SavedMontage = { version: 1; voiceId: string; speed: number; captions: boolean; style?: "mixed" | "3d"; shots: Record<string, SavedShot> };
|
||||
|
||||
const EMPTY_VISUAL: ShotVisual = { kind: "image", file: null, credit: "", license: "", sourceUrl: "" };
|
||||
/** Pastas de onde um visual pode vir (nada fora do projeto). */
|
||||
const VISUAL_ROOTS = [STORIES_DIR, OUTPUT_DIR, path.join(REPO_ROOT, "assets")];
|
||||
|
||||
const montagePath = (ep: EpisodeView) => path.join(storyDir(ep.story_id), `${ep.file_key}.montage.json`);
|
||||
const audioDir = (ep: EpisodeView) => path.join(storyDir(ep.story_id), "audio");
|
||||
|
||||
function episodeOrThrow(episodeId: number): EpisodeView {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Vídeo não encontrado.");
|
||||
return ep;
|
||||
}
|
||||
|
||||
function readSaved(ep: EpisodeView): SavedMontage {
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(montagePath(ep), "utf8")) as SavedMontage;
|
||||
if (data && data.version === 1 && typeof data.shots === "object") return data;
|
||||
} catch { /* ainda não existe */ }
|
||||
return { version: 1, voiceId: "", speed: 1, captions: true, shots: {} };
|
||||
}
|
||||
|
||||
function writeSaved(ep: EpisodeView, data: SavedMontage): void {
|
||||
fs.writeFileSync(montagePath(ep), JSON.stringify(data, null, 2) + "\n", "utf8");
|
||||
touchStory(ep.story_id);
|
||||
}
|
||||
|
||||
/** Chave do áudio: muda se o texto falado, a voz ou a velocidade mudarem (áudio fica desatualizado). */
|
||||
function audioKey(voiceId: string, speed: number, spoken: string): string {
|
||||
let h = 0;
|
||||
for (const ch of `${voiceId}|${speed}|${spoken}`) h = (Math.imul(h, 31) + ch.codePointAt(0)!) | 0;
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
export function loadMontage(episodeId: number): Montage {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const script = readTextIfExists(path.join(REPO_ROOT, ep.scriptPath));
|
||||
if (!script) throw new UserError("Escreva o roteiro antes de montar o vídeo.");
|
||||
const doc = parseScript(script);
|
||||
if (doc.shots.length === 0) throw new UserError("O roteiro não tem a tabela de trechos (coluna \"t (s)\"). Revise o roteiro.");
|
||||
const saved = readSaved(ep);
|
||||
const shots = doc.shots.map((s): MontageShot => {
|
||||
const own = saved.shots[String(s.index)] ?? {};
|
||||
// Texto na tela que é pergunta e a narração não repete ("Uma cobra por m²?" + "Não. ..."):
|
||||
// a voz pergunta antes de responder.
|
||||
const question = s.onScreen.replace(/\*\*|__|[*_`]/g, "").replace(/^["“](.*)["”]$/, "$1").trim();
|
||||
const asks = question.endsWith("?") && !s.narration.toLowerCase().includes(question.slice(0, -1).toLowerCase());
|
||||
const spoken = own.spoken ?? toSpokenText(asks ? `${question} ${s.narration}` : s.narration);
|
||||
const audio = own.audio && fs.existsSync(path.join(REPO_ROOT, own.audio.file)) ? own.audio : null;
|
||||
return {
|
||||
index: s.index, time: s.time, narration: s.narration,
|
||||
// Sem marcas de markdown: o itálico do nome científico viraria asterisco no vídeo.
|
||||
onScreen: s.onScreen.replace(/\*\*|__|[*_`]/g, "").replace(/^["“](.*)["”]$/, "$1").trim(), visualHint: s.visual,
|
||||
spoken, spokenEdited: own.spoken !== undefined,
|
||||
visual: { ...EMPTY_VISUAL, ...own.visual },
|
||||
audio, audioStale: !!audio && audio.key !== audioKey(saved.voiceId, saved.speed, spoken),
|
||||
};
|
||||
});
|
||||
const sources = doc.sections.find((s) => s.role === "sources");
|
||||
const sourceHosts = [...new Set((sources ? JSON.stringify(sources.blocks) : "").match(/https?:\/\/[^/\s"]+/g) ?? [])]
|
||||
.map((u) => u.replace(/^https?:\/\/(www\.)?/, ""));
|
||||
return { episodeId, voiceId: saved.voiceId, speed: saved.speed, captions: saved.captions, style: saved.style ?? "mixed", shots, sourceHosts };
|
||||
}
|
||||
|
||||
/** Ajustes da montagem: voz, velocidade, legenda e, por trecho, texto falado e visual. */
|
||||
export function updateMontage(episodeId: number, patch: {
|
||||
voiceId?: unknown; speed?: unknown; captions?: unknown; style?: unknown;
|
||||
shot?: { index?: unknown; spoken?: unknown; resetSpoken?: unknown; visual?: Partial<Record<keyof ShotVisual, unknown>> };
|
||||
}): Montage {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const current = loadMontage(episodeId);
|
||||
const saved = readSaved(ep);
|
||||
if (patch.voiceId !== undefined) {
|
||||
const voiceId = String(patch.voiceId);
|
||||
if (voiceId && !/^[a-z0-9][a-z0-9_.:-]{0,95}$/i.test(voiceId)) throw new UserError("Voz inválida.");
|
||||
saved.voiceId = voiceId;
|
||||
}
|
||||
if (patch.speed !== undefined) {
|
||||
const speed = Number(patch.speed);
|
||||
if (!(speed >= 0.5 && speed <= 2)) throw new UserError("Velocidade precisa estar entre 0,5 e 2.");
|
||||
saved.speed = Math.round(speed * 100) / 100;
|
||||
}
|
||||
if (patch.captions !== undefined) saved.captions = Boolean(patch.captions);
|
||||
if (patch.style !== undefined) saved.style = patch.style === "3d" ? "3d" : "mixed";
|
||||
if (patch.shot) {
|
||||
const index = Number(patch.shot.index);
|
||||
const shot = current.shots.find((s) => s.index === index);
|
||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||
const own = (saved.shots[String(index)] ??= {});
|
||||
if (patch.shot.resetSpoken) delete own.spoken;
|
||||
else if (patch.shot.spoken !== undefined) {
|
||||
const spoken = String(patch.shot.spoken).replace(/\s+/g, " ").trim();
|
||||
if (spoken.length > 1500) throw new UserError("Texto falado longo demais (máx. 1.500 caracteres por trecho).");
|
||||
own.spoken = spoken;
|
||||
}
|
||||
if (patch.shot.visual) {
|
||||
const v = patch.shot.visual;
|
||||
const next: ShotVisual = { ...EMPTY_VISUAL, ...own.visual };
|
||||
if (v.kind !== undefined) {
|
||||
const kind = VISUAL_KINDS.find((k) => k.id === v.kind);
|
||||
if (!kind?.available) throw new UserError("Esse estilo de visual ainda não está disponível.");
|
||||
next.kind = kind.id;
|
||||
}
|
||||
if (v.file !== undefined) {
|
||||
const file = v.file === null || v.file === "" ? null : String(v.file);
|
||||
if (file && !resolveInside(file, VISUAL_ROOTS)) throw new UserError("O arquivo precisa estar dentro do projeto (stories/, assets/ ou output/).");
|
||||
if (file && !fs.existsSync(path.join(REPO_ROOT, file))) throw new UserError("Arquivo não encontrado.");
|
||||
next.file = file;
|
||||
}
|
||||
for (const key of ["credit", "license", "sourceUrl"] as const) {
|
||||
if (v[key] !== undefined) next[key] = String(v[key]).trim().slice(0, 300);
|
||||
}
|
||||
if (next.sourceUrl && !/^https?:\/\//i.test(next.sourceUrl)) throw new UserError("O link da fonte precisa começar com http:// ou https://.");
|
||||
// Cena 2D do Godot: modelo/parâmetros vindos do painel, ou o plano automático do trecho.
|
||||
if (v.scene !== undefined) next.scene = validScene(v.scene);
|
||||
// Cena do Godot coerente com o estilo: 2D (mapa/contador/título) ou 3D (ilha).
|
||||
if (next.kind === "godot2d" && (!next.scene || next.scene.kind === "doc3d")) next.scene = { kind: "doc2d", ...planScene(shot) };
|
||||
if (next.kind === "godot3d" && next.scene?.kind !== "doc3d") {
|
||||
// A cena 3D da biblioteca que combina com o trecho, ou a primeira da biblioteca.
|
||||
const plan = planShot(shot, { species: [], places: [], library: listLibrary() });
|
||||
const first = listLibrary().find((s) => s.kind === "doc3d");
|
||||
if (plan.kind === "godot3d") next.scene = plan.scene;
|
||||
else if (first) next.scene = { kind: "doc3d", template: first.id, params: { ...paramsFor(first, shot.visualHint), variant: 0 } };
|
||||
else throw new UserError("A biblioteca de cenas 3D está vazia: peça uma cena ao agente (tarefa \"Cena no Godot\").");
|
||||
}
|
||||
if (next.kind !== "godot2d" && next.kind !== "godot3d") { delete next.scene; delete next.sceneKey; }
|
||||
if (next.kind !== "image") delete next.search;
|
||||
next.auto = false;
|
||||
own.visual = next;
|
||||
}
|
||||
}
|
||||
writeSaved(ep, saved);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
|
||||
function validScene(raw: unknown): Doc2DScene {
|
||||
const s = raw as { template?: unknown; params?: unknown };
|
||||
const kind = (s as { kind?: unknown })?.kind === "doc3d" ? "doc3d" : "doc2d";
|
||||
const templates: { id: string }[] = kind === "doc3d" ? listLibrary().filter((l) => l.kind === "doc3d") : DOC2D_TEMPLATES;
|
||||
if (!s || !templates.some((t) => t.id === s.template)) throw new UserError("Modelo de cena inválido.");
|
||||
if (!s.params || typeof s.params !== "object" || Array.isArray(s.params)) throw new UserError("Parâmetros da cena 2D inválidos.");
|
||||
if (JSON.stringify(s.params).length > 4000) throw new UserError("Parâmetros da cena 2D grandes demais.");
|
||||
return { kind, template: s.template as Doc2DScene["template"], params: s.params as Record<string, unknown> };
|
||||
}
|
||||
|
||||
/** Duração do trecho no vídeo: a fala + uma pausa curta (a última, mais longa). */
|
||||
function shotDuration(montage: Montage, shot: MontageShot): number {
|
||||
const last = shot.index === montage.shots[montage.shots.length - 1].index;
|
||||
return shot.audio!.durationMs / 1000 + (last ? LAST_PAD_S : PAD_S);
|
||||
}
|
||||
|
||||
/** A cena 2D já renderizada vale para este trecho (mesmo modelo, parâmetros e duração)? */
|
||||
function sceneIsCurrent(montage: Montage, shot: MontageShot): boolean {
|
||||
const v = shot.visual;
|
||||
return (v.kind === "godot2d" || v.kind === "godot3d") && !!v.scene && !!v.file && !!shot.audio && !shot.audioStale &&
|
||||
v.sceneKey === sceneKey(v.scene, shotDuration(montage, shot)) && fs.existsSync(path.join(REPO_ROOT, v.file));
|
||||
}
|
||||
|
||||
/** Renderiza no Godot a cena 2D de UM trecho (precisa do áudio: a cena dura o tempo da fala). */
|
||||
async function renderShotSceneInternal(ep: EpisodeView, montage: Montage, shot: MontageShot, hook?: JobHook): Promise<void> {
|
||||
if (!shot.audio || shot.audioStale) throw new UserError(`Gere o áudio do trecho ${shot.index + 1} antes: a cena dura o tempo da fala.`);
|
||||
const scene = shot.visual.scene ?? { kind: "doc2d" as const, ...planScene(shot) };
|
||||
const duration = shotDuration(montage, shot);
|
||||
const n = String(shot.index + 1).padStart(2, "0");
|
||||
const mp4 = await renderGodotScene({
|
||||
repoRoot: REPO_ROOT, id: `${ep.story_id}-${ep.file_key}-t${n}`.slice(0, 60),
|
||||
configFile: path.join(storyDir(ep.story_id), "godot", `${ep.file_key}-t${n}.json`), scene, durationSeconds: duration, hook,
|
||||
});
|
||||
const saved = readSaved(ep);
|
||||
const own = (saved.shots[String(shot.index)] ??= {});
|
||||
own.visual = { ...EMPTY_VISUAL, ...own.visual, kind: scene.kind === "doc3d" ? "godot3d" : "godot2d", scene, file: mp4, sceneKey: sceneKey(scene, duration) };
|
||||
writeSaved(ep, saved);
|
||||
}
|
||||
|
||||
export async function renderShotScene(episodeId: number, index: number): Promise<Montage> {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const montage = loadMontage(episodeId);
|
||||
const shot = montage.shots.find((s) => s.index === index);
|
||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||
if (shot.visual.kind !== "godot2d" && shot.visual.kind !== "godot3d") throw new UserError("Este trecho não usa cena do Godot.");
|
||||
await renderShotSceneInternal(ep, montage, shot);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
|
||||
/** Gera (ou refaz) o áudio de UM trecho. Um parágrafo por vez: a voz fica natural. */
|
||||
export async function generateShotAudio(episodeId: number, index: number): Promise<Montage> {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const montage = loadMontage(episodeId);
|
||||
const shot = montage.shots.find((s) => s.index === index);
|
||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||
if (!montage.voiceId) throw new UserError("Escolha a voz da narração.");
|
||||
if (!shot.spoken.trim()) throw new UserError(`O trecho ${index + 1} não tem texto falado.`);
|
||||
const response = await synthesize({ voiceId: montage.voiceId, text: shot.spoken, speed: montage.speed });
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
if (bytes.length < 100) throw new UserError("O serviço de voz devolveu um áudio vazio.");
|
||||
fs.mkdirSync(audioDir(ep), { recursive: true });
|
||||
const file = path.join(audioDir(ep), `${ep.file_key}-${String(index + 1).padStart(2, "0")}.ogg`);
|
||||
fs.writeFileSync(file, bytes);
|
||||
const durationMs = Number(response.headers.get("X-Audio-Duration-Ms")) || (await probeDuration(file)) * 1000;
|
||||
const saved = readSaved(ep);
|
||||
(saved.shots[String(index)] ??= {}).audio = { file: rel(file), durationMs: Math.round(durationMs), key: audioKey(montage.voiceId, montage.speed, shot.spoken) };
|
||||
writeSaved(ep, saved);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
|
||||
/** Envia uma imagem ou clipe para um trecho: vira asset da história e é ligado ao trecho. */
|
||||
export async function uploadShotVisual(episodeId: number, index: number, input: {
|
||||
file: File; credit: string; license: string; sourceUrl: string;
|
||||
}): Promise<Montage> {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const ext = path.extname(input.file.name).toLowerCase();
|
||||
const kind: AssetKind = [".mp4", ".mov", ".webm", ".mkv"].includes(ext) ? "video" : "image";
|
||||
const asset = await createAsset({
|
||||
file: input.file, kind, scope: "story", storyId: ep.story_id,
|
||||
name: `${ep.file_key} trecho ${index + 1}`.slice(0, 80),
|
||||
// Licença é opcional (decisão do dono); o registro de asset pede um texto, então vai o padrão.
|
||||
license: input.license.trim() || "não informada", source: input.sourceUrl || input.credit, notes: input.credit,
|
||||
});
|
||||
return updateMontage(episodeId, { shot: { index, visual: {
|
||||
kind: kind === "video" ? "video" : "image", file: asset.file_path, credit: input.credit, license: input.license, sourceUrl: input.sourceUrl,
|
||||
} } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Imagem da internet para um trecho: busca (da mais específica para a mais geral), pega o
|
||||
* resultado `startPick` em diante sem repetir imagens já usadas em outros trechos, baixa e liga.
|
||||
*/
|
||||
async function applyInternetImage(ep: EpisodeView, shot: MontageShot, queries: string[], startPick: number, used: Set<string>, target: "main" | "inset" = "main"): Promise<boolean> {
|
||||
const found = await searchFirst(queries, 16);
|
||||
if (!found) return false;
|
||||
const n = found.images.length;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const pick = (startPick + k) % n;
|
||||
const img = found.images[pick];
|
||||
if (used.has(img.pageUrl)) continue;
|
||||
const { bytes, ext } = await downloadImage(img.url);
|
||||
const asset = await createAsset({
|
||||
file: new File([new Uint8Array(bytes)], `foto${ext}`), kind: "image", scope: "story", storyId: ep.story_id,
|
||||
name: `${ep.file_key} trecho ${shot.index + 1} ${img.title}`.slice(0, 80),
|
||||
license: img.license || "ver fonte", source: img.pageUrl, notes: img.author,
|
||||
});
|
||||
const saved = readSaved(ep);
|
||||
const own = (saved.shots[String(shot.index)] ??= {});
|
||||
const search = { queries: [found.query, ...queries.filter((q) => q !== found.query)], pick };
|
||||
if (target === "inset") {
|
||||
// Cartão por cima da cena: o visual (a cena 3D) continua o mesmo.
|
||||
own.visual = { ...EMPTY_VISUAL, ...own.visual, inset: { file: asset.file_path, credit: img.author, license: img.license, sourceUrl: img.pageUrl, search } };
|
||||
} else {
|
||||
own.visual = { ...EMPTY_VISUAL, kind: "image", file: asset.file_path, credit: img.author, license: img.license, sourceUrl: img.pageUrl, search, auto: true };
|
||||
}
|
||||
writeSaved(ep, saved);
|
||||
used.add(img.pageUrl);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Imagens da internet já usadas nos outros trechos (para não repetir). */
|
||||
function usedImages(montage: Montage, except: number): Set<string> {
|
||||
const urls = montage.shots.filter((s) => s.index !== except).flatMap((s) => [
|
||||
s.visual.kind === "image" ? s.visual.sourceUrl : "", s.visual.inset?.sourceUrl ?? "",
|
||||
]);
|
||||
return new Set(urls.filter(Boolean));
|
||||
}
|
||||
|
||||
function scriptContext(ep: EpisodeView) {
|
||||
return { ...scriptEntities(readTextIfExists(path.join(REPO_ROOT, ep.scriptPath)) ?? ""), library: listLibrary() };
|
||||
}
|
||||
|
||||
/**
|
||||
* "Gerar de novo" de um trecho: cena do Godot (2D ou 3D) ganha outra variação de layout/câmera
|
||||
* e é renderizada já; imagem da internet troca pela próxima da busca (sem repetir as dos outros
|
||||
* trechos); imagem enviada vira busca na internet.
|
||||
*/
|
||||
export async function regenerateShot(episodeId: number, index: number, target: "visual" | "inset" | "remove-inset" = "visual"): Promise<Montage> {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const montage = loadMontage(episodeId);
|
||||
const shot = montage.shots.find((s) => s.index === index);
|
||||
if (!shot) throw new UserError("Trecho não encontrado.");
|
||||
const v = shot.visual;
|
||||
if (target === "remove-inset") {
|
||||
const saved = readSaved(ep);
|
||||
const own = (saved.shots[String(index)] ??= {});
|
||||
if (own.visual) own.visual.inset = null;
|
||||
writeSaved(ep, saved);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
if (target === "inset") {
|
||||
// Outra foto no cartão (ou a primeira): a busca do cartão, a do plano 3D ou o nome científico.
|
||||
const ctx = scriptContext(ep);
|
||||
const queries = v.inset?.search?.queries ?? planShot3d(shot, ctx, index)?.insetQueries ?? [];
|
||||
const all = queries.length ? queries : [...ctx.species, ...ctx.places.filter((p) => p.startsWith("Ilha"))];
|
||||
if (!all.length) throw new UserError("Não sei o que buscar: escreve \"[foto: termos]\" na coluna Imagem do roteiro.");
|
||||
const ok = await applyInternetImage(ep, shot, all, (v.inset?.search?.pick ?? -1) + 1, usedImages(montage, index), "inset");
|
||||
if (!ok) throw new UserError("Não achei outra foto diferente das que já estão no vídeo.");
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
if ((v.kind === "godot2d" || v.kind === "godot3d") && v.scene) {
|
||||
const variant = Number(v.scene.params.variant ?? 0) + 1;
|
||||
const saved = readSaved(ep);
|
||||
const own = (saved.shots[String(index)] ??= {});
|
||||
own.visual = { ...EMPTY_VISUAL, ...own.visual, scene: { ...v.scene, params: { ...v.scene.params, variant } } };
|
||||
writeSaved(ep, saved);
|
||||
const fresh = loadMontage(episodeId);
|
||||
const freshShot = fresh.shots.find((s) => s.index === index)!;
|
||||
if (freshShot.audio && !freshShot.audioStale) await renderShotSceneInternal(ep, fresh, freshShot);
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
if (v.kind === "image") {
|
||||
const plan = planShot(shot, scriptContext(ep));
|
||||
const queries = v.search?.queries ?? (plan.kind === "image" ? plan.queries : [...scriptContext(ep).species, ...scriptContext(ep).places.slice(0, 1)]);
|
||||
if (!queries.length) throw new UserError("Não sei o que buscar para este trecho: escreva o que a imagem deve mostrar na coluna Imagem do roteiro.");
|
||||
const ok = await applyInternetImage(ep, shot, queries, (v.search?.pick ?? -1) + 1, usedImages(montage, index));
|
||||
if (!ok) throw new UserError("Não achei outra imagem diferente das que já estão no vídeo.");
|
||||
return loadMontage(episodeId);
|
||||
}
|
||||
throw new UserError("Cartela e clipe não têm variação automática: troque o estilo ou edite o texto.");
|
||||
}
|
||||
|
||||
/** Opções prontas para escolher num trecho: assets de imagem/vídeo e vídeos renderizados pelo Godot. */
|
||||
export function visualOptions(episodeId: number): { images: { file: string; name: string }[]; videos: { file: string; name: string }[]; renders: { file: string; name: string }[] } {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const assets = all<{ kind: string; name: string; file_path: string }>(
|
||||
"SELECT kind, name, file_path FROM assets WHERE (scope = 'library' OR story_id = ?) AND kind IN ('image', 'background', 'texture', 'video') ORDER BY name", ep.story_id);
|
||||
const renders = all<{ mp4: string; story_id: string; number: number; finished_at: string }>(
|
||||
`SELECT r.mp4, e.story_id, e.number, r.finished_at FROM renders r JOIN episodes e ON e.id = r.episode_id
|
||||
WHERE r.status = 'success' AND r.mp4 IS NOT NULL AND r.profile != 'documentary' ORDER BY r.id DESC LIMIT 30`);
|
||||
return {
|
||||
images: assets.filter((a) => a.kind !== "video").map((a) => ({ file: a.file_path, name: a.name })),
|
||||
videos: [
|
||||
...assets.filter((a) => a.kind === "video").map((a) => ({ file: a.file_path, name: a.name })),
|
||||
...renders.filter((r) => fs.existsSync(path.join(REPO_ROOT, r.mp4))).map((r) => ({ file: r.mp4, name: `Render Godot: ${r.story_id} ep${String(r.number).padStart(2, "0")}` })),
|
||||
],
|
||||
renders: renders.filter((r) => fs.existsSync(path.join(REPO_ROOT, r.mp4)))
|
||||
.map((r) => ({ file: r.mp4, name: `${r.story_id} · ep${String(r.number).padStart(2, "0")} · ${r.finished_at.slice(0, 16).replace("T", " ")}` })),
|
||||
};
|
||||
}
|
||||
|
||||
type MontageJob = { episodeId: number; child: ChildProcess | null; cancelled: boolean; progress: string };
|
||||
const g = globalThis as unknown as { __cenaforgeMontage?: Map<number, MontageJob> };
|
||||
const jobs = (g.__cenaforgeMontage ??= new Map());
|
||||
|
||||
export function listMontageRenders(episodeId: number): RenderJob[] {
|
||||
return all<RenderJob>("SELECT * FROM renders WHERE episode_id = ? AND profile = 'documentary' ORDER BY id DESC", episodeId);
|
||||
}
|
||||
|
||||
/** Montagem em andamento deste vídeo e a etapa em que está ("Narração 3 de 9", "Cena 2D 5 de 9"…). */
|
||||
export function montageJob(episodeId: number): { renderId: number; progress: string } | null {
|
||||
for (const [renderId, job] of jobs) if (job.episodeId === episodeId) return { renderId, progress: job.progress };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Trecho sem visual escolhido pelo admin (imagem/clipe vazio): o modo automático usa cena 2D. */
|
||||
const needsVisual = (s: MontageShot) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && s.visual.kind !== "godot3d" && !s.visual.file;
|
||||
/** No "Refazer tudo do zero": o que o automático escolheu (ou cena do Godot sem marca, de versões antigas) é replanejado. */
|
||||
const replannable = (s: MontageShot) => needsVisual(s) || s.visual.auto === true || (s.visual.auto === undefined && (s.visual.kind === "godot2d" || s.visual.kind === "godot3d"));
|
||||
const isGodot = (s: MontageShot) => s.visual.kind === "godot2d" || s.visual.kind === "godot3d";
|
||||
|
||||
/** Voz pt-BR padrão do serviço (para o modo automático, quando nenhuma foi escolhida). */
|
||||
async function defaultVoice(): Promise<string> {
|
||||
const status = (await getStatus()) as { online?: boolean; voices?: { id: string; languages?: string[]; default?: boolean }[] };
|
||||
if (!status.online) throw new UserError("O serviço de voz está fora do ar: sem ele não dá para gerar a narração.");
|
||||
const pt = (status.voices ?? []).filter((v) => v.languages?.includes("pt-BR"));
|
||||
const voice = pt.find((v) => v.default) ?? pt[0];
|
||||
if (!voice) throw new UserError("Nenhuma voz pt-BR disponível no serviço de voz.");
|
||||
return voice.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Começa a montagem em segundo plano.
|
||||
* auto = false: exige áudio atualizado e visual em todos os trechos (botão "Montar vídeo").
|
||||
* auto = true ("Gerar vídeo automático", um clique): trecho sem visual vira cena 2D do Godot
|
||||
* (mapa/contador/título pelo texto), escolhe a voz pt-BR padrão se faltar, gera os áudios
|
||||
* que faltam, renderiza no Godot as cenas 2D desatualizadas e monta o MP4.
|
||||
*/
|
||||
export function startMontageRender(episodeId: number, options: { auto?: boolean; replan?: boolean } = {}): RenderJob {
|
||||
const ep = episodeOrThrow(episodeId);
|
||||
const story = getStory(ep.story_id)!;
|
||||
const initial = loadMontage(episodeId);
|
||||
if (jobs.size > 0) throw new UserError("Já existe uma montagem em andamento. Aguarde terminar.");
|
||||
if (!options.auto) {
|
||||
const missingAudio = initial.shots.filter((s) => !s.audio || s.audioStale).map((s) => s.index + 1);
|
||||
if (missingAudio.length) throw new UserError(`Gere o áudio dos trechos ${missingAudio.join(", ")} antes de montar.`);
|
||||
const missingVisual = initial.shots.filter(needsVisual).map((s) => s.index + 1);
|
||||
if (missingVisual.length) throw new UserError(`Escolha o visual dos trechos ${missingVisual.join(", ")} (ou use "Gerar vídeo automático").`);
|
||||
}
|
||||
const font = fontFile();
|
||||
ffmpegBin("ffmpeg");
|
||||
|
||||
const stamp = now().replace(/[:.]/g, "-");
|
||||
const dir = path.join(OUTPUT_DIR, "documentary", `${story.id}-${ep.file_key}-${stamp}`);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const logDir = path.join(DATA_DIR, "logs", "renders");
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
const info = run(`INSERT INTO renders (episode_id, config_path, profile, status, run_dir, started_at) VALUES (?, ?, 'documentary', 'running', ?, ?)`,
|
||||
episodeId, rel(montagePath(ep)), rel(dir), now());
|
||||
const id = Number(info.lastInsertRowid);
|
||||
const logPath = path.join(logDir, `${id}.log`);
|
||||
run("UPDATE renders SET log_path = ? WHERE id = ?", rel(logPath), id);
|
||||
const job: MontageJob = { episodeId, child: null, cancelled: false, progress: "Preparando…" };
|
||||
jobs.set(id, job);
|
||||
|
||||
const log = (line: string) => fs.appendFileSync(logPath, `[${new Date().toISOString()}] ${line}\n`, "utf8");
|
||||
const step = (text: string) => { job.progress = text; log(text); };
|
||||
const hook: JobHook = { onChild: (child) => { job.child = child; }, cancelled: () => job.cancelled };
|
||||
const checkCancel = () => { if (job.cancelled) throw new UserError("cancelado pelo painel"); };
|
||||
void (async () => {
|
||||
try {
|
||||
if (options.auto) {
|
||||
// 1) Plano de cada trecho sem visual: foto da internet, mapa/contador 2D, ilha 3D ou título.
|
||||
step("Planejando as cenas");
|
||||
const ctx = scriptContext(ep);
|
||||
const toPlan = initial.shots.filter(options.replan ? replannable : needsVisual);
|
||||
const used = new Set(initial.shots.filter((s) => !toPlan.includes(s) && s.visual.kind === "image" && s.visual.sourceUrl).map((s) => s.visual.sourceUrl));
|
||||
const style = readSaved(ep).style ?? "mixed";
|
||||
for (const shot of toPlan) {
|
||||
checkCancel();
|
||||
if (style === "3d") {
|
||||
// Tudo em 3D: cena 3D da biblioteca + cartão de foto real quando o trecho pede.
|
||||
const plan3d = planShot3d(shot, ctx, shot.index);
|
||||
if (!plan3d) throw new UserError("A biblioteca de cenas 3D está vazia: peça uma cena ao agente (tarefa \"Cena no Godot\").");
|
||||
const saved3d = readSaved(ep);
|
||||
(saved3d.shots[String(shot.index)] ??= {}).visual = { ...EMPTY_VISUAL, kind: "godot3d", scene: plan3d.scene, auto: true, inset: null };
|
||||
writeSaved(ep, saved3d);
|
||||
if (plan3d.insetQueries.length) {
|
||||
step(`Buscando foto para o cartão (trecho ${shot.index + 1})`);
|
||||
await applyInternetImage(ep, shot, plan3d.insetQueries, 0, used, "inset").catch((e) => { log(`cartão do trecho ${shot.index + 1}: ${(e as Error).message}`); return false; });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const plan = planShot(shot, ctx);
|
||||
if (plan.kind === "image") {
|
||||
step(`Buscando imagem na internet (trecho ${shot.index + 1})`);
|
||||
const ok = await applyInternetImage(ep, shot, plan.queries, 0, used).catch((e) => { log(`imagem do trecho ${shot.index + 1}: ${(e as Error).message}`); return false; });
|
||||
if (ok) continue;
|
||||
}
|
||||
const saved = readSaved(ep);
|
||||
(saved.shots[String(shot.index)] ??= {}).visual = plan.kind === "image"
|
||||
? { ...EMPTY_VISUAL, kind: "godot2d", scene: plan.fallback, auto: true }
|
||||
: { ...EMPTY_VISUAL, kind: plan.kind, scene: plan.scene, auto: true };
|
||||
writeSaved(ep, saved);
|
||||
}
|
||||
const saved = readSaved(ep);
|
||||
if (!saved.voiceId) { saved.voiceId = await defaultVoice(); writeSaved(ep, saved); }
|
||||
// 2) Áudios que faltam (um por trecho).
|
||||
const needAudio = loadMontage(episodeId).shots.filter((s) => !s.audio || s.audioStale);
|
||||
for (const [i, shot] of needAudio.entries()) {
|
||||
checkCancel();
|
||||
step(`Narração ${i + 1} de ${needAudio.length} (trecho ${shot.index + 1})`);
|
||||
await generateShotAudio(episodeId, shot.index);
|
||||
}
|
||||
}
|
||||
// 3) Cenas do Godot (2D e 3D) desatualizadas, com a duração exata de cada fala.
|
||||
const current = loadMontage(episodeId);
|
||||
const needScene = current.shots.filter((s) => isGodot(s) && s.audio && !s.audioStale && !sceneIsCurrent(current, s));
|
||||
for (const [i, shot] of needScene.entries()) {
|
||||
checkCancel();
|
||||
step(`Cena ${shot.visual.kind === "godot3d" ? "3D" : "2D"} no Godot ${i + 1} de ${needScene.length} (trecho ${shot.index + 1})`);
|
||||
await renderShotSceneInternal(ep, current, shot, hook);
|
||||
}
|
||||
const montage = loadMontage(episodeId);
|
||||
const pending = montage.shots.filter((s) => !s.audio || s.audioStale || (s.visual.kind !== "card" && !s.visual.file) ||
|
||||
(isGodot(s) && !sceneIsCurrent(montage, s)));
|
||||
if (pending.length) throw new UserError(`Trechos ainda sem áudio ou visual atualizado: ${pending.map((s) => s.index + 1).join(", ")}.`);
|
||||
// 4) Um segmento por trecho + créditos, depois junta tudo.
|
||||
const segments: string[] = [];
|
||||
for (const shot of montage.shots) {
|
||||
checkCancel();
|
||||
step(`Montando trecho ${shot.index + 1} de ${montage.shots.length}`);
|
||||
segments.push(await buildSegment({
|
||||
visual: shot.visual,
|
||||
inset: shot.visual.inset ? { file: shot.visual.inset.file, credit: shot.visual.inset.credit } : null,
|
||||
// A cena 2D já mostra o texto dela; não sobrepõe de novo.
|
||||
onScreen: shot.visual.kind === "godot2d" ? "" : shot.onScreen,
|
||||
narration: shot.narration, audio: shot.audio!.file, duration: shotDuration(montage, shot), index: shot.index, captions: montage.captions,
|
||||
}, dir, font, REPO_ROOT, hook));
|
||||
}
|
||||
const credits = [...new Set(montage.shots.map((s) => s.visual.credit && `${s.visual.credit}${s.visual.license ? ` (${s.visual.license})` : ""}`).filter(Boolean))];
|
||||
if (credits.length || montage.sourceHosts.length) {
|
||||
segments.push(await buildCredits([
|
||||
...(credits.length ? ["Imagens:", ...credits.slice(0, 8)] : []),
|
||||
...(montage.sourceHosts.length ? ["", "Fontes:", ...montage.sourceHosts.slice(0, 6)] : []),
|
||||
], dir, font, hook));
|
||||
}
|
||||
step("Juntando os trechos");
|
||||
const finalName = `${story.id}-${ep.file_key}.mp4`;
|
||||
const seconds = await concatSegments(segments, dir, finalName, hook);
|
||||
log(`pronto: ${finalName} (${seconds.toFixed(1)} s)`);
|
||||
run("UPDATE renders SET status = 'success', mp4 = ?, finished_at = ? WHERE id = ? AND status = 'running'", rel(path.join(dir, finalName)), now(), id);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
log(`erro: ${message}`);
|
||||
run("UPDATE renders SET status = ?, error = ?, finished_at = ? WHERE id = ? AND status = 'running'",
|
||||
job.cancelled ? "cancelled" : "failed", message.slice(0, 2000), now(), id);
|
||||
} finally {
|
||||
jobs.delete(id);
|
||||
touchStory(ep.story_id);
|
||||
}
|
||||
})();
|
||||
return get<RenderJob>("SELECT * FROM renders WHERE id = ?", id)!;
|
||||
}
|
||||
|
||||
export function cancelMontageRender(id: number): void {
|
||||
const job = jobs.get(id);
|
||||
if (!job) throw new UserError("Esta montagem não está em andamento.");
|
||||
job.cancelled = true;
|
||||
if (job.child) killTree(job.child);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Caminhos do repositório CenaForge vistos pelo painel. O painel roda em panel/, mas
|
||||
// histórias, cenas, assets e renders vivem na raiz do repositório.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
function findRepoRoot(): string {
|
||||
if (process.env.CENAFORGE_ROOT) return path.resolve(process.env.CENAFORGE_ROOT);
|
||||
let dir = process.cwd();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
if (fs.existsSync(path.join(dir, "godot", "project.godot"))) return dir;
|
||||
const up = path.dirname(dir);
|
||||
if (up === dir) break;
|
||||
dir = up;
|
||||
}
|
||||
throw new Error("Raiz do CenaForge não encontrada (pasta com godot/project.godot). Defina CENAFORGE_ROOT.");
|
||||
}
|
||||
|
||||
export const REPO_ROOT = findRepoRoot();
|
||||
export const DATA_DIR = path.join(REPO_ROOT, "data");
|
||||
export const STORIES_DIR = path.join(REPO_ROOT, "stories");
|
||||
export const CONFIG_DIR = path.join(REPO_ROOT, "config");
|
||||
export const OUTPUT_DIR = path.join(REPO_ROOT, "output");
|
||||
export const LIBRARY_DIR = path.join(REPO_ROOT, "assets", "library");
|
||||
export const BASE_SCENE = "config/demo-street.json";
|
||||
|
||||
/** Pastas que o painel pode servir ao navegador (vídeos, imagens, roteiros, assets). */
|
||||
export const SERVABLE_ROOTS = [OUTPUT_DIR, STORIES_DIR, path.join(REPO_ROOT, "assets")];
|
||||
|
||||
export const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
|
||||
|
||||
export function slugify(text: string): string {
|
||||
return text
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 48)
|
||||
.replace(/-+$/, "");
|
||||
}
|
||||
|
||||
export const pad2 = (n: number) => String(n).padStart(2, "0");
|
||||
export const storyDir = (storyId: string) => path.join(STORIES_DIR, storyId);
|
||||
export const storyAssetsDir = (storyId: string) => path.join(storyDir(storyId), "assets");
|
||||
/** Nome dos arquivos de um episódio: `ep01` no caminho principal antigo; `ep02-b` para a vertente B do nível 2. */
|
||||
export const episodeFileKey = (n: number, choice?: string | null) => `ep${pad2(n)}${choice ? `-${choice.toLowerCase()}` : ""}`;
|
||||
export const episodeScriptPath = (storyId: string, fileKey: string) => path.join(storyDir(storyId), `${fileKey}.md`);
|
||||
export const episodeConfigPath = (storyId: string, fileKey: string) => path.join(CONFIG_DIR, `${storyId}-${fileKey}.json`);
|
||||
/** Opções da decisão de um episódio, gravadas pela IA ao preparar as vertentes: {"A": "texto", ...}. */
|
||||
export const episodeChoicesPath = (storyId: string, fileKey: string) => path.join(storyDir(storyId), `${fileKey}.choices.json`);
|
||||
|
||||
/** Caminho relativo à raiz, com "/" (o que vai para o banco, prompts e URLs). */
|
||||
export function rel(p: string): string {
|
||||
return path.relative(REPO_ROOT, p).split(path.sep).join("/");
|
||||
}
|
||||
|
||||
/** Resolve um caminho relativo garantindo que ele fique dentro de uma das raízes permitidas. */
|
||||
export function resolveInside(relPath: string, roots: string[]): string | null {
|
||||
const full = path.resolve(REPO_ROOT, relPath);
|
||||
return roots.some((root) => full === root || full.startsWith(root + path.sep)) ? full : null;
|
||||
}
|
||||
|
||||
export function readTextIfExists(p: string): string | null {
|
||||
try {
|
||||
return fs.readFileSync(p, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Processos filhos do painel: sem shell, argumentos em lista, encerramento da árvore inteira.
|
||||
import { spawnSync, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export function killTree(child: ChildProcess): void {
|
||||
if (child.pid === undefined || child.exitCode !== null) return;
|
||||
if (process.platform === "win32") {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
|
||||
} else {
|
||||
child.kill("SIGTERM");
|
||||
}
|
||||
}
|
||||
|
||||
/** Procura um executável no PATH (com PATHEXT no Windows). */
|
||||
export function findOnPath(name: string): string | null {
|
||||
// No Windows, "claude.exe" vem antes de "claude" (que pode ser um script de shell).
|
||||
// .cmd/.bat ficam de fora: o Node não os executa sem shell.
|
||||
const exts = [".exe", ".com"];
|
||||
for (const dir of (process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
||||
// Sem extensão no Windows costuma ser script de shell (ex.: shim do npm): não executável.
|
||||
for (const ext of process.platform === "win32" ? exts : [""]) {
|
||||
const candidate = path.join(dir, name + ext.toLowerCase());
|
||||
try {
|
||||
if (fs.statSync(candidate).isFile()) return candidate;
|
||||
} catch {
|
||||
// continua
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Divide um fluxo em linhas completas. */
|
||||
export function lineSplitter(onLine: (line: string) => void): (chunk: string) => void {
|
||||
let buffer = "";
|
||||
return (chunk: string) => {
|
||||
buffer += chunk;
|
||||
let i: number;
|
||||
while ((i = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, i).replace(/\r$/, "");
|
||||
buffer = buffer.slice(i + 1);
|
||||
if (line.trim()) onLine(line);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// Montagem do prompt enviado ao agente. O contexto (história, episódio, caminhos, escolha
|
||||
// anterior) vem do banco; o texto do usuário entra como "Pedido". Comentários do público
|
||||
// não entram.
|
||||
import { childEpisodes, getEpisodeById } from "./stories";
|
||||
import { BASE_SCENE, episodeChoicesPath, episodeConfigPath, episodeScriptPath, rel } from "./paths";
|
||||
import type { AgentKind, EpisodeView, Provider, Story, StoryKind } from "./types";
|
||||
|
||||
/**
|
||||
* Regras de roteiro: ficam em doc/roteiro/ (fonte única). O Codex lê os guias direto; o Claude
|
||||
* delega ao subagente `cenaforge-story-writer`, que lê os mesmos guias. Assim os dois têm o
|
||||
* mesmo contexto, e mudar uma regra é editar um .md, não este arquivo.
|
||||
*/
|
||||
const GUIDE_COMMON = "doc/roteiro/comum.md";
|
||||
const GUIDE_BY_KIND: Record<StoryKind, string> = {
|
||||
interactive: "doc/roteiro/ficcao.md",
|
||||
linear: "doc/roteiro/ficcao.md",
|
||||
documentary: "doc/roteiro/documental.md",
|
||||
};
|
||||
const FORMAT_LABEL: Record<StoryKind, string> = { interactive: "interativa", linear: "linear", documentary: "documental" };
|
||||
|
||||
/** Scripts sem LLM que substituem trabalho que o agente fazia lendo arquivos e imagens. */
|
||||
const CHECK_FRAMES = "python .claude/skills/cenaforge/scripts/frame_check.py";
|
||||
const CHECK_SCRIPT = "python .claude/skills/cenaforge/scripts/check_script.py";
|
||||
|
||||
/** Fecho das tarefas de texto: o script confere duração, narração por trecho e os JSON. */
|
||||
function scriptCheck(storyId: string): string {
|
||||
return `Antes de terminar, rode \`${CHECK_SCRIPT} stories/${storyId}\` e corrija os avisos (duração alvo, narração por trecho, meta.json, choices.json). Não reconte palavras à mão.`;
|
||||
}
|
||||
|
||||
/** Pesquisa web do documental: as páginas abertas inteiras eram o que mais pesava no roteiro. */
|
||||
const RESEARCH_ECONOMY = "Na pesquisa, busque o termo dentro da página em vez de abri-la inteira e pare em 3–5 fontes confiáveis que cubram os fatos do roteiro.";
|
||||
|
||||
function writingRules(provider: Provider, kind: StoryKind): string {
|
||||
const guides = `\`${GUIDE_COMMON}\` e \`${GUIDE_BY_KIND[kind]}\``;
|
||||
const core = kind === "documentary"
|
||||
? "Formato DOCUMENTAL: vídeo único sobre fatos reais. Cidades, lugares e instituições reais pelo nome, cada fato com fonte; sem votação. As restrições de ficção não valem."
|
||||
: `Formato ${FORMAT_LABEL[kind].toUpperCase()} (ficção): sem cidades, marcas nem pessoas reais.`;
|
||||
return provider === "claude"
|
||||
? `${core}\nPara o texto, use o subagente \`cenaforge-story-writer\` e diga a ele o formato (${FORMAT_LABEL[kind]}). Ele segue ${guides}.`
|
||||
: `${core}\nLeia ${guides} e siga-os: são as regras e os formatos de arquivo. Escreva você mesmo; ` +
|
||||
"não use `.claude/agents/` (subagentes do Claude, que leem esses mesmos guias).";
|
||||
}
|
||||
|
||||
export function buildPrompt(input: { kind: AgentKind; provider: Provider; request: string; story?: Story; episode?: EpisodeView }): string {
|
||||
const { kind, provider, request, story, episode } = input;
|
||||
const documentary = story?.kind === "documentary";
|
||||
// Economia de tokens: cada tarefa recebe só a lista curta do que ler. A skill inteira (SKILL.md +
|
||||
// references, ~1.500 linhas) só entra nas tarefas que mexem no pipeline de render (cena, livre).
|
||||
const reading: Record<AgentKind, string> = {
|
||||
story: "Leia SÓ: `doc/roteiro/comum.md` e o guia do formato (`doc/roteiro/ficcao.md` ou `doc/roteiro/documental.md`). Não carregue a skill `cenaforge` nem `.claude/skills/`.",
|
||||
script: "Leia SÓ: `doc/roteiro/comum.md`, o guia do formato e a pasta da história. Não carregue a skill `cenaforge` nem `.claude/skills/`.",
|
||||
branches: "Leia SÓ: `doc/roteiro/comum.md`, `doc/roteiro/ficcao.md` e a pasta da história; para a cena, use o script `new_scene.py` indicado abaixo. Não carregue a skill inteira.",
|
||||
godot: "Leia SÓ: `doc/godot/cenas.md` e `doc/godot/api.md` (assinaturas das peças e cenas; NÃO leia os .gd inteiros de outras cenas). Não carregue a skill `cenaforge`.",
|
||||
scene: "Siga a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md): leia só as seções que a tarefa pedir.",
|
||||
free: "Siga o CLAUDE.md; consulte a skill `cenaforge` (.claude/skills/cenaforge/SKILL.md) só no que a tarefa pedir.",
|
||||
};
|
||||
const lines: (string | null)[] = [
|
||||
"Você está trabalhando no repositório CenaForge (vídeos narrativos: cena descrita por JSON → Godot → MP4).",
|
||||
"Responda em português do Brasil.",
|
||||
reading[kind],
|
||||
"Trabalhe só dentro do repositório. Seja econômico: Grep antes de ler, leia por intervalo de linhas, filtre saídas longas (`| Select-Object -Last 20` / `| tail -n 20`). " +
|
||||
"Não acione os subagentes `cenaforge-skill-updater` nem `cenaforge-token-auditor` (100–150 mil tokens cada): isso é feito fora do painel. " +
|
||||
"Ao terminar, liste os arquivos criados ou alterados e o que ficou pendente.",
|
||||
provider === "codex"
|
||||
? "Você é o Codex. Arquivos em `.claude/agents/` são subagentes do Claude: você não os aciona; quando o CLAUDE.md mandar delegar a um deles, faça o trabalho você mesmo. " +
|
||||
"No PowerShell, leia texto com `Get-Content -Raw -Encoding UTF8` (sem isso os acentos saem quebrados) e rode o pnpm como `pnpm.cmd` " +
|
||||
"(o `pnpm.ps1` é bloqueado pela política de execução): `pnpm.cmd render -- --config <json> --profile preview`."
|
||||
: null,
|
||||
];
|
||||
if (story) {
|
||||
const format = story.kind === "interactive"
|
||||
? `interativa: cada episódio termina numa escolha do público entre ${story.branch_count} vertentes`
|
||||
: documentary ? "documental: vídeo único sobre fatos reais, sem votação" : "linear";
|
||||
lines.push("", "## Contexto",
|
||||
`História: ${story.title} (id \`${story.id}\`, ${format}).`,
|
||||
story.logline ? `Premissa: ${story.logline}` : "Premissa: ainda não definida.",
|
||||
`Pasta da história: \`stories/${story.id}/\` (bíblia, episódios e assets exclusivos em \`stories/${story.id}/assets/\`). Biblioteca compartilhada: \`assets/library/\`.`);
|
||||
}
|
||||
if (story && episode) {
|
||||
lines.push(`Episódio ${episode.number} (\`${episode.file_key}\`)${episode.title ? ` — ${episode.title}` : ""}.`,
|
||||
`Roteiro: \`${episode.scriptPath}\` (${episode.hasScript ? "existe" : "ainda não existe"}).`,
|
||||
`Cena: \`${episode.configPath}\` (${episode.hasConfig ? "existe" : "ainda não existe"}).`);
|
||||
if (episode.parent_episode_id && episode.parent_choice) {
|
||||
const parent = getEpisodeById(episode.parent_episode_id);
|
||||
const label = episode.branch_label || parent?.choices.find((c) => c.letter === episode.parent_choice)?.label || null;
|
||||
lines.push(`Escolha do público no episódio anterior: ${episode.parent_choice}${label ? ` ("${label}")` : ""}. O episódio precisa seguir essa consequência.`);
|
||||
}
|
||||
}
|
||||
if (kind === "story" && story && documentary) {
|
||||
const ep = episode ? episode.scriptPath : `stories/${story.id}/ep01.md`;
|
||||
lines.push("", "## Tarefa: montar o vídeo documental a partir do texto do usuário",
|
||||
"O texto em \"Pedido\" é o tema escolhido pelo criador. Pesquise na web, confira os fatos e escreva o vídeo.",
|
||||
RESEARCH_ECONOMY,
|
||||
writingRules(provider, story.kind),
|
||||
`1. Escreva a ficha de pauta em \`stories/${story.id}/biblia.md\`.`,
|
||||
`2. Escreva o roteiro do vídeo em \`${ep}\`.`,
|
||||
`3. Grave \`stories/${story.id}/meta.json\` exatamente assim: {"title": "<título final, até 60 caracteres>", "logline": "<o vídeo em 1–2 frases>"}.`,
|
||||
scriptCheck(story.id),
|
||||
"Não crie cena JSON, não renderize e não altere código. Ao terminar, resuma o vídeo, liste as fontes usadas e as necessidades de produção.");
|
||||
} else if (kind === "story" && story) {
|
||||
const ep = episode ? episode.scriptPath : `stories/${story.id}/ep01.md`;
|
||||
lines.push("", "## Tarefa: montar a história a partir do texto do usuário",
|
||||
"O texto em \"Pedido\" é o material de partida do criador (ideia, sinopse ou rascunho). Transforme-o numa história do formato CenaForge:",
|
||||
"episódios verticais curtos (~12 s), um de cada vez, " + (story.kind === "interactive" ? "cada um terminando numa escolha A/B do público." : "sem escolha do público."),
|
||||
writingRules(provider, story.kind),
|
||||
`1. Escreva a bíblia em \`stories/${story.id}/biblia.md\`.`,
|
||||
`2. Escreva o primeiro episódio em \`${ep}\`.`,
|
||||
`3. Grave \`stories/${story.id}/meta.json\` exatamente assim: {"title": "<título final, até 60 caracteres>", "logline": "<premissa em 1–2 frases>"}.`,
|
||||
scriptCheck(story.id),
|
||||
"Não crie cena JSON, não renderize e não altere código. Ao terminar, resuma a história e liste as necessidades de produção.");
|
||||
} else if (kind === "script") {
|
||||
lines.push("", "## Tarefa: roteiro",
|
||||
story ? writingRules(provider, story.kind) : null,
|
||||
story ? `Crie a ${documentary ? "ficha de pauta" : "bíblia"} \`stories/${story.id}/biblia.md\` se não existir.` : "Peça a história antes de escrever.",
|
||||
episode ? `Escreva \`${episode.scriptPath}\`.` : null,
|
||||
story && documentary ? RESEARCH_ECONOMY : null,
|
||||
story ? scriptCheck(story.id) : null,
|
||||
"Não crie cena JSON nem renderize nesta tarefa.");
|
||||
} else if (kind === "godot") {
|
||||
lines.push("", "## Tarefa: construir uma cena no Godot (biblioteca de cenas)",
|
||||
"O pedido descreve uma cena (lugar, objeto, personagem, animação). Construa-a no Godot e guarde na biblioteca, para este e para os próximos vídeos.",
|
||||
"Siga `doc/godot/cenas.md` (contrato, manifesto, teste e checklist). As peças e cenas prontas estão resumidas em `doc/godot/api.md`: use as funções de lá sem abrir os .gd inteiros.",
|
||||
"1. Liste `godot/library/` e leia só os manifest.json: reaproveite cenas e peças (`godot/kits/`) em vez de refazer.",
|
||||
"2. Crie ou estenda `godot/library/<id>/template.gd` e `manifest.json` (id em minúsculas com hífens). Peças reaproveitáveis em .gd separados na mesma pasta.",
|
||||
`3. Teste com \`${CHECK_FRAMES} --config data/tmp/<id>-teste.json\`: ele renderiza o preview e devolve ~10 linhas (status, tempo, luz, contraste, movimento e enquadramento de cada quadro). ` +
|
||||
"Corrija até passar no checklist do guia, inclusive variant 0, 1 e 2 e cada opção dos parâmetros. " +
|
||||
"IMAGENS: no máximo UMA por render, a que o script indicar (folha de 480 px ou o quadro marcado). Não abra quadros soltos em resolução cheia, não abra imagens em lote " +
|
||||
"e não gere imagens próprias de QA: cada imagem fica no histórico e é reenviada a todo turno. Não entregue sem olhar ao menos uma folha.",
|
||||
"4. Não altere `godot/scripts/`, `scripts/` nem `panel/`: a cena aparece sozinha no painel (formulário e escolha automática pelas palavras-chave).",
|
||||
story ? `Contexto: a cena é para o vídeo "${story.title}". Leia \`stories/${story.id}/\` (roteiro: coluna Imagem de cada trecho) para acertar o que a cena precisa mostrar.` : null,
|
||||
"Ao terminar: rode `python .claude/skills/cenaforge/scripts/godot_api.py` (atualiza o resumo doc/godot/api.md), apague os JSON de teste de data/tmp/ e informe o id da cena, o que cada parâmetro faz e o tempo de render.");
|
||||
} else if (kind === "scene") {
|
||||
lines.push("", "## Tarefa: cena",
|
||||
episode
|
||||
? `Crie \`${episode.configPath}\` a partir do roteiro \`${episode.scriptPath}\`, usando ` +
|
||||
`\`python .claude/skills/cenaforge/scripts/new_scene.py --id ${story!.id}-${episode.file_key} --base ${BASE_SCENE}\` ` +
|
||||
"com --set para overlay (title, choiceA, choiceB) e o que o roteiro pedir dentro do contrato. Use seed diferente por episódio."
|
||||
: "Escolha um episódio antes de montar a cena.",
|
||||
"Valide (o script já valida). Não renderize: o render é disparado pelo painel. Se o roteiro pedir algo que o contrato não suporta, liste em 'pendências'.");
|
||||
}
|
||||
if (kind === "branches" && story && episode) {
|
||||
const children = childEpisodes(episode.id);
|
||||
const letters = children.map((c) => c.parent_choice).join(", ");
|
||||
lines.push("", `## Tarefa: preparar as ${children.length} vertentes do episódio \`${episode.file_key}\` (só o próximo nível)`,
|
||||
`O episódio \`${episode.scriptPath}\` termina numa decisão do público com ${children.length} opções (${letters}).`,
|
||||
"Leia a bíblia da história e o roteiro deste episódio (e dos anteriores no caminho, se precisar de contexto).",
|
||||
writingRules(provider, story.kind),
|
||||
`1. Escreva as opções da decisão em \`${rel(episodeChoicesPath(story.id, episode.file_key))}\`, exatamente assim: ` +
|
||||
`{${children.map((c) => `"${c.parent_choice}": "<texto curto da opção, até 60 caracteres>"`).join(", ")}}. ` +
|
||||
"As opções precisam ser realmente diferentes entre si e levar a consequências distintas.",
|
||||
"2. Para cada vertente, escreva o roteiro do episódio seguinte como consequência daquela escolha:",
|
||||
...children.map((c) => ` - ${c.parent_choice}: \`${rel(episodeScriptPath(story.id, c.file_key))}\``),
|
||||
" Cada roteiro termina na sua própria decisão para o público (o próximo nível será preparado depois).",
|
||||
"3. Para cada vertente, crie a cena com " +
|
||||
`\`python .claude/skills/cenaforge/scripts/new_scene.py --id ${story.id}-<file_key> --base ${BASE_SCENE}\` ` +
|
||||
"(seed diferente em cada uma), gerando:",
|
||||
...children.map((c) => ` - ${c.parent_choice}: \`${rel(episodeConfigPath(story.id, c.file_key))}\``),
|
||||
`4. No overlay da cena deste episódio (\`${episode.configPath}\`), ajuste choiceA/choiceB para as opções A e B ` +
|
||||
(children.length > 2 ? "(o render ainda só desenha duas opções na tela; C e D ficam no choices.json e no painel)." : "."),
|
||||
scriptCheck(story.id),
|
||||
"Não renderize, não gere áudio e não altere código. Ao terminar, liste as opções e os arquivos criados.");
|
||||
}
|
||||
lines.push("", "## Pedido", request);
|
||||
return lines.filter((l): l is string => l !== null).join("\n");
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Testes da proteção das rotas /api/** (src/proxy.ts): DNS rebinding (Host) e CSRF (Origin / Sec-Fetch-Site).
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { checkRequest } from "../proxy";
|
||||
|
||||
const h = (init: Record<string, string>) => new Headers(init);
|
||||
|
||||
describe("proxy: Host e origem", () => {
|
||||
it("leitura pelo endereço local passa; Host de outro domínio (DNS rebinding) é recusado", () => {
|
||||
assert.equal(checkRequest("GET", h({ host: "127.0.0.1:4500" })), null);
|
||||
assert.equal(checkRequest("GET", h({ host: "localhost:4500" })), null);
|
||||
assert.match(checkRequest("GET", h({ host: "ataque.exemplo:4500" }))!, /endereço local/);
|
||||
assert.match(checkRequest("GET", h({}))!, /endereço local/);
|
||||
});
|
||||
|
||||
it("mudança vinda do próprio painel passa", () => {
|
||||
assert.equal(checkRequest("POST", h({ host: "127.0.0.1:4500", origin: "http://127.0.0.1:4500" })), null);
|
||||
assert.equal(checkRequest("DELETE", h({ host: "localhost:4500", origin: "http://localhost:4500" })), null);
|
||||
assert.equal(checkRequest("PATCH", h({ host: "127.0.0.1:4500", "sec-fetch-site": "same-origin" })), null);
|
||||
});
|
||||
|
||||
it("mudança vinda de outro site (CSRF) ou sem origem é recusada", () => {
|
||||
assert.match(checkRequest("POST", h({ host: "127.0.0.1:4500", origin: "https://ataque.exemplo" }))!, /outro site/);
|
||||
assert.match(checkRequest("POST", h({ host: "127.0.0.1:4500", origin: "http://localhost:4500" }))!, /outro site/);
|
||||
assert.match(checkRequest("PUT", h({ host: "127.0.0.1:4500", "sec-fetch-site": "cross-site" }))!, /sem origem/);
|
||||
assert.match(checkRequest("POST", h({ host: "127.0.0.1:4500" }))!, /sem origem/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
// Ponte do painel com o Publicador (publisher/, 127.0.0.1:4530): o executor que guarda os tokens (cofre DPAPI),
|
||||
// os perfis de navegador do modo "sessão logada" e envia os vídeos às redes. O painel decide o quê e quando
|
||||
// (lib/publishing.ts); o Publicador só executa. Contrato: doc/publicacao/PLANO.md, seção 3.
|
||||
//
|
||||
// A chave e a porta vêm de publisher/.env, como o Clipador (lib/clipper.ts). Segredos (client secret, tokens)
|
||||
// passam por aqui só na ida — nada que o Publicador devolva contém segredo, e as rotas do painel filtram os campos.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ServiceError } from "./http";
|
||||
import { REPO_ROOT } from "./paths";
|
||||
import type { ConnectNext, ConnectionMode, NetworkStatus, Platform, Privacy, TiktokMode } from "./types";
|
||||
|
||||
const ENV_FILE = path.join(REPO_ROOT, "publisher", ".env");
|
||||
export const PUBLISHER_OFFLINE = "O Publicador não está rodando — inicie com pnpm dev.";
|
||||
|
||||
// ---------- formas do contrato (seção 3 do plano) ----------
|
||||
export type PublisherProfile = {
|
||||
profileId: string;
|
||||
platform: Platform;
|
||||
mode: ConnectionMode | null;
|
||||
status: NetworkStatus;
|
||||
displayName: string | null;
|
||||
handle: string | null;
|
||||
connectedAt: string | null;
|
||||
expiresAt: string | null;
|
||||
lastCheckAt: string | null;
|
||||
lastError: string | null;
|
||||
};
|
||||
|
||||
export type PublisherAppState = { configured: boolean; clientId: string | null; redirectUri: string; notes: string };
|
||||
|
||||
export type PublisherStatus = {
|
||||
browser: { found: boolean; kind: "chrome" | "msedge" | null; path: string | null };
|
||||
worker: "idle" | "busy";
|
||||
queue: number;
|
||||
};
|
||||
|
||||
export type PublisherJobInput = {
|
||||
profileId: string;
|
||||
platform: Platform;
|
||||
file: string;
|
||||
cover: string | null;
|
||||
title: string;
|
||||
caption: string;
|
||||
tags: string[];
|
||||
privacy: Privacy;
|
||||
publishAt: string | null;
|
||||
aiGenerated: boolean;
|
||||
madeForKids: boolean;
|
||||
tiktokMode: TiktokMode;
|
||||
/**
|
||||
* Referência idempotente (≤ 80): o Publicador guarda com UNIQUE e, se ela se repetir, devolve o job existente
|
||||
* em vez de criar outro. O painel manda "<publish_jobs.id>:<attempts>".
|
||||
*/
|
||||
clientRef: string;
|
||||
};
|
||||
|
||||
export type PublisherJobStatus = "queued" | "running" | "done" | "failed" | "needs_login" | "canceled";
|
||||
|
||||
export type PublisherJob = {
|
||||
jobId: string;
|
||||
profileId: string;
|
||||
platform: string;
|
||||
status: PublisherJobStatus;
|
||||
step: string;
|
||||
progress: number;
|
||||
remoteId: string | null;
|
||||
url: string | null;
|
||||
draft: boolean;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type TiktokCreatorInfo = {
|
||||
nickname: string;
|
||||
privacyOptions: string[];
|
||||
maxDurationS: number;
|
||||
commentDisabled: boolean;
|
||||
duetDisabled: boolean;
|
||||
stitchDisabled: boolean;
|
||||
};
|
||||
|
||||
/** profileId do contrato: um perfil por (canal, rede). */
|
||||
export const profileIdFor = (accountId: string, platform: Platform) => `${accountId}--${platform}`;
|
||||
|
||||
// ---------- transporte ----------
|
||||
function readPublisherEnv(): 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 = readPublisherEnv();
|
||||
if (!env.PUBLISHER_SERVICE_KEY) {
|
||||
throw new ServiceError("O Publicador não está instalado: rode o setup.bat (ele cria publisher/.env com a chave).", 503);
|
||||
}
|
||||
return { url: `http://127.0.0.1:${env.PUBLISHER_PORT || "4530"}${pathname}`, key: env.PUBLISHER_SERVICE_KEY };
|
||||
}
|
||||
|
||||
/** Mensagem de erro do Publicador: `{detail}` em pt-BR (ou a lista de validação do FastAPI). */
|
||||
async function serviceError(response: Response): Promise<ServiceError> {
|
||||
let message = `O Publicador respondeu ${response.status}.`;
|
||||
try {
|
||||
const body = (await response.json()) as { detail?: unknown; error?: unknown };
|
||||
const detail = body.detail ?? body.error;
|
||||
if (typeof detail === "string" && detail) message = detail;
|
||||
else if (Array.isArray(detail) && detail.length > 0) {
|
||||
message = detail.map((d) => (d && typeof d === "object" && "msg" in d ? String((d as { msg: unknown }).msg) : String(d))).join("; ");
|
||||
}
|
||||
} catch { /* corpo sem JSON: fica a mensagem com o código */ }
|
||||
// 4xx do Publicador = pedido recusado (mensagem dele); 5xx = falha do serviço (502 para o navegador).
|
||||
return new ServiceError(message, response.status >= 500 ? 502 : response.status);
|
||||
}
|
||||
|
||||
async function publisherFetch(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);
|
||||
if (init.body) headers.set("Content-Type", "application/json");
|
||||
try {
|
||||
return await fetch(url, { ...init, headers, signal: AbortSignal.timeout(timeoutMs), cache: "no-store" });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "TimeoutError") {
|
||||
throw new ServiceError("O Publicador demorou demais para responder. Veja o terminal do pnpm dev.", 504);
|
||||
}
|
||||
throw new ServiceError(PUBLISHER_OFFLINE, 503);
|
||||
}
|
||||
}
|
||||
|
||||
async function call<T>(method: string, pathname: string, body?: unknown, timeoutMs?: number): Promise<T> {
|
||||
const response = await publisherFetch(pathname, { method, body: body === undefined ? undefined : JSON.stringify(body) }, timeoutMs);
|
||||
if (!response.ok) throw await serviceError(response);
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
const enc = encodeURIComponent;
|
||||
|
||||
// ---------- chamadas ----------
|
||||
export type PublisherOnline = ({ online: true } & PublisherStatus) | { online: false; reason: string };
|
||||
|
||||
/** Saúde sem falhar: fora do ar (ou sem chave) vira `online: false` com o motivo em pt-BR. */
|
||||
export async function publisherStatus(): Promise<PublisherOnline> {
|
||||
try {
|
||||
const status = await call<PublisherStatus>("GET", "/v1/status", undefined, 5_000);
|
||||
return { online: true, browser: status.browser, worker: status.worker, queue: status.queue };
|
||||
} catch (error) {
|
||||
return { online: false, reason: error instanceof ServiceError ? error.message : PUBLISHER_OFFLINE };
|
||||
}
|
||||
}
|
||||
|
||||
/** Só os campos públicos do AppState (o Publicador já não manda segredo; aqui garantimos). */
|
||||
function cleanApp(app: PublisherAppState): PublisherAppState {
|
||||
return { configured: !!app.configured, clientId: app.clientId ?? null, redirectUri: String(app.redirectUri ?? ""), notes: String(app.notes ?? "") };
|
||||
}
|
||||
|
||||
export async function getApps(): Promise<Record<Platform, PublisherAppState>> {
|
||||
const apps = await call<Record<Platform, PublisherAppState>>("GET", "/v1/apps");
|
||||
return { youtube: cleanApp(apps.youtube), tiktok: cleanApp(apps.tiktok), instagram: cleanApp(apps.instagram) };
|
||||
}
|
||||
|
||||
/** YouTube/TikTok exigem clientId + clientSecret; no Instagram o secret é opcional (redirectUri vem vazio: a Meta não aceita localhost). */
|
||||
export async function putApp(platform: Platform, input: { clientId: string; clientSecret?: string }): Promise<PublisherAppState> {
|
||||
const body = input.clientSecret ? input : { clientId: input.clientId };
|
||||
return cleanApp(await call<PublisherAppState>("PUT", `/v1/apps/${platform}`, body));
|
||||
}
|
||||
|
||||
export async function deleteApp(platform: Platform): Promise<PublisherAppState> {
|
||||
return cleanApp(await call<PublisherAppState>("DELETE", `/v1/apps/${platform}`));
|
||||
}
|
||||
|
||||
export const getProfile = (profileId: string) => call<PublisherProfile>("GET", `/v1/profiles/${enc(profileId)}`, undefined, 15_000);
|
||||
|
||||
export const connectProfile = (profileId: string, platform: Platform, mode: ConnectionMode) =>
|
||||
// Modo sessão abre o navegador: pode demorar um pouco mais.
|
||||
call<{ profile: PublisherProfile; next: ConnectNext }>("POST", `/v1/profiles/${enc(profileId)}/connect`, { platform, mode }, 60_000);
|
||||
|
||||
export const pasteToken = (profileId: string, accessToken: string) =>
|
||||
call<PublisherProfile>("POST", `/v1/profiles/${enc(profileId)}/token`, { accessToken }, 60_000);
|
||||
|
||||
/** Confere a sessão logada (abre a página de envio e vê se está logado): pode levar até ~2 min. */
|
||||
export const checkSession = (profileId: string) =>
|
||||
call<PublisherProfile>("POST", `/v1/profiles/${enc(profileId)}/session/check`, {}, 150_000);
|
||||
|
||||
export const openSession = (profileId: string) =>
|
||||
call<{ profile: PublisherProfile; next: ConnectNext }>("POST", `/v1/profiles/${enc(profileId)}/session/open`, {}, 60_000);
|
||||
|
||||
export const deleteProfile = (profileId: string) => call<PublisherProfile>("DELETE", `/v1/profiles/${enc(profileId)}`, undefined, 60_000);
|
||||
|
||||
export const tiktokCreatorInfo = (profileId: string) =>
|
||||
call<TiktokCreatorInfo>("GET", `/v1/profiles/${enc(profileId)}/tiktok/creator-info`, undefined, 30_000);
|
||||
|
||||
/** Números dos posts (dashboard). ids = id do vídeo (YouTube, TikTok) ou código do reel (Instagram).
|
||||
* TikTok e Instagram abrem a janela logada e esperam um envio em andamento: pode levar alguns minutos. */
|
||||
export type PublisherPostStats = { remoteId: string; views: number | null; likes: number | null; comments: number | null; shares: number | null; saves: number | null };
|
||||
export const postStats = (profileId: string, ids: string[]) =>
|
||||
call<{ capturedAt: string; items: PublisherPostStats[]; missing: string[] }>("POST", `/v1/profiles/${enc(profileId)}/stats`, { ids }, 300_000);
|
||||
|
||||
export const createJob = (input: PublisherJobInput) => call<PublisherJob>("POST", "/v1/jobs", input, 30_000);
|
||||
|
||||
export const getJob = (jobId: string) => call<PublisherJob>("GET", `/v1/jobs/${enc(jobId)}`, undefined, 15_000);
|
||||
|
||||
export const cancelJob = (jobId: string) => call<PublisherJob>("POST", `/v1/jobs/${enc(jobId)}/cancel`, {}, 15_000);
|
||||
@@ -0,0 +1,421 @@
|
||||
// Migração v5 e fluxos da fila num banco TEMPORÁRIO (CENAFORGE_ROOT aponta para uma pasta nova; o banco real
|
||||
// data/cenaforge.db nunca é tocado). Monta um banco v4 com dados (perfil "mock", publicação simulada com
|
||||
// métricas), abre pelo db() — que migra para v5 com backup — e exercita aprovação de episódio, publicar agora,
|
||||
// cancelar, tentar de novo e o resultado do Publicador. Rodar: pnpm --filter cenaforge-panel test:panel
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
|
||||
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-pub-"));
|
||||
process.env.CENAFORGE_ROOT = ROOT;
|
||||
|
||||
type Db = typeof import("./db");
|
||||
type Publishing = typeof import("./publishing");
|
||||
type Accounts = typeof import("./accounts");
|
||||
type Settings = typeof import("./settings");
|
||||
let dbm: Db;
|
||||
let pub: Publishing;
|
||||
let accounts: Accounts;
|
||||
let settings: Settings;
|
||||
|
||||
const MP4 = "output/runs/r1/ep01.mp4";
|
||||
|
||||
before(async () => {
|
||||
dbm = await import("./db");
|
||||
// Banco v4 com dados, como o do usuário antes desta versão.
|
||||
fs.mkdirSync(path.join(ROOT, "data"), { recursive: true });
|
||||
const raw = new DatabaseSync(path.join(ROOT, "data", "cenaforge.db"));
|
||||
raw.exec("PRAGMA foreign_keys = OFF");
|
||||
for (const sql of dbm.MIGRATIONS.slice(0, 4)) raw.exec(sql);
|
||||
raw.exec("PRAGMA user_version = 4; PRAGMA foreign_keys = ON;");
|
||||
const t = "2026-11-01T00:00:00.000Z";
|
||||
raw.exec(`
|
||||
INSERT INTO stories (id, title, kind, created_at, updated_at) VALUES ('litoral', 'Histórias do Litoral', 'linear', '${t}', '${t}');
|
||||
INSERT INTO episodes (id, story_id, number, file_key, title, created_at) VALUES (1, 'litoral', 1, 'ep01', 'O farol', '${t}');
|
||||
INSERT INTO accounts (id, name, created_at, updated_at) VALUES ('canal', 'Canal', '${t}', '${t}');
|
||||
INSERT INTO account_networks (id, account_id, platform, handle, status, connected_at) VALUES (3, 'canal', 'youtube', '@canal', 'mock', '${t}');
|
||||
INSERT INTO account_stories (account_id, story_id, status, linked_at) VALUES ('canal', 'litoral', 'active', '${t}');
|
||||
INSERT INTO publications (id, episode_id, account_id, platform, url, published_at, simulated) VALUES (5, 1, 'canal', 'youtube', '', '${t}', 1);
|
||||
INSERT INTO publication_metrics (publication_id, captured_at, views, simulated) VALUES (5, '${t}', 1234, 1);
|
||||
INSERT INTO renders (id, episode_id, config_path, profile, status, mp4, started_at, finished_at)
|
||||
VALUES (1, 1, 'config/litoral-ep01.json', 'final', 'success', '${MP4}', '${t}', '${t}'),
|
||||
(2, 1, 'config/litoral-ep01.json', 'preview', 'success', 'output/runs/r0/ep01.mp4', '${t}', '${t}');
|
||||
`);
|
||||
raw.close();
|
||||
fs.mkdirSync(path.join(ROOT, "output", "runs", "r1"), { recursive: true });
|
||||
fs.writeFileSync(path.join(ROOT, MP4), "mp4 de teste");
|
||||
pub = await import("./publishing");
|
||||
accounts = await import("./accounts");
|
||||
settings = await import("./settings");
|
||||
});
|
||||
|
||||
after(() => {
|
||||
dbm.db().close();
|
||||
fs.rmSync(ROOT, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("migração v5", () => {
|
||||
it("migra com backup, preserva ids e não quebra chaves estrangeiras", () => {
|
||||
const version = dbm.get<{ user_version: number }>("PRAGMA user_version")!.user_version;
|
||||
assert.equal(version, dbm.MIGRATIONS.length);
|
||||
assert.equal(version, 8);
|
||||
assert.equal(fs.readdirSync(path.join(ROOT, "data", "backups")).filter((f) => f.startsWith("cenaforge-v4-")).length, 1);
|
||||
assert.deepEqual(dbm.all("PRAGMA foreign_key_check"), []);
|
||||
});
|
||||
|
||||
it("perfil mock vira disconnected, mantém o @ e ganha os padrões", () => {
|
||||
const n = dbm.get<Record<string, unknown>>("SELECT * FROM account_networks WHERE id = 3")!;
|
||||
assert.deepEqual(
|
||||
[n.status, n.handle, n.mode, n.enabled, n.daily_limit, n.privacy, n.tiktok_mode, n.connected_at],
|
||||
["disconnected", "@canal", null, 1, 3, "public", "direct", null]);
|
||||
});
|
||||
|
||||
it("publicações: mesmo id, métricas ainda ligadas, episode_id aceita NULL com clip_id", () => {
|
||||
const row = dbm.get<{ views: number; clip_id: number | null }>(
|
||||
"SELECT m.views, p.clip_id FROM publications p JOIN publication_metrics m ON m.publication_id = p.id WHERE p.id = 5")!;
|
||||
assert.deepEqual([row.views, row.clip_id], [1234, null]);
|
||||
dbm.run("INSERT INTO publications (episode_id, clip_id, account_id, platform, published_at, simulated) VALUES (NULL, 99, 'canal', 'tiktok', ?, 0)", dbm.now());
|
||||
assert.throws(() => dbm.run("INSERT INTO publications (episode_id, clip_id, account_id, platform, published_at) VALUES (NULL, NULL, 'canal', 'tiktok', ?)", dbm.now()));
|
||||
dbm.run("DELETE FROM publications WHERE clip_id = 99");
|
||||
});
|
||||
|
||||
it("canal com regras padrão e configurações iniciais", () => {
|
||||
const a = dbm.get<Record<string, unknown>>("SELECT approval_mode, timing, ai_label FROM accounts WHERE id = 'canal'")!;
|
||||
assert.deepEqual([a.approval_mode, a.timing, a.ai_label], ["manual", "best_slot", "auto"]);
|
||||
const s = settings.getSettings();
|
||||
assert.equal(s.publishingPaused, false);
|
||||
assert.equal(s.timezone, "America/Sao_Paulo");
|
||||
assert.deepEqual(s.slots.youtube, ["12:00", "15:00", "19:00"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("configurações", () => {
|
||||
it("valida e grava horários bons e pausa", () => {
|
||||
assert.throws(() => settings.updateSettings({ slots: { youtube: ["25:00"] } }), /HH:MM/);
|
||||
assert.throws(() => settings.updateSettings({ timezone: "Lua/Base" }), /Fuso/);
|
||||
const s = settings.updateSettings({ publishingPaused: true, slots: { tiktok: ["21:00", "08:00", "08:00"] } });
|
||||
assert.equal(s.publishingPaused, true);
|
||||
assert.deepEqual(s.slots.tiktok, ["08:00", "21:00"]);
|
||||
settings.updateSettings({ publishingPaused: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("canal: regras e ajustes da rede", () => {
|
||||
it("ligar o automático grava desde quando vale; desligar limpa", () => {
|
||||
assert.ok(accounts.updateAccount("canal", { approvalMode: "auto" }).auto_since);
|
||||
assert.equal(accounts.updateAccount("canal", { approvalMode: "manual" }).auto_since, null);
|
||||
assert.throws(() => accounts.updateAccount("canal", { timing: "amanhã" }), /Quando publicar/);
|
||||
});
|
||||
|
||||
it("ajustes por rede validados (privacidade por rede, limite 1–20)", () => {
|
||||
const n = accounts.updateNetworkSettings("canal", "tiktok", { dailyLimit: 5, privacy: "private", tiktokMode: "draft" });
|
||||
assert.deepEqual([n.status, n.daily_limit, n.privacy, n.tiktok_mode], ["disconnected", 5, "private", "draft"]);
|
||||
assert.throws(() => accounts.updateNetworkSettings("canal", "instagram", { privacy: "unlisted" }), /Privacidade/);
|
||||
assert.throws(() => accounts.updateNetworkSettings("canal", "youtube", { dailyLimit: 0 }), /1 a 20/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("episódio aprovado → fila → resultado", () => {
|
||||
it("exige render final (prévia não vale)", () => {
|
||||
assert.throws(() => pub.approveEpisode(1, { renderId: 2, title: "O farol" }), /render final/);
|
||||
assert.deepEqual(pub.episodeApproval(1).renders.map((r) => r.id), [1]);
|
||||
});
|
||||
|
||||
it("rede nunca conectada não recebe; conectada recebe, agendada no próximo horário bom", () => {
|
||||
assert.equal(pub.approveEpisode(1, { renderId: 1, title: "O farol", caption: "#litoral" }).jobs.length, 0);
|
||||
dbm.run("UPDATE account_networks SET status = 'connected', mode = 'official' WHERE account_id = 'canal' AND platform = 'youtube'");
|
||||
const approval = pub.approveEpisode(1, { renderId: 1, title: "O farol", caption: "#litoral" });
|
||||
assert.ok(approval.approvedAt);
|
||||
assert.equal(approval.jobs.length, 1);
|
||||
const job = approval.jobs[0];
|
||||
assert.deepEqual([job.platform, job.status, job.file, job.title, job.sourceLabel], ["youtube", "scheduled", MP4, "O farol", "Histórias do Litoral · ep01"]);
|
||||
assert.ok(new Date(job.scheduledAt!).getTime() > Date.now());
|
||||
assert.deepEqual(job.actions, ["publish-now", "reschedule", "edit", "cancel"]);
|
||||
});
|
||||
|
||||
it("publicar agora, cancelar, tentar de novo (volta a aguardar) e aprovar", async () => {
|
||||
const id = pub.listJobs({ sourceKind: "episode" })[0].id;
|
||||
assert.equal((await pub.publishNow(id)).status, "queued");
|
||||
assert.equal((await pub.cancelPublishJob(id)).status, "canceled");
|
||||
assert.equal(pub.retryJob(id).status, "awaiting_approval");
|
||||
assert.equal((await pub.approveJob(id)).status, "scheduled");
|
||||
assert.equal(pub.publishingSummary().counts.scheduled, 1);
|
||||
});
|
||||
|
||||
it("mudar horário à mão e título", () => {
|
||||
const id = pub.listJobs({ sourceKind: "episode" })[0].id;
|
||||
const at = new Date(Date.now() + 3 * 86_400_000).toISOString();
|
||||
const job = pub.updateJob(id, { scheduledAt: at, title: "O farol — parte 1" });
|
||||
assert.deepEqual([job.status, job.scheduledAt, job.title], ["scheduled", at, "O farol — parte 1"]);
|
||||
assert.throws(() => pub.updateJob(id, { scheduledAt: "2020-01-01T00:00:00Z" }), /futuro/);
|
||||
assert.throws(() => pub.updateJob(id, { title: "x".repeat(101) }), /100/);
|
||||
});
|
||||
|
||||
it("Publicador terminou sem link: falha (não diz publicado)", () => {
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE source_kind = 'episode'")!;
|
||||
dbm.run("UPDATE publish_jobs SET status = 'publishing', publisher_job_id = 'pj-1' WHERE id = ?", row.id);
|
||||
pub.finishFromPublisher(row, { status: "done", step: "publicado; link não encontrado na tela", progress: 1, remoteId: null, url: null, draft: false, error: null });
|
||||
const job = pub.getJobView(row.id)!;
|
||||
assert.equal(job.status, "failed");
|
||||
assert.match(job.error!, /não confirmou/);
|
||||
assert.equal(dbm.get("SELECT 1 FROM publications WHERE job_id = ?", row.id), undefined);
|
||||
});
|
||||
|
||||
it("com URL: published e publicação real substitui a simulada", () => {
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE source_kind = 'episode'")!;
|
||||
pub.finishFromPublisher(row, { status: "done", step: "Publicado.", progress: 1, remoteId: "abc123", url: "https://youtu.be/abc123", draft: false, error: null });
|
||||
const job = pub.getJobView(row.id)!;
|
||||
assert.deepEqual([job.status, job.url, job.remoteId], ["published", "https://youtu.be/abc123", "abc123"]);
|
||||
assert.ok(job.publishedAt);
|
||||
const pubs = dbm.all<{ simulated: number; url: string; job_id: number }>("SELECT * FROM publications WHERE episode_id = 1 AND account_id = 'canal' AND platform = 'youtube'");
|
||||
assert.deepEqual(pubs.map((p) => [p.simulated, p.url, p.job_id]), [[0, "https://youtu.be/abc123", row.id]]);
|
||||
});
|
||||
|
||||
it("needs_login no envio marca o perfil", () => {
|
||||
const ts = dbm.now();
|
||||
const info = dbm.run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, file, title, status, publisher_job_id, created_at, updated_at)
|
||||
VALUES ('canal', 'youtube', 'clip', '42', ?, 'Corte', 'publishing', 'pj-2', ?, ?)`, MP4, ts, ts);
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE id = ?", Number(info.lastInsertRowid))!;
|
||||
pub.finishFromPublisher(row, { status: "needs_login", step: "", progress: 0.1, remoteId: null, url: null, draft: false, error: "Sessão expirou." });
|
||||
assert.equal(pub.getJobView(row.id)!.status, "needs_login");
|
||||
assert.equal(accounts.getNetwork("canal", "youtube")!.status, "needs_login");
|
||||
});
|
||||
|
||||
it("desfazer a aprovação cancela o que não saiu e mantém o publicado", async () => {
|
||||
dbm.run("INSERT INTO account_networks (account_id, platform, status, mode) VALUES ('canal', 'instagram', 'connected', 'session')");
|
||||
const approval = pub.approveEpisode(1, { renderId: 1, title: "O farol", caption: "" });
|
||||
const insta = approval.jobs.find((j) => j.platform === "instagram")!;
|
||||
assert.equal(insta.status, "scheduled");
|
||||
const after = await pub.unapproveEpisode(1);
|
||||
assert.equal(after.approvedAt, null);
|
||||
assert.equal(after.jobs.find((j) => j.platform === "instagram")!.status, "canceled");
|
||||
assert.equal(after.jobs.find((j) => j.platform === "youtube")!.status, "published");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------- despachante com um Publicador falso (fetch simulado; nenhuma porta aberta) ----------
|
||||
type FakeCall = { method: string; path: string; body: Record<string, unknown> | null };
|
||||
|
||||
describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
|
||||
const calls: FakeCall[] = [];
|
||||
let onCreate: (body: Record<string, unknown>) => Promise<Response> = async () => { throw new Error("sem roteiro"); };
|
||||
let realFetch: typeof fetch;
|
||||
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
const remoteJob = (jobId: string, status = "queued") => ({
|
||||
jobId, profileId: "canal--youtube", platform: "youtube", status, step: "Na fila do Publicador.", progress: 0,
|
||||
remoteId: null, url: null, draft: false, error: null, createdAt: dbm.now(), updatedAt: dbm.now(),
|
||||
});
|
||||
const profile = (profileId: string) => ({
|
||||
profileId, platform: profileId.split("--")[1], mode: "official", status: "connected", displayName: "Canal", handle: "@canal",
|
||||
connectedAt: dbm.now(), expiresAt: null, lastCheckAt: dbm.now(), lastError: null,
|
||||
});
|
||||
let nextId = 100;
|
||||
/** Job de corte na fila (fonte twitch-xis ligada ao canal), pronto para sair agora. */
|
||||
const queuedClipJob = (over: Record<string, string | number | null> = {}): number => {
|
||||
const ts = dbm.now();
|
||||
const row = { status: "queued", scheduled_at: ts, schedule_source: "now", ...over };
|
||||
return Number(dbm.run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, title, caption, status,
|
||||
scheduled_at, schedule_source, created_at, updated_at)
|
||||
VALUES ('canal', 'youtube', 'clip', ?, 'twitch-xis', ?, 'Corte', '#corte', ?, ?, ?, ?, ?)`,
|
||||
String(nextId++), MP4, row.status, row.scheduled_at, row.schedule_source, ts, ts).lastInsertRowid);
|
||||
};
|
||||
const clearQueue = () => dbm.run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'user'
|
||||
WHERE status IN ('queued', 'scheduled', 'awaiting_approval', 'publishing')`);
|
||||
|
||||
before(() => {
|
||||
fs.mkdirSync(path.join(ROOT, "publisher"), { recursive: true });
|
||||
fs.writeFileSync(path.join(ROOT, "publisher", ".env"), "PUBLISHER_SERVICE_KEY=chave-de-teste\nPUBLISHER_PORT=4530\n");
|
||||
dbm.run("UPDATE account_networks SET status = 'connected', mode = 'official', enabled = 1 WHERE account_id = 'canal'");
|
||||
accounts.linkChannel("canal", "twitch-xis");
|
||||
realFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = new URL(String(input instanceof Request ? input.url : input));
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
|
||||
calls.push({ method, path: url.pathname, body });
|
||||
if (url.pathname === "/v1/status") return json({ browser: { found: true, kind: "chrome", path: "x" }, worker: "idle", queue: 0 });
|
||||
const prof = /^\/v1\/profiles\/([^/]+)$/.exec(url.pathname);
|
||||
if (prof && method === "GET") return json(profile(decodeURIComponent(prof[1])));
|
||||
if (url.pathname === "/v1/jobs" && method === "POST") return onCreate(body!);
|
||||
const cancel = /^\/v1\/jobs\/([^/]+)\/cancel$/.exec(url.pathname);
|
||||
if (cancel) return json(remoteJob(cancel[1], "canceled"));
|
||||
const job = /^\/v1\/jobs\/([^/]+)$/.exec(url.pathname);
|
||||
if (job) return json(remoteJob(job[1], "running"));
|
||||
return json({ detail: "rota não simulada" }, 404);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
it("cancelar enquanto o Publicador cria o envio: o job fica cancelado e o envio é cancelado lá", async () => {
|
||||
clearQueue();
|
||||
const id = queuedClipJob();
|
||||
onCreate = async () => {
|
||||
await pub.cancelPublishJob(id); // você clicou "Cancelar" bem no meio do envio
|
||||
return json(remoteJob("pj-corrida"), 201);
|
||||
};
|
||||
await pub.dispatcherTick();
|
||||
const job = pub.getJobView(id)!;
|
||||
assert.deepEqual([job.status, job.cancelReason], ["canceled", "user"]);
|
||||
assert.ok(calls.some((c) => c.method === "POST" && c.path === "/v1/jobs/pj-corrida/cancel"));
|
||||
});
|
||||
|
||||
it("falha ambígua (conexão caiu): fica na fila e o reenvio usa o MESMO clientRef; tentar de novo troca", async () => {
|
||||
clearQueue();
|
||||
const id = queuedClipJob();
|
||||
const refs: string[] = [];
|
||||
let first = true;
|
||||
onCreate = async (body) => {
|
||||
refs.push(String(body.clientRef));
|
||||
if (first) { first = false; throw new TypeError("fetch failed"); }
|
||||
return json(remoteJob("pj-dedup"), 200); // o Publicador reconheceu o clientRef: devolve o existente
|
||||
};
|
||||
await pub.dispatcherTick();
|
||||
assert.equal(pub.getJobView(id)!.status, "queued");
|
||||
await pub.dispatcherTick();
|
||||
const job = pub.getJobView(id)!;
|
||||
assert.deepEqual([job.status, job.attempts], ["publishing", 0]);
|
||||
assert.deepEqual(refs, [`${id}:0`, `${id}:0`]);
|
||||
|
||||
// O envio falhou no meio: pode já estar na rede ⇒ "Tentar de novo" exige confirmação e usa um clientRef novo.
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE id = ?", id)!;
|
||||
pub.finishFromPublisher(row, { status: "failed", step: "", progress: 0.5, remoteId: null, url: null, draft: false, error: "caiu" });
|
||||
assert.equal(pub.getJobView(id)!.mayBeLive, true);
|
||||
assert.throws(() => pub.retryJob(id), /Confira na rede/);
|
||||
assert.equal(pub.retryJob(id, { confirm: true }).attempts, 1);
|
||||
onCreate = async (body) => { refs.push(String(body.clientRef)); return json(remoteJob("pj-nova"), 201); };
|
||||
await pub.dispatcherTick();
|
||||
assert.equal(refs.at(-1), `${id}:1`);
|
||||
});
|
||||
|
||||
it("placeApproved não desfaz um cancelamento (UPDATE condicional)", () => {
|
||||
clearQueue();
|
||||
const id = queuedClipJob({ status: "canceled" });
|
||||
assert.equal(pub.placeApproved(id, { from: ["awaiting_approval"] }), false);
|
||||
assert.equal(pub.getJobView(id)!.status, "canceled");
|
||||
});
|
||||
|
||||
it("agendado pela agenda automática que venceu com o painel fechado é reagendado, não disparado", async () => {
|
||||
clearQueue();
|
||||
settings.updateSettings({ publishingPaused: true });
|
||||
const twoHoursAgo = new Date(Date.now() - 2 * 3_600_000).toISOString();
|
||||
const auto = queuedClipJob({ status: "scheduled", scheduled_at: twoHoursAgo, schedule_source: "auto" });
|
||||
const manual = queuedClipJob({ status: "scheduled", scheduled_at: twoHoursAgo, schedule_source: "manual" });
|
||||
await pub.dispatcherTick();
|
||||
const reflowed = pub.getJobView(auto)!;
|
||||
assert.equal(reflowed.status, "scheduled");
|
||||
assert.ok(new Date(reflowed.scheduledAt!).getTime() > Date.now());
|
||||
assert.match(reflowed.step, /Reagendado/);
|
||||
assert.equal(pub.getJobView(manual)!.status, "queued"); // horário escolhido à mão sai (aqui fica esperando a pausa)
|
||||
settings.updateSettings({ publishingPaused: false });
|
||||
});
|
||||
|
||||
it("desligar a fonte cancela os cortes não enviados; religar recomeça o linked_at", () => {
|
||||
clearQueue();
|
||||
const id = queuedClipJob({ status: "scheduled", scheduled_at: new Date(Date.now() + 3_600_000).toISOString(), schedule_source: "auto" });
|
||||
const linkedBefore = dbm.get<{ linked_at: string }>("SELECT linked_at FROM account_channels WHERE account_id = 'canal' AND channel_id = 'twitch-xis'")!;
|
||||
accounts.endChannel("canal", "twitch-xis");
|
||||
assert.deepEqual([pub.getJobView(id)!.status, pub.getJobView(id)!.cancelReason], ["canceled", "unlinked"]);
|
||||
const t0 = Date.now();
|
||||
while (Date.now() === t0) { /* garante outro milissegundo no relógio */ }
|
||||
accounts.linkChannel("canal", "twitch-xis");
|
||||
const afterLink = dbm.get<{ linked_at: string; status: string }>("SELECT linked_at, status FROM account_channels WHERE account_id = 'canal' AND channel_id = 'twitch-xis'")!;
|
||||
assert.equal(afterLink.status, "active");
|
||||
assert.ok(afterLink.linked_at > linkedBefore.linked_at, "religar precisa atualizar linked_at");
|
||||
});
|
||||
|
||||
it("job de fonte desligada na fila não sai (confere o vínculo antes de enviar)", async () => {
|
||||
clearQueue();
|
||||
const id = queuedClipJob();
|
||||
dbm.run("UPDATE account_channels SET status = 'ended' WHERE account_id = 'canal' AND channel_id = 'twitch-xis'");
|
||||
const sent = calls.length;
|
||||
onCreate = async () => json(remoteJob("pj-nao"), 201);
|
||||
await pub.dispatcherTick();
|
||||
assert.equal(pub.getJobView(id)!.status, "canceled");
|
||||
assert.equal(calls.slice(sent).some((c) => c.path === "/v1/jobs" && c.method === "POST"), false);
|
||||
accounts.linkChannel("canal", "twitch-xis");
|
||||
});
|
||||
});
|
||||
|
||||
describe("\"Publicar\" no cartão do corte (origem manual)", () => {
|
||||
let realFetch: typeof fetch;
|
||||
const envFile = path.join(ROOT, "clipper", ".env");
|
||||
const clip = (id: number, status: string) => ({
|
||||
id, status, channelId: "twitch-xis", createdAt: "2026-11-01T00:00:00.000Z", title: "Corte bom", caption: "#corte",
|
||||
file: MP4, thumb: null, edit: null,
|
||||
});
|
||||
|
||||
before(() => {
|
||||
fs.mkdirSync(path.dirname(envFile), { recursive: true });
|
||||
fs.writeFileSync(envFile, "CLIPPER_SERVICE_KEY=chave-de-teste\nCLIPPER_PORT=4520\n");
|
||||
dbm.run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'user' WHERE status IN ('queued', 'scheduled', 'awaiting_approval', 'publishing')`);
|
||||
// YouTube conectado e TikTok desconectado neste canal (testes anteriores podem ter mexido nas redes).
|
||||
dbm.run("UPDATE account_networks SET status = 'connected', enabled = 1 WHERE account_id = 'canal' AND platform = 'youtube'");
|
||||
dbm.run("UPDATE account_networks SET status = 'disconnected' WHERE account_id = 'canal' AND platform = 'tiktok'");
|
||||
realFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = new URL(String(input instanceof Request ? input.url : input));
|
||||
const m = /^\/v1\/clips\/(\d+)$/.exec(url.pathname);
|
||||
const body = m && (m[1] === "500" ? clip(500, "approved") : m[1] === "501" ? clip(501, "ready") : null);
|
||||
return body ? Response.json(body) : Response.json({ detail: "não achei" }, { status: 404 });
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
fs.rmSync(envFile, { force: true });
|
||||
});
|
||||
|
||||
it("cria job aprovado e manual nas redes conectadas; a não conectada fica de fora com o motivo", async () => {
|
||||
const r = await pub.publishClip(500, { accountId: "canal", platforms: ["youtube", "tiktok"], timing: "now" });
|
||||
assert.equal(r.placed, 1);
|
||||
assert.deepEqual(r.skipped, [{ platform: "tiktok", reason: "não está conectada neste canal" }]);
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE source_kind = 'clip' AND source_id = '500'")!;
|
||||
assert.deepEqual([row.status, row.origin, row.schedule_source, row.title], ["queued", "manual", "now", "Corte bom"]);
|
||||
|
||||
// De novo, no próximo horário bom: a rede já está na fila ⇒ fica de fora.
|
||||
const again = await pub.publishClip(500, { accountId: "canal", platforms: ["youtube"], timing: "best_slot" });
|
||||
assert.deepEqual([again.placed, again.skipped[0]?.reason], [0, "já está na fila"]);
|
||||
});
|
||||
|
||||
it("desligar a fonte do canal não cancela o que você publicou à mão", () => {
|
||||
accounts.endChannel("canal", "twitch-xis");
|
||||
assert.equal(dbm.get<{ status: string }>("SELECT status FROM publish_jobs WHERE source_kind = 'clip' AND source_id = '500'")!.status, "queued");
|
||||
accounts.linkChannel("canal", "twitch-xis");
|
||||
});
|
||||
|
||||
it("\"Já saiu: informar o link\": falhou ⇒ publicado com o link (e conta como publicação real)", () => {
|
||||
const id = dbm.get<{ id: number }>("SELECT id FROM publish_jobs WHERE source_kind = 'clip' AND source_id = '500'")!.id;
|
||||
dbm.run("UPDATE publish_jobs SET status = 'failed', publisher_job_id = 'pj-sem-link', error = 'sem link' WHERE id = ?", id);
|
||||
assert.throws(() => pub.markPublished(id, { url: "https://www.tiktok.com/@canal/video/1" }), /link do vídeo no YouTube/);
|
||||
const job = pub.markPublished(id, { url: "https://youtu.be/AbC123xyz" });
|
||||
assert.deepEqual([job.status, job.url, job.remoteId, job.error], ["published", "https://www.youtube.com/shorts/AbC123xyz", "AbC123xyz", null]);
|
||||
assert.ok(dbm.get("SELECT 1 FROM publications WHERE job_id = ? AND simulated = 0", id));
|
||||
assert.throws(() => pub.markPublished(id, { url: "https://youtu.be/AbC123xyz" }), /ficou com problema/);
|
||||
});
|
||||
|
||||
it("\"Apaguei na rede\": publicado ⇒ cancelado sem link nem registro; \"Publicar\" manda de novo (nova tentativa)", async () => {
|
||||
const id = dbm.get<{ id: number }>("SELECT id FROM publish_jobs WHERE source_kind = 'clip' AND source_id = '500'")!.id;
|
||||
assert.equal(pub.getJobView(id)!.status, "published");
|
||||
const attempts = pub.getJobView(id)!.attempts;
|
||||
const job = pub.markRemoved(id);
|
||||
assert.deepEqual([job.status, job.url, job.remoteId, job.actions], ["canceled", null, null, ["retry"]]);
|
||||
assert.equal(dbm.get("SELECT 1 FROM publications WHERE job_id = ?", id), undefined);
|
||||
assert.throws(() => pub.markRemoved(id), /está publicado/);
|
||||
const again = await pub.publishClip(500, { accountId: "canal", platforms: ["youtube"], timing: "now" });
|
||||
assert.equal(again.placed, 1);
|
||||
const after = pub.getJobView(id)!;
|
||||
assert.deepEqual([after.status, after.attempts], ["queued", attempts + 1]);
|
||||
});
|
||||
|
||||
it("recusa corte que não está aprovado, canal inexistente e lista vazia de redes", async () => {
|
||||
await assert.rejects(pub.publishClip(501, { accountId: "canal", platforms: ["youtube"] }), /aprovado/);
|
||||
await assert.rejects(pub.publishClip(500, { accountId: "nao-existe", platforms: ["youtube"] }), /canal de publicação/);
|
||||
await assert.rejects(pub.publishClip(500, { accountId: "canal", platforms: [] }), /pelo menos uma rede/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
// Testes das regras puras da publicação: agenda (horário bom, limite do dia, espaçamento, fuso), decisões do
|
||||
// despachante sobre os cortes (aprovação manual/automática, cancelamento quando o corte volta para `pending`)
|
||||
// e leitura honesta do resultado do Publicador. Rodar: pnpm --filter cenaforge-panel test:panel
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
DEFAULT_SLOTS, clientRefFor, isDue, localDay, mayBeLive, needsReflow, nextFreeSlot, parseVideoUrl, placeJob, planClipSync, readPublisherJob, sendBlocker,
|
||||
tagsFromCaption, zonedTimeToUtc, type ClipInfo, type ClipTarget, type ExistingJob,
|
||||
} from "./publishing-rules";
|
||||
|
||||
const TZ = "America/Sao_Paulo";
|
||||
/** Instante a partir do relógio de Brasília (−03:00, sem horário de verão desde 2019). */
|
||||
const br = (local: string) => new Date(`${local}:00-03:00`);
|
||||
|
||||
describe("agenda: próximo horário bom", () => {
|
||||
const base = { timezone: TZ, slots: DEFAULT_SLOTS.youtube, dailyLimit: 3, occupied: [] as Date[] };
|
||||
|
||||
it("antes do primeiro horário do dia escolhe o primeiro", () => {
|
||||
assert.equal(nextFreeSlot({ ...base, now: br("2026-11-17T10:00") })?.toISOString(), br("2026-11-17T12:00").toISOString());
|
||||
});
|
||||
|
||||
it("horário já passado é pulado", () => {
|
||||
assert.equal(nextFreeSlot({ ...base, now: br("2026-11-17T12:30") })?.toISOString(), br("2026-11-17T15:00").toISOString());
|
||||
});
|
||||
|
||||
it("depois do último horário vai para o dia seguinte", () => {
|
||||
assert.equal(nextFreeSlot({ ...base, now: br("2026-11-17T20:00") })?.toISOString(), br("2026-11-18T12:00").toISOString());
|
||||
});
|
||||
|
||||
it("respeita o limite por dia (publicados + agendados)", () => {
|
||||
const occupied = [br("2026-11-17T08:00"), br("2026-11-17T09:30"), br("2026-11-17T11:00")];
|
||||
assert.equal(nextFreeSlot({ ...base, occupied, now: br("2026-11-17T10:00") })?.toISOString(), br("2026-11-18T12:00").toISOString());
|
||||
});
|
||||
|
||||
it("espaça pelo menos 1 h do vídeo mais próximo na mesma rede", () => {
|
||||
const occupied = [br("2026-11-17T12:30")];
|
||||
assert.equal(nextFreeSlot({ ...base, occupied, now: br("2026-11-17T10:00") })?.toISOString(), br("2026-11-17T15:00").toISOString());
|
||||
});
|
||||
|
||||
it("dia conta pelo fuso de Brasília, não pelo UTC", () => {
|
||||
// 22:30 em Brasília já é dia seguinte em UTC.
|
||||
assert.equal(localDay(br("2026-11-17T22:30"), TZ), "2026-11-17");
|
||||
});
|
||||
|
||||
it("sem horários ou limite zero: nada", () => {
|
||||
assert.equal(nextFreeSlot({ ...base, slots: [], now: br("2026-11-17T10:00") }), null);
|
||||
assert.equal(nextFreeSlot({ ...base, dailyLimit: 0, now: br("2026-11-17T10:00") }), null);
|
||||
});
|
||||
|
||||
it("fuso com horário de verão converte certo", () => {
|
||||
assert.equal(zonedTimeToUtc("2026-07-01", "12:00", "America/New_York").toISOString(), "2026-07-01T16:00:00.000Z");
|
||||
assert.equal(zonedTimeToUtc("2026-12-01", "12:00", "America/New_York").toISOString(), "2026-12-01T17:00:00.000Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("agenda: onde o job aprovado entra", () => {
|
||||
const base = { timezone: TZ, slots: DEFAULT_SLOTS.tiktok, dailyLimit: 2, occupied: [] as Date[], now: br("2026-11-17T10:00") };
|
||||
|
||||
it("na hora: fila agora", () => {
|
||||
const p = placeJob("now", base);
|
||||
assert.equal(p.status, "queued");
|
||||
assert.equal(p.status === "queued" && p.scheduledAt.toISOString(), base.now.toISOString());
|
||||
});
|
||||
|
||||
it("na hora, mas o dia já bateu o limite: próximo horário bom de amanhã", () => {
|
||||
const p = placeJob("now", { ...base, occupied: [br("2026-11-17T08:00"), br("2026-11-17T09:00")] });
|
||||
assert.equal(p.status, "scheduled");
|
||||
assert.equal(p.status === "scheduled" && p.scheduledAt.toISOString(), br("2026-11-18T08:00").toISOString());
|
||||
});
|
||||
|
||||
it("melhor horário", () => {
|
||||
const p = placeJob("best_slot", base);
|
||||
assert.equal(p.status === "scheduled" && p.scheduledAt.toISOString(), br("2026-11-17T12:00").toISOString());
|
||||
});
|
||||
|
||||
it("horário escolhido à mão (no futuro) vale", () => {
|
||||
const preferredAt = br("2026-11-20T07:15");
|
||||
const p = placeJob("best_slot", { ...base, preferredAt });
|
||||
assert.equal(p.status === "scheduled" && p.scheduledAt.toISOString(), preferredAt.toISOString());
|
||||
});
|
||||
|
||||
it("vencido só sai quando passa o horário", () => {
|
||||
assert.equal(isDue({ status: "scheduled", scheduledAt: br("2026-11-17T12:00").toISOString() }, br("2026-11-17T11:59")), false);
|
||||
assert.equal(isDue({ status: "scheduled", scheduledAt: br("2026-11-17T12:00").toISOString() }, br("2026-11-17T12:00")), true);
|
||||
assert.equal(isDue({ status: "awaiting_approval", scheduledAt: null }, br("2026-11-17T12:00")), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("despachante: cortes do Clipador", () => {
|
||||
const linkedAt = "2026-11-10T00:00:00.000Z";
|
||||
const target = (over: Partial<ClipTarget> = {}): ClipTarget => ({
|
||||
accountId: "canal", approvalMode: "manual", autoSince: null, channels: [{ channelId: "twitch-x", linkedAt }], platforms: ["youtube"], ...over,
|
||||
});
|
||||
const clip = (over: Partial<ClipInfo> = {}): ClipInfo => ({ id: 7, status: "ready", channelId: "twitch-x", createdAt: "2026-11-16T10:00:00+00:00", ...over });
|
||||
const job = (over: Partial<ExistingJob> = {}): ExistingJob => ({
|
||||
id: 1, accountId: "canal", platform: "youtube", sourceId: "7", status: "awaiting_approval", cancelReason: null, publisherJobId: null, ...over,
|
||||
});
|
||||
const plan = (input: Partial<Parameters<typeof planClipSync>[0]>) =>
|
||||
planClipSync({ clips: [], complete: true, autoApproved: new Set(), targets: [target()], jobs: [], ...input });
|
||||
|
||||
it("manual: corte pronto vira job aguardando aprovação e NÃO é aprovado no Clipador", () => {
|
||||
assert.deepEqual(plan({ clips: [clip()] }), [{ kind: "create", clipId: 7, accountId: "canal", platform: "youtube", approved: false }]);
|
||||
});
|
||||
|
||||
it("manual: job aguardando continua aguardando enquanto o corte só está pronto", () => {
|
||||
assert.deepEqual(plan({ clips: [clip()], jobs: [job()] }), []);
|
||||
});
|
||||
|
||||
it("automático: aprova no Clipador e cria o job já aprovado", () => {
|
||||
const actions = plan({ clips: [clip()], targets: [target({ approvalMode: "auto", autoSince: linkedAt })] });
|
||||
assert.deepEqual(actions, [
|
||||
{ kind: "create", clipId: 7, accountId: "canal", platform: "youtube", approved: true },
|
||||
{ kind: "approve_clip", clipId: 7 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("automático não aprova sozinho corte anterior ao vínculo ou a ligar o automático", () => {
|
||||
const old = plan({ clips: [clip({ createdAt: "2026-11-01T00:00:00+00:00" })], targets: [target({ approvalMode: "auto" })] });
|
||||
assert.deepEqual(old, [{ kind: "create", clipId: 7, accountId: "canal", platform: "youtube", approved: false }]);
|
||||
const beforeAuto = plan({ clips: [clip()], targets: [target({ approvalMode: "auto", autoSince: "2026-11-17T00:00:00.000Z" })] });
|
||||
assert.equal(beforeAuto.some((a) => a.kind === "approve_clip"), false);
|
||||
});
|
||||
|
||||
it("aprovado por humano no Clipador: jobs aguardando entram na agenda", () => {
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "approved" })], jobs: [job()] }), [{ kind: "approve", jobId: 1 }]);
|
||||
});
|
||||
|
||||
it("aprovação automática de outro canal não vale para um canal manual", () => {
|
||||
const actions = plan({ clips: [clip({ status: "approved" })], jobs: [job()], autoApproved: new Set([7]) });
|
||||
assert.deepEqual(actions, []);
|
||||
});
|
||||
|
||||
it("corte voltou para pending (editado/exportado): cancela os jobs não enviados", () => {
|
||||
const jobs = [job({ id: 1, status: "scheduled" }), job({ id: 2, platform: "tiktok", status: "queued" }), job({ id: 3, platform: "instagram", status: "awaiting_approval" })];
|
||||
const actions = plan({ clips: [clip({ status: "pending" })], jobs });
|
||||
assert.deepEqual(actions, [1, 2, 3].map((jobId) => ({ kind: "cancel", jobId, reason: "source_changed" })));
|
||||
});
|
||||
|
||||
it("job já entregue ao Publicador não é cancelado por edição do corte", () => {
|
||||
const actions = plan({ clips: [clip({ status: "pending" })], jobs: [job({ status: "queued", publisherJobId: "pj-1" }), job({ id: 2, status: "publishing", publisherJobId: "pj-2" })] });
|
||||
assert.deepEqual(actions, []);
|
||||
});
|
||||
|
||||
it("corte rejeitado ou apagado cancela; sem a consulta completa, ausência não cancela", () => {
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "rejected" })], jobs: [job()] }), [{ kind: "cancel", jobId: 1, reason: "source_changed" }]);
|
||||
assert.deepEqual(plan({ clips: [], jobs: [job()] }), [{ kind: "cancel", jobId: 1, reason: "source_changed" }]);
|
||||
assert.deepEqual(plan({ clips: [], jobs: [job()], complete: false }), []);
|
||||
});
|
||||
|
||||
it("corte renderizado de novo: job cancelado pela edição renasce; cancelado por você, não", () => {
|
||||
assert.deepEqual(plan({ clips: [clip()], jobs: [job({ status: "canceled", cancelReason: "source_changed" })] }), [{ kind: "revive", jobId: 1, approved: false }]);
|
||||
assert.deepEqual(plan({ clips: [clip()], jobs: [job({ status: "canceled", cancelReason: "user" })] }), []);
|
||||
});
|
||||
|
||||
it("aprovação automática esquecida quando o corte sai de approved", () => {
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "pending" })], autoApproved: new Set([7]) }), [{ kind: "forget_auto", clipId: 7 }]);
|
||||
});
|
||||
|
||||
it("todos os jobs publicados: marca o corte published no Clipador", () => {
|
||||
const jobs = [job({ status: "published" }), job({ id: 2, platform: "tiktok", status: "canceled", cancelReason: "user" })];
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "approved" })], jobs, targets: [target({ platforms: ["youtube", "tiktok"] })] }),
|
||||
[{ kind: "mark_clip_published", clipId: 7 }]);
|
||||
const pending = [job({ status: "published" }), job({ id: 2, platform: "tiktok", status: "failed" })];
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "approved" })], jobs: pending, targets: [target({ platforms: ["youtube", "tiktok"] })] }), []);
|
||||
});
|
||||
|
||||
it("fonte desligada do canal: cancela o não enviado (unlinked); religada, o job renasce", () => {
|
||||
assert.deepEqual(plan({ clips: [clip()], jobs: [job({ status: "scheduled" })], targets: [] }), [{ kind: "cancel", jobId: 1, reason: "unlinked" }]);
|
||||
assert.deepEqual(plan({ clips: [clip()], jobs: [job({ status: "canceled", cancelReason: "unlinked" })] }), [{ kind: "revive", jobId: 1, approved: false }]);
|
||||
});
|
||||
|
||||
it("publicado à mão (origin manual): fonte sem vínculo não cancela; corte rejeitado ainda cancela", () => {
|
||||
const manual = job({ status: "scheduled", origin: "manual" });
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "approved" })], jobs: [manual], targets: [] }), []);
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "rejected" })], jobs: [manual], targets: [] }),
|
||||
[{ kind: "cancel", jobId: 1, reason: "source_changed" }]);
|
||||
// Publicado nas redes escolhidas ⇒ marca o corte published no Clipador, mesmo sem vínculo.
|
||||
assert.deepEqual(plan({ clips: [clip({ status: "approved" })], jobs: [job({ status: "published", origin: "manual" })], targets: [] }),
|
||||
[{ kind: "mark_clip_published", clipId: 7 }]);
|
||||
});
|
||||
|
||||
it("link colado por você: aceita só vídeo da rede certa e tira o ID", () => {
|
||||
assert.deepEqual(parseVideoUrl("tiktok", " https://www.tiktok.com/@vortplay/video/7709179978520284437?is_from_webapp=1 "),
|
||||
{ url: "https://www.tiktok.com/@vortplay/video/7709179978520284437", remoteId: "7709179978520284437" });
|
||||
assert.equal(parseVideoUrl("tiktok", "https://www.tiktok.com/@vortplay"), null);
|
||||
assert.equal(parseVideoUrl("tiktok", "https://www.youtube.com/shorts/AbC123xyz"), null);
|
||||
assert.equal(parseVideoUrl("youtube", "https://youtu.be/AbC123xyz")?.remoteId, "AbC123xyz");
|
||||
assert.equal(parseVideoUrl("youtube", "https://www.youtube.com/watch?v=AbC123xyz")?.url, "https://www.youtube.com/shorts/AbC123xyz");
|
||||
assert.equal(parseVideoUrl("instagram", "https://www.instagram.com/reels/DAbC12_x/")?.remoteId, "DAbC12_x");
|
||||
assert.equal(parseVideoUrl("instagram", "javascript:alert(1)"), null);
|
||||
});
|
||||
|
||||
it("fonte de outro canal não gera job", () => {
|
||||
assert.deepEqual(plan({ clips: [clip({ channelId: "kick-y" })] }), []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("despachante: envio e resultado", () => {
|
||||
it("bloqueios em palavras", () => {
|
||||
assert.match(sendBlocker({ status: "connected", enabled: 1 }, true)!, /pausada/);
|
||||
assert.match(sendBlocker(null, false)!, /conecte/);
|
||||
assert.match(sendBlocker({ status: "connected", enabled: 0 }, false)!, /desligada/);
|
||||
assert.match(sendBlocker({ status: "needs_login", enabled: 1 }, false)!, /entrar de novo/);
|
||||
assert.equal(sendBlocker({ status: "connected", enabled: 1 }, false), null);
|
||||
});
|
||||
|
||||
it("nunca published sem ID/URL remota ou rascunho explícito", () => {
|
||||
assert.equal(readPublisherJob({ status: "done", remoteId: null, url: null, draft: false }).status, "failed");
|
||||
// Postou (a rede confirmou) mas sem link: pede o link, não manda conferir se saiu.
|
||||
const noLink = readPublisherJob({ status: "done", step: "Publicado no TikTok (Studio), mas o vídeo não apareceu na lista", url: null });
|
||||
assert.deepEqual([noLink.status, /Já saiu: informar o link/.test(noLink.error ?? "")], ["failed", true]);
|
||||
assert.equal(readPublisherJob({ status: "done", remoteId: "abc", url: null }).status, "published");
|
||||
assert.equal(readPublisherJob({ status: "done", url: "https://youtu.be/x" }).status, "published");
|
||||
const draft = readPublisherJob({ status: "done", draft: true });
|
||||
assert.equal(draft.status, "published");
|
||||
assert.equal(draft.draft, true);
|
||||
});
|
||||
|
||||
it("needs_login marca o perfil; running vira publishing com progresso", () => {
|
||||
const login = readPublisherJob({ status: "needs_login", error: null });
|
||||
assert.equal(login.status, "needs_login");
|
||||
assert.equal(login.networkNeedsLogin, true);
|
||||
const running = readPublisherJob({ status: "running", step: "Enviando vídeo…", progress: 0.4 });
|
||||
assert.deepEqual([running.status, running.step, running.progress], ["publishing", "Enviando vídeo…", 0.4]);
|
||||
});
|
||||
|
||||
it("hashtags da legenda viram tags", () => {
|
||||
assert.deepEqual(tagsFromCaption("Que jogada! #alanzoka #cortes #alanzoka via twitch.tv/alanzoka"), ["alanzoka", "cortes"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("envio: idempotência, reencaixe e confirmação", () => {
|
||||
it("clientRef = <id>:<attempts>", () => {
|
||||
assert.equal(clientRefFor(42, 0), "42:0");
|
||||
assert.equal(clientRefFor(42, 3), "42:3");
|
||||
});
|
||||
|
||||
it("só a agenda automática vencida há mais de 30 min é reencaixada", () => {
|
||||
const at = br("2026-11-17T12:00");
|
||||
const old = br("2026-11-17T11:00").toISOString();
|
||||
assert.equal(needsReflow({ scheduleSource: "auto", scheduledAt: old }, at), true);
|
||||
assert.equal(needsReflow({ scheduleSource: "auto", scheduledAt: br("2026-11-17T11:45").toISOString() }, at), false);
|
||||
assert.equal(needsReflow({ scheduleSource: "manual", scheduledAt: old }, at), false);
|
||||
assert.equal(needsReflow({ scheduleSource: "now", scheduledAt: old }, at), false);
|
||||
});
|
||||
|
||||
it("pode já estar na rede = falhou depois de chegar ao Publicador", () => {
|
||||
assert.equal(mayBeLive("failed", "pj-1"), true);
|
||||
assert.equal(mayBeLive("failed", null), false);
|
||||
assert.equal(mayBeLive("needs_login", "pj-1"), false);
|
||||
});
|
||||
|
||||
it("autorização vencida pede reconexão", () => {
|
||||
assert.match(sendBlocker({ status: "expired", enabled: 1 }, false)!, /venceu/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,423 @@
|
||||
// Regras puras da publicação (sem banco, sem rede): agendamento por horários bons + limite diário + espaçamento,
|
||||
// e as decisões do despachante (o que fazer com cada corte do Clipador, quando um job pode sair, como ler o
|
||||
// resultado do Publicador). Ficam separadas do I/O de lib/publishing.ts para serem testadas
|
||||
// (panel/src/lib/publishing-rules.test.ts).
|
||||
import type {
|
||||
AccountNetwork, AiLabel, ApprovalMode, Platform, PublishJobAction, PublishJobStatus, PublishTiming, SlotMap,
|
||||
} from "./types";
|
||||
|
||||
export const DEFAULT_TIMEZONE = "America/Sao_Paulo";
|
||||
export const DEFAULT_SLOTS: SlotMap = {
|
||||
youtube: ["12:00", "15:00", "19:00"],
|
||||
tiktok: ["08:00", "12:00", "19:00", "21:00"],
|
||||
instagram: ["12:00", "19:00", "21:00"],
|
||||
};
|
||||
/** Espaço mínimo entre dois vídeos do mesmo canal na mesma rede. */
|
||||
export const MIN_SPACING_MS = 60 * 60 * 1000;
|
||||
/** Até onde procurar um horário livre. */
|
||||
export const HORIZON_DAYS = 60;
|
||||
|
||||
export const HHMM_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
/** Estados em que o job ainda não foi entregue ao Publicador (pode ser cancelado sem falar com ele). */
|
||||
export const UNSENT: PublishJobStatus[] = ["awaiting_approval", "scheduled", "queued"];
|
||||
/** Estados que ocupam um lugar no dia da rede (contam para o limite diário e o espaçamento). */
|
||||
export const OCCUPYING: PublishJobStatus[] = ["scheduled", "queued", "publishing", "published"];
|
||||
|
||||
// ---------- fuso horário (sem biblioteca: Intl) ----------
|
||||
type Parts = { year: number; month: number; day: number; hour: number; minute: number; second: number };
|
||||
|
||||
const formatters = new Map<string, Intl.DateTimeFormat>();
|
||||
function formatter(timeZone: string): Intl.DateTimeFormat {
|
||||
let f = formatters.get(timeZone);
|
||||
if (!f) {
|
||||
f = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit",
|
||||
});
|
||||
formatters.set(timeZone, f);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
export function isValidTimezone(timeZone: string): boolean {
|
||||
try {
|
||||
formatter(timeZone);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function zonedParts(date: Date, timeZone: string): Parts {
|
||||
const out: Record<string, number> = {};
|
||||
for (const p of formatter(timeZone).formatToParts(date)) if (p.type !== "literal") out[p.type] = Number(p.value);
|
||||
return { year: out.year, month: out.month, day: out.day, hour: out.hour % 24, minute: out.minute, second: out.second };
|
||||
}
|
||||
|
||||
/** Diferença (ms) entre o relógio local do fuso e o UTC naquele instante (São Paulo = −3 h). */
|
||||
function offsetMs(date: Date, timeZone: string): number {
|
||||
const p = zonedParts(date, timeZone);
|
||||
const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
|
||||
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
|
||||
}
|
||||
|
||||
/** Dia local "YYYY-MM-DD" de um instante no fuso. */
|
||||
export function localDay(date: Date, timeZone: string): string {
|
||||
const p = zonedParts(date, timeZone);
|
||||
return `${p.year}-${String(p.month).padStart(2, "0")}-${String(p.day).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function addDays(day: string, n: number): string {
|
||||
const [y, m, d] = day.split("-").map(Number);
|
||||
return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Instante UTC de "dia HH:MM" no relógio do fuso (duas passadas: acerta a troca de horário de verão). */
|
||||
export function zonedTimeToUtc(day: string, hhmm: string, timeZone: string): Date {
|
||||
const [y, m, d] = day.split("-").map(Number);
|
||||
const [h, mi] = hhmm.split(":").map(Number);
|
||||
const guess = Date.UTC(y, m - 1, d, h, mi);
|
||||
let result = guess - offsetMs(new Date(guess), timeZone);
|
||||
const second = guess - offsetMs(new Date(result), timeZone);
|
||||
if (second !== result) result = second;
|
||||
return new Date(result);
|
||||
}
|
||||
|
||||
// ---------- agendamento ----------
|
||||
export type PlacementInput = {
|
||||
now: Date;
|
||||
timezone: string;
|
||||
/** Horários bons da rede ("HH:MM", qualquer ordem). */
|
||||
slots: string[];
|
||||
dailyLimit: number;
|
||||
/** Horários já ocupados no mesmo canal + rede (agendados, na fila, enviando, publicados). */
|
||||
occupied: Date[];
|
||||
spacingMs?: number;
|
||||
horizonDays?: number;
|
||||
};
|
||||
|
||||
function dayCount(occupied: Date[], day: string, timeZone: string): number {
|
||||
return occupied.filter((d) => localDay(d, timeZone) === day).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Próximo horário bom livre: depois de `now`, num dia com menos de `dailyLimit` vídeos e a pelo menos
|
||||
* `spacingMs` de qualquer outro vídeo do canal na rede. null se nada couber no horizonte (ou sem horários).
|
||||
*/
|
||||
export function nextFreeSlot(input: PlacementInput): Date | null {
|
||||
const { now, timezone, dailyLimit } = input;
|
||||
const spacing = input.spacingMs ?? MIN_SPACING_MS;
|
||||
const slots = [...new Set(input.slots.filter((s) => HHMM_RE.test(s)))].sort();
|
||||
if (slots.length === 0 || dailyLimit < 1) return null;
|
||||
const today = localDay(now, timezone);
|
||||
for (let i = 0; i <= (input.horizonDays ?? HORIZON_DAYS); i++) {
|
||||
const day = addDays(today, i);
|
||||
if (dayCount(input.occupied, day, timezone) >= dailyLimit) continue;
|
||||
for (const slot of slots) {
|
||||
const at = zonedTimeToUtc(day, slot, timezone);
|
||||
if (at.getTime() <= now.getTime()) continue;
|
||||
if (input.occupied.some((o) => Math.abs(o.getTime() - at.getTime()) < spacing)) continue;
|
||||
return at;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type Placement = { status: "queued" | "scheduled"; scheduledAt: Date } | { status: "none"; reason: string };
|
||||
|
||||
/**
|
||||
* Onde um job aprovado entra. `now` = na fila agora, se o limite do dia ainda deixa (passou do limite, vai para o
|
||||
* próximo horário bom). `best_slot` = próximo horário bom livre. `preferredAt` (horário escolhido à mão antes de
|
||||
* aprovar) vale se ainda estiver no futuro.
|
||||
*/
|
||||
export function placeJob(timing: PublishTiming, input: PlacementInput & { preferredAt?: Date | null }): Placement {
|
||||
if (input.preferredAt && input.preferredAt.getTime() > input.now.getTime()) {
|
||||
return { status: "scheduled", scheduledAt: input.preferredAt };
|
||||
}
|
||||
if (timing === "now" && dayCount(input.occupied, localDay(input.now, input.timezone), input.timezone) < input.dailyLimit) {
|
||||
return { status: "queued", scheduledAt: input.now };
|
||||
}
|
||||
const at = nextFreeSlot(input);
|
||||
if (!at) return { status: "none", reason: `Sem horário livre nos próximos ${input.horizonDays ?? HORIZON_DAYS} dias (confira os horários bons e o limite por dia).` };
|
||||
return { status: "scheduled", scheduledAt: at };
|
||||
}
|
||||
|
||||
// ---------- cortes do Clipador ----------
|
||||
export type ClipInfo = {
|
||||
id: number;
|
||||
/** candidate · discarded · pending · rendering · ready · approved · rejected · published · error */
|
||||
status: string;
|
||||
channelId: string | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type ClipTarget = {
|
||||
accountId: string;
|
||||
approvalMode: ApprovalMode;
|
||||
autoSince: string | null;
|
||||
/** Fontes ativas ligadas ao canal, com a data do vínculo. */
|
||||
channels: { channelId: string; linkedAt: string }[];
|
||||
/** Redes do canal que recebem vídeos (ligadas e já conectadas alguma vez). */
|
||||
platforms: Platform[];
|
||||
};
|
||||
|
||||
export type ExistingJob = {
|
||||
id: number;
|
||||
accountId: string;
|
||||
platform: Platform;
|
||||
sourceId: string;
|
||||
status: PublishJobStatus;
|
||||
cancelReason: string | null;
|
||||
publisherJobId: string | null;
|
||||
/** 'manual' = publicado à mão pelo cartão do corte: não depende da fonte estar ligada ao canal. */
|
||||
origin?: "link" | "manual";
|
||||
};
|
||||
|
||||
export type ClipAction =
|
||||
| { kind: "create"; clipId: number; accountId: string; platform: Platform; approved: boolean }
|
||||
| { kind: "approve"; jobId: number }
|
||||
| { kind: "revive"; jobId: number; approved: boolean }
|
||||
| { kind: "cancel"; jobId: number; reason: "source_changed" | "unlinked" }
|
||||
| { kind: "approve_clip"; clipId: number }
|
||||
| { kind: "forget_auto"; clipId: number }
|
||||
| { kind: "mark_clip_published"; clipId: number };
|
||||
|
||||
const PUBLISHABLE = new Set(["ready", "approved"]);
|
||||
/** Estados do corte em que os jobs não enviados continuam válidos. */
|
||||
const KEEPS_JOBS = new Set(["ready", "approved", "published"]);
|
||||
|
||||
/**
|
||||
* Decide o que fazer em um ciclo, dado o que o Clipador mostra agora:
|
||||
* - `ready` + canal automático (corte criado depois do vínculo e de ligar o automático) ⇒ aprova no Clipador e cria jobs aprovados;
|
||||
* - `ready` + canal manual ⇒ job `awaiting_approval`;
|
||||
* - `approved` por humano (não está em `autoApproved`) ⇒ jobs aguardando viram aprovados;
|
||||
* - fonte desligada do canal ⇒ cancela os não enviados (menos os publicados à mão: `origin = 'manual'`);
|
||||
* - corte que voltou para `pending` (editado/exportado), rejeitado, com erro ou apagado ⇒ cancela os não enviados
|
||||
* (e um job cancelado assim renasce quando o corte fica pronto de novo);
|
||||
* - todos os jobs (não cancelados) publicados ⇒ marca o corte `published` no Clipador.
|
||||
*
|
||||
* `clips` deve conter os cortes publicáveis das fontes ligadas E os cortes que têm jobs (para conferir o estado);
|
||||
* `complete` = a consulta por ids deu certo (só então "sumiu" quer dizer "apagado").
|
||||
*/
|
||||
export function planClipSync(input: {
|
||||
clips: ClipInfo[];
|
||||
complete: boolean;
|
||||
autoApproved: Set<number>;
|
||||
targets: ClipTarget[];
|
||||
jobs: ExistingJob[];
|
||||
}): ClipAction[] {
|
||||
const actions: ClipAction[] = [];
|
||||
const byId = new Map(input.clips.map((c) => [c.id, c]));
|
||||
const jobKey = (accountId: string, platform: string, clipId: number) => `${accountId}|${platform}|${clipId}`;
|
||||
const jobs = new Map(input.jobs.map((j) => [jobKey(j.accountId, j.platform, Number(j.sourceId)), j]));
|
||||
const approveClip = new Set<number>();
|
||||
|
||||
// 1) Jobs não enviados de cortes que não estão mais publicáveis, ou cuja fonte foi desligada do canal.
|
||||
const linked = (accountId: string, channelId: string | null) =>
|
||||
!!channelId && input.targets.some((t) => t.accountId === accountId && t.channels.some((c) => c.channelId === channelId));
|
||||
for (const job of input.jobs) {
|
||||
if (!UNSENT.includes(job.status) || job.publisherJobId) continue;
|
||||
const clip = byId.get(Number(job.sourceId));
|
||||
if (!clip && !input.complete) continue;
|
||||
if (!clip || !KEEPS_JOBS.has(clip.status)) actions.push({ kind: "cancel", jobId: job.id, reason: "source_changed" });
|
||||
else if (job.origin !== "manual" && !linked(job.accountId, clip.channelId)) actions.push({ kind: "cancel", jobId: job.id, reason: "unlinked" });
|
||||
}
|
||||
|
||||
// 2) Cortes publicáveis × canais ligados à fonte × redes.
|
||||
for (const clip of input.clips) {
|
||||
if (input.autoApproved.has(clip.id) && clip.status !== "approved" && clip.status !== "published") {
|
||||
actions.push({ kind: "forget_auto", clipId: clip.id });
|
||||
}
|
||||
if (!PUBLISHABLE.has(clip.status) || !clip.channelId) continue;
|
||||
const humanApproved = clip.status === "approved" && !input.autoApproved.has(clip.id);
|
||||
for (const target of input.targets) {
|
||||
const link = target.channels.find((c) => c.channelId === clip.channelId);
|
||||
if (!link) continue;
|
||||
const created = Date.parse(clip.createdAt);
|
||||
const autoOk = target.approvalMode === "auto" && created >= Date.parse(link.linkedAt)
|
||||
&& (!target.autoSince || created >= Date.parse(target.autoSince));
|
||||
const approved = humanApproved || autoOk;
|
||||
for (const platform of target.platforms) {
|
||||
const job = jobs.get(jobKey(target.accountId, platform, clip.id));
|
||||
let touched = false;
|
||||
if (!job) {
|
||||
actions.push({ kind: "create", clipId: clip.id, accountId: target.accountId, platform, approved });
|
||||
touched = true;
|
||||
} else if (job.status === "awaiting_approval" && approved) {
|
||||
actions.push({ kind: "approve", jobId: job.id });
|
||||
touched = true;
|
||||
} else if (job.status === "canceled" && (job.cancelReason === "source_changed" || job.cancelReason === "unlinked")) {
|
||||
actions.push({ kind: "revive", jobId: job.id, approved });
|
||||
touched = true;
|
||||
}
|
||||
if (touched && autoOk && clip.status === "ready") approveClip.add(clip.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const clipId of approveClip) actions.push({ kind: "approve_clip", clipId });
|
||||
|
||||
// 3) Corte com todos os jobs publicados ⇒ `published` no Clipador.
|
||||
const perClip = new Map<number, ExistingJob[]>();
|
||||
for (const job of input.jobs) {
|
||||
const id = Number(job.sourceId);
|
||||
perClip.set(id, [...(perClip.get(id) ?? []), job]);
|
||||
}
|
||||
for (const [clipId, list] of perClip) {
|
||||
const clip = byId.get(clipId);
|
||||
if (!clip || !PUBLISHABLE.has(clip.status)) continue;
|
||||
const live = list.filter((j) => j.status !== "canceled");
|
||||
if (live.length > 0 && live.every((j) => j.status === "published")) actions.push({ kind: "mark_clip_published", clipId });
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
// ---------- envio ----------
|
||||
/** O job aprovado já pode sair? (`queued`, ou `scheduled` com horário vencido) */
|
||||
export function isDue(job: { status: PublishJobStatus; scheduledAt: string | null }, now: Date): boolean {
|
||||
if (job.status === "queued") return true;
|
||||
return job.status === "scheduled" && !!job.scheduledAt && new Date(job.scheduledAt).getTime() <= now.getTime();
|
||||
}
|
||||
|
||||
/** Agendado pelo despachante e vencido há mais disso (painel fechado): é reencaixado na agenda, não disparado em rajada. */
|
||||
export const STALE_AFTER_MS = 30 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* O horário automático deste job ficou para trás (painel fechado, rede esperando conexão…)? Então ele volta para
|
||||
* o próximo horário bom livre (limite do dia + 1 h). "Publicar agora", "Tentar de novo" e horário escolhido à mão
|
||||
* não são reencaixados.
|
||||
*/
|
||||
export function needsReflow(job: { scheduleSource: "auto" | "manual" | "now"; scheduledAt: string | null }, now: Date): boolean {
|
||||
if (job.scheduleSource !== "auto" || !job.scheduledAt) return false;
|
||||
return now.getTime() - new Date(job.scheduledAt).getTime() > STALE_AFTER_MS;
|
||||
}
|
||||
|
||||
/** Referência idempotente do envio: o Publicador devolve o job existente se ela se repetir (reenvio após timeout é seguro). */
|
||||
export const clientRefFor = (jobId: number, attempts: number) => `${jobId}:${attempts}`;
|
||||
|
||||
/** Pode já estar na rede: o último envio chegou ao Publicador e terminou em falha. */
|
||||
export const mayBeLive = (status: PublishJobStatus, publisherJobId: string | null) => status === "failed" && !!publisherJobId;
|
||||
|
||||
/** Por que um job vencido não pode sair agora (texto para `step`), ou null se pode. */
|
||||
export function sendBlocker(network: Pick<AccountNetwork, "status" | "enabled"> | null | undefined, paused: boolean): string | null {
|
||||
if (paused) return "Esperando: a publicação está pausada em Configurações.";
|
||||
if (!network || network.status === "disconnected") return "Esperando: conecte esta rede em Canais de publicação.";
|
||||
if (!network.enabled) return "Esperando: esta rede está desligada neste canal.";
|
||||
if (network.status === "needs_login") return "Esperando: é preciso entrar de novo nesta rede.";
|
||||
if (network.status === "expired") return "Esperando: a autorização desta rede venceu — conecte de novo em Canais de publicação.";
|
||||
if (network.status === "connecting") return "Esperando: a conexão com a rede ainda não terminou.";
|
||||
if (network.status === "error") return "Esperando: a conexão com a rede deu erro. Confira em Canais de publicação.";
|
||||
return null;
|
||||
}
|
||||
|
||||
export type JobUpdate = {
|
||||
status: PublishJobStatus;
|
||||
step: string;
|
||||
progress: number;
|
||||
remoteId: string | null;
|
||||
url: string | null;
|
||||
draft: boolean;
|
||||
error: string | null;
|
||||
/** O perfil precisa de login de novo (vira `needs_login` também em account_networks). */
|
||||
networkNeedsLogin: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Lê o job do Publicador. Regra de honestidade: só vira `published` com ID ou URL remota confirmada,
|
||||
* ou com `draft: true` explícito (foi para rascunho/inbox). "Terminou" sem confirmação vira `failed`
|
||||
* com aviso para conferir na rede antes de tentar de novo (evita vídeo duplicado).
|
||||
*/
|
||||
export function readPublisherJob(job: {
|
||||
status: string; step?: string | null; progress?: number | null; remoteId?: string | null; url?: string | null; draft?: boolean | null; error?: string | null;
|
||||
}): JobUpdate {
|
||||
const base = {
|
||||
step: String(job.step ?? ""), progress: Math.max(0, Math.min(1, Number(job.progress ?? 0))),
|
||||
remoteId: job.remoteId || null, url: job.url || null, draft: job.draft === true, error: job.error ?? null, networkNeedsLogin: false,
|
||||
};
|
||||
switch (job.status) {
|
||||
case "queued":
|
||||
case "running":
|
||||
return { ...base, status: "publishing", error: null };
|
||||
case "done":
|
||||
if (base.remoteId || base.url || base.draft) return { ...base, status: "published", progress: 1, error: null };
|
||||
// O modo sessão diz "Publicado no …" quando a rede confirmou o post e só o link não veio: não pedir para conferir
|
||||
// se saiu — pedir o link (e nunca sugerir "Tentar de novo", que postaria de novo).
|
||||
return {
|
||||
...base, status: "failed",
|
||||
error: /^Publicado no /.test(base.step)
|
||||
? "Saiu na rede, mas o link do vídeo não apareceu a tempo. Copie o link do vídeo na rede e use “Já saiu: informar o link” (não use “Tentar de novo”: publicaria duas vezes)."
|
||||
: "O Publicador terminou, mas não confirmou o link do vídeo. Confira na rede se ele saiu antes de tentar de novo (para não publicar duas vezes).",
|
||||
};
|
||||
case "needs_login":
|
||||
return { ...base, status: "needs_login", networkNeedsLogin: true, error: base.error ?? "A rede pediu login de novo." };
|
||||
case "canceled":
|
||||
return { ...base, status: "canceled" };
|
||||
default:
|
||||
return { ...base, status: "failed", error: base.error ?? "O envio falhou sem mensagem do Publicador." };
|
||||
}
|
||||
}
|
||||
|
||||
/** Ações que a UI pode oferecer para um job, pelo estado. */
|
||||
export function jobActions(status: PublishJobStatus, sent: boolean): PublishJobAction[] {
|
||||
switch (status) {
|
||||
case "awaiting_approval": return ["approve", "publish-now", "reschedule", "edit", "cancel"];
|
||||
case "scheduled": return ["publish-now", "reschedule", "edit", "cancel"];
|
||||
case "queued": return sent ? ["cancel"] : ["reschedule", "edit", "cancel"];
|
||||
case "publishing": return sent ? ["cancel"] : [];
|
||||
case "failed": return ["retry", "mark-published", "edit", "cancel"];
|
||||
case "needs_login": return ["relogin", "retry", "mark-published", "cancel"];
|
||||
case "canceled": return ["retry"];
|
||||
case "published": return ["removed"];
|
||||
default: return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Link de um vídeo publicado, colado por você ("Já saiu: informar o link"). Confere que é da rede certa e tira o ID.
|
||||
* TikTok: tiktok.com/@conta/video/<id> · YouTube: youtube.com/shorts/<id>, watch?v=<id> ou youtu.be/<id> ·
|
||||
* Instagram: instagram.com/reel(s)/<código> ou /p/<código>. null = não é um link de vídeo dessa rede.
|
||||
*/
|
||||
export function parseVideoUrl(platform: Platform, raw: string): { url: string; remoteId: string } | null {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw.trim());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
||||
const host = parsed.hostname.toLowerCase().replace(/^(www\.|m\.)/, "");
|
||||
const path = parsed.pathname;
|
||||
if (platform === "tiktok" && host === "tiktok.com") {
|
||||
const m = /^\/@([\w.-]+)\/video\/(\d+)/.exec(path);
|
||||
return m ? { url: `https://www.tiktok.com/@${m[1]}/video/${m[2]}`, remoteId: m[2] } : null;
|
||||
}
|
||||
if (platform === "youtube") {
|
||||
const id = host === "youtu.be" ? path.slice(1).split("/")[0]
|
||||
: host === "youtube.com" ? (/^\/shorts\/([\w-]+)/.exec(path)?.[1] ?? (path === "/watch" ? parsed.searchParams.get("v") : null))
|
||||
: null;
|
||||
return id && /^[\w-]{6,20}$/.test(id) ? { url: `https://www.youtube.com/shorts/${id}`, remoteId: id } : null;
|
||||
}
|
||||
if (platform === "instagram" && host === "instagram.com") {
|
||||
const m = /^\/(?:[\w.]+\/)?(?:reels?|p)\/([\w-]+)/.exec(path);
|
||||
return m ? { url: `https://www.instagram.com/reel/${m[1]}/`, remoteId: m[1] } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Rótulo de IA: always/never pelo canal; auto = só quando o vídeo usa voz de personagem (RVC) ou clonada. */
|
||||
export function aiGeneratedFor(label: AiLabel, usesPersonaVoice: boolean): boolean {
|
||||
return label === "always" ? true : label === "never" ? false : usesPersonaVoice;
|
||||
}
|
||||
|
||||
/** Hashtags da legenda viram tags (sem #, sem repetir, até 15). */
|
||||
export function tagsFromCaption(caption: string): string[] {
|
||||
const tags = [...caption.matchAll(/#([\p{L}\p{N}_]{2,50})/gu)].map((m) => m[1]);
|
||||
return [...new Set(tags)].slice(0, 15);
|
||||
}
|
||||
|
||||
/** Normaliza horários bons: "HH:MM" válidos, sem repetir, em ordem (máx. 12 por rede). */
|
||||
export function normalizeSlots(list: unknown): string[] | null {
|
||||
if (!Array.isArray(list)) return null;
|
||||
const clean = list.map((s) => String(s).trim());
|
||||
if (clean.some((s) => !HHMM_RE.test(s))) return null;
|
||||
return [...new Set(clean)].sort().slice(0, 12);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
// Render de episódio pelo painel: chama o MESMO lançador da linha de comando
|
||||
// (scripts/cli.ts render), que valida, renderiza, converte, verifica e escreve report.json.
|
||||
// Um render por vez (o lançador também tem trava própria).
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, get, now, run } from "./db";
|
||||
import { DATA_DIR, REPO_ROOT } from "./paths";
|
||||
import { killTree, lineSplitter } from "./proc";
|
||||
import { UserError, getEpisodeById, touchStory } from "./stories";
|
||||
import type { RenderJob } from "./types";
|
||||
|
||||
const g = globalThis as unknown as { __cenaforgeRenders?: Map<number, ChildProcess> };
|
||||
const active = (g.__cenaforgeRenders ??= new Map());
|
||||
|
||||
export function listRenders(episodeId: number): RenderJob[] {
|
||||
return all<RenderJob>("SELECT * FROM renders WHERE episode_id = ? ORDER BY id DESC", episodeId);
|
||||
}
|
||||
|
||||
export function getRender(id: number): RenderJob | undefined {
|
||||
return get<RenderJob>("SELECT * FROM renders WHERE id = ?", id);
|
||||
}
|
||||
|
||||
export function startRender(episodeId: number, profile: "preview" | "final"): RenderJob {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Episódio não encontrado.");
|
||||
if (!ep.hasConfig) throw new UserError(`A cena ${ep.configPath} ainda não existe. Monte a cena antes de renderizar.`);
|
||||
if (active.size > 0) throw new UserError("Já existe um render em andamento. Aguarde terminar.");
|
||||
const tsxCli = path.join(REPO_ROOT, "node_modules", "tsx", "dist", "cli.mjs");
|
||||
if (!fs.existsSync(tsxCli)) throw new UserError("tsx não encontrado; rode pnpm install na raiz do projeto.");
|
||||
|
||||
const logDir = path.join(DATA_DIR, "logs", "renders");
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
const info = run(`INSERT INTO renders (episode_id, config_path, profile, status, started_at) VALUES (?, ?, ?, 'running', ?)`,
|
||||
episodeId, ep.configPath, profile, now());
|
||||
const id = Number(info.lastInsertRowid);
|
||||
const logPath = path.join(logDir, `${id}.log`);
|
||||
run("UPDATE renders SET log_path = ? WHERE id = ?", path.relative(REPO_ROOT, logPath).split(path.sep).join("/"), id);
|
||||
const log = fs.createWriteStream(logPath);
|
||||
|
||||
const child = spawn(process.execPath, [tsxCli, "scripts/cli.ts", "render", "--config", ep.configPath, "--profile", profile], {
|
||||
cwd: REPO_ROOT, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
active.set(id, child);
|
||||
let runDir: string | null = null;
|
||||
const onLine = lineSplitter((line) => {
|
||||
log.write(line + "\n");
|
||||
const m = /-> (output\/runs\/\S+)/.exec(line);
|
||||
if (m && !runDir) {
|
||||
runDir = m[1];
|
||||
run("UPDATE renders SET run_dir = ? WHERE id = ?", runDir, id);
|
||||
}
|
||||
});
|
||||
child.stdout.setEncoding("utf8").on("data", onLine);
|
||||
child.stderr.setEncoding("utf8").on("data", onLine);
|
||||
child.on("error", (error) => finish(id, "failed", `não iniciou: ${error.message}`));
|
||||
child.on("close", (code) => {
|
||||
log.end();
|
||||
active.delete(id);
|
||||
if (getRender(id)?.status !== "running") return;
|
||||
// O report.json do lançador é a fonte da verdade sobre o resultado.
|
||||
const report = runDir ? readReport(runDir) : null;
|
||||
if (report?.status === "success" && code === 0) {
|
||||
run("UPDATE renders SET status = 'success', mp4 = ?, finished_at = ? WHERE id = ?", report.mp4 ?? null, now(), id);
|
||||
} else {
|
||||
finish(id, report?.status === "cancelled" ? "cancelled" : "failed", report?.error ?? `lançador saiu com código ${code}`);
|
||||
}
|
||||
touchStory(ep.story_id);
|
||||
});
|
||||
return getRender(id)!;
|
||||
}
|
||||
|
||||
export function cancelRender(id: number): void {
|
||||
const child = active.get(id);
|
||||
if (!child) throw new UserError("Este render não está em andamento.");
|
||||
finish(id, "cancelled", "cancelado pelo painel");
|
||||
killTree(child);
|
||||
}
|
||||
|
||||
function finish(id: number, status: string, error: string): void {
|
||||
run("UPDATE renders SET status = ?, error = ?, finished_at = ? WHERE id = ? AND status = 'running'", status, error.slice(0, 2000), now(), id);
|
||||
}
|
||||
|
||||
function readReport(runDir: string): { status?: string; mp4?: string; error?: string } | null {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(REPO_ROOT, runDir, "report.json"), "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Biblioteca de cenas do Godot (godot/library/<id>/manifest.json + template.gd). Cada cena nova
|
||||
// que um agente constrói (doc/godot/cenas.md) aparece aqui sozinha: no formulário da montagem e
|
||||
// na escolha automática (pelas palavras-chave do manifesto). Sem banco: lê os arquivos.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { REPO_ROOT } from "./paths";
|
||||
|
||||
export type LibraryParam = {
|
||||
name: string; label: string; type: "select" | "bool" | "number" | "text";
|
||||
default?: unknown; options?: { value: string; label: string; keywords?: string[] }[];
|
||||
};
|
||||
export type LibraryScene = {
|
||||
id: string; kind: "doc3d" | "doc2d"; label: string; description: string; keywords: string[];
|
||||
params: LibraryParam[]; createdBy?: string; createdAt?: string;
|
||||
};
|
||||
|
||||
export const LIBRARY_DIR = path.join(REPO_ROOT, "godot", "library");
|
||||
const ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
|
||||
|
||||
/** Cenas válidas da biblioteca (pasta com template.gd e manifest.json legível). */
|
||||
export function listLibrary(): LibraryScene[] {
|
||||
let dirs: string[] = [];
|
||||
try {
|
||||
dirs = fs.readdirSync(LIBRARY_DIR, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: LibraryScene[] = [];
|
||||
for (const id of dirs.sort()) {
|
||||
if (!ID_RE.test(id) || !fs.existsSync(path.join(LIBRARY_DIR, id, "template.gd"))) continue;
|
||||
try {
|
||||
const m = JSON.parse(fs.readFileSync(path.join(LIBRARY_DIR, id, "manifest.json"), "utf8")) as Partial<LibraryScene>;
|
||||
out.push({
|
||||
id, kind: m.kind === "doc2d" ? "doc2d" : "doc3d",
|
||||
label: String(m.label ?? id), description: String(m.description ?? ""),
|
||||
keywords: Array.isArray(m.keywords) ? m.keywords.map(String) : [],
|
||||
params: Array.isArray(m.params) ? (m.params as LibraryParam[]).filter((p) => p && typeof p.name === "string") : [],
|
||||
createdBy: m.createdBy, createdAt: m.createdAt,
|
||||
});
|
||||
} catch { /* manifesto ilegível: a cena não aparece até ser corrigida */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const norm = (s: string) => s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
|
||||
|
||||
function hits(text: string, keywords: string[] = []): number {
|
||||
const t = norm(text);
|
||||
return keywords.filter((k) => k && t.includes(norm(k))).length;
|
||||
}
|
||||
|
||||
/** Parâmetros padrão do manifesto, com cada `select` escolhido pelas palavras do texto. */
|
||||
export function paramsFor(scene: LibraryScene, text: string): Record<string, unknown> {
|
||||
const params: Record<string, unknown> = {};
|
||||
for (const p of scene.params) {
|
||||
if (p.type === "select" && p.options?.length) {
|
||||
const best = p.options.map((o) => ({ o, n: hits(text, o.keywords) })).sort((a, b) => b.n - a.n)[0];
|
||||
params[p.name] = best.n > 0 ? best.o.value : p.default ?? p.options[0].value;
|
||||
} else if (p.default !== undefined) {
|
||||
params[p.name] = p.default;
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/** A cena 3D da biblioteca que mais combina com o texto (pelo menos uma palavra-chave), ou null. */
|
||||
export function matchLibrary(text: string, library: LibraryScene[]): { scene: LibraryScene; score: number } | null {
|
||||
const ranked = library.filter((s) => s.kind === "doc3d").map((scene) => ({ scene, score: hits(text, scene.keywords) }))
|
||||
.filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
|
||||
return ranked[0] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// Leitura estruturada do roteiro (.md) para exibir no painel. Entende o subconjunto de markdown
|
||||
// que os guias de doc/roteiro/ pedem: título, linha de metadados, seções "##", parágrafos,
|
||||
// listas, tabelas, blocos de código e citações. A tabela cuja primeira coluna é "t (s)" vira a
|
||||
// lista de trechos do vídeo (tempo, imagem, texto na tela, narração).
|
||||
// Sem dependência de servidor: pode ser usado em componente cliente.
|
||||
|
||||
export type Block =
|
||||
| { type: "paragraph"; text: string }
|
||||
| { type: "list"; ordered: boolean; items: string[] }
|
||||
| { type: "table"; header: string[]; rows: string[][] }
|
||||
| { type: "code"; lang: string; text: string }
|
||||
| { type: "quote"; text: string }
|
||||
| { type: "heading"; level: number; text: string };
|
||||
|
||||
/** O que cada seção representa (pelo título); "other" é exibida como texto comum. */
|
||||
export type SectionRole = "hook" | "shots" | "sources" | "needs" | "cover" | "overlay" | "summary" | "ending" | "consequences" | "other";
|
||||
|
||||
export type ScriptSection = { title: string; role: SectionRole; blocks: Block[] };
|
||||
|
||||
export type Shot = {
|
||||
index: number;
|
||||
/** Segundos; null quando a célula de tempo não tem número. */
|
||||
start: number | null;
|
||||
end: number | null;
|
||||
time: string;
|
||||
visual: string;
|
||||
onScreen: string;
|
||||
narration: string;
|
||||
};
|
||||
|
||||
export type ScriptDoc = {
|
||||
title: string | null;
|
||||
/** Linhas entre o título e a primeira seção (ex.: "Duração alvo: 72 s · Formato: documental"). */
|
||||
meta: string[];
|
||||
/** Pares "chave: valor" extraídos das linhas de metadados. */
|
||||
facts: { label: string; value: string }[];
|
||||
sections: ScriptSection[];
|
||||
shots: Shot[];
|
||||
/** Duração alvo declarada no roteiro, em segundos. */
|
||||
targetSeconds: number | null;
|
||||
narrationWords: number;
|
||||
};
|
||||
|
||||
/** Ritmo de narração usado nos guias (doc/roteiro/comum.md). */
|
||||
export const WORDS_PER_SECOND = 2.5;
|
||||
|
||||
const ROLE_RULES: [RegExp, SectionRole][] = [
|
||||
[/gancho/i, "hook"],
|
||||
[/cena a cena|roteiro cena|trechos/i, "shots"],
|
||||
[/fontes?/i, "sources"],
|
||||
[/necessidades/i, "needs"],
|
||||
[/campos de overlay/i, "overlay"],
|
||||
[/capa|overlay/i, "cover"],
|
||||
[/resumo/i, "summary"],
|
||||
[/chamada final|gancho para o pr/i, "ending"],
|
||||
[/consequ/i, "consequences"],
|
||||
];
|
||||
|
||||
function roleOf(title: string): SectionRole {
|
||||
return ROLE_RULES.find(([re]) => re.test(title))?.[1] ?? "other";
|
||||
}
|
||||
|
||||
const splitRow = (line: string) => line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
|
||||
const isTableSeparator = (line: string) => /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(line);
|
||||
|
||||
/** Blocos de um trecho de markdown (sem os títulos "#"/"##", já separados antes). */
|
||||
export function parseBlocks(lines: string[]): Block[] {
|
||||
const blocks: Block[] = [];
|
||||
let i = 0;
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
if (!line.trim()) { i++; continue; }
|
||||
const fence = /^\s*```(\w*)/.exec(line);
|
||||
if (fence) {
|
||||
const body: string[] = [];
|
||||
for (i++; i < lines.length && !/^\s*```/.test(lines[i]); i++) body.push(lines[i]);
|
||||
blocks.push({ type: "code", lang: fence[1], text: body.join("\n") });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const heading = /^(#{3,6})\s+(.*)$/.exec(line);
|
||||
if (heading) { blocks.push({ type: "heading", level: heading[1].length, text: heading[2].trim() }); i++; continue; }
|
||||
if (line.trim().startsWith("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
|
||||
const header = splitRow(line);
|
||||
const rows: string[][] = [];
|
||||
for (i += 2; i < lines.length && lines[i].trim().startsWith("|"); i++) rows.push(splitRow(lines[i]));
|
||||
blocks.push({ type: "table", header, rows });
|
||||
continue;
|
||||
}
|
||||
if (/^\s*>/.test(line)) {
|
||||
const body: string[] = [];
|
||||
for (; i < lines.length && /^\s*>/.test(lines[i]); i++) body.push(lines[i].replace(/^\s*>\s?/, ""));
|
||||
blocks.push({ type: "quote", text: body.join(" ") });
|
||||
continue;
|
||||
}
|
||||
const bullet = /^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/.exec(line);
|
||||
if (bullet) {
|
||||
const ordered = bullet[1] !== undefined;
|
||||
const items: string[] = [];
|
||||
while (i < lines.length) {
|
||||
const m = /^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/.exec(lines[i]);
|
||||
if (m) { items.push(m[2]); i++; continue; }
|
||||
// Continuação do item (linha recuada, sem marcador).
|
||||
if (lines[i].trim() && /^\s{2,}/.test(lines[i]) && items.length) { items[items.length - 1] += ` ${lines[i].trim()}`; i++; continue; }
|
||||
break;
|
||||
}
|
||||
blocks.push({ type: "list", ordered, items });
|
||||
continue;
|
||||
}
|
||||
const body: string[] = [];
|
||||
for (; i < lines.length && lines[i].trim() && !/^\s*(```|\||>|#{3,6}\s|[-*+]\s|\d+[.)]\s)/.test(lines[i]); i++) body.push(lines[i].trim());
|
||||
if (body.length === 0) { body.push(line.trim()); i++; }
|
||||
blocks.push({ type: "paragraph", text: body.join(" ") });
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function parseTime(cell: string): { start: number | null; end: number | null } {
|
||||
const nums = (cell.match(/\d+(?:[.,]\d+)?/g) ?? []).map((n) => Number(n.replace(",", ".")));
|
||||
if (nums.length === 0) return { start: null, end: null };
|
||||
return { start: nums[0], end: nums.length > 1 ? nums[1] : null };
|
||||
}
|
||||
|
||||
/** Trechos: a primeira tabela cuja primeira coluna é o tempo ("t (s)"). */
|
||||
function extractShots(sections: ScriptSection[]): Shot[] {
|
||||
for (const section of sections) {
|
||||
for (const block of section.blocks) {
|
||||
if (block.type !== "table" || !/^t\b|tempo/i.test(block.header[0] ?? "")) continue;
|
||||
const col = (re: RegExp) => block.header.findIndex((h) => re.test(h));
|
||||
const visual = col(/imagem|b-?roll|visual/i);
|
||||
const onScreen = col(/texto na tela|tela/i);
|
||||
const narration = col(/narra|di[aá]logo|fala/i);
|
||||
return block.rows.map((row, index) => ({
|
||||
index,
|
||||
...parseTime(row[0] ?? ""),
|
||||
time: row[0] ?? "",
|
||||
visual: visual >= 0 ? row[visual] ?? "" : "",
|
||||
onScreen: onScreen >= 0 ? row[onScreen] ?? "" : "",
|
||||
narration: narration >= 0 ? row[narration] ?? "" : "",
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export const countWords = (text: string) => (text.replace(/[*_`"“”]/g, " ").match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu) ?? []).length;
|
||||
|
||||
export function parseScript(markdown: string): ScriptDoc {
|
||||
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
|
||||
let title: string | null = null;
|
||||
const meta: string[] = [];
|
||||
const sections: ScriptSection[] = [];
|
||||
let current: { title: string; lines: string[] } | null = null;
|
||||
const flush = () => {
|
||||
if (current) sections.push({ title: current.title, role: roleOf(current.title), blocks: parseBlocks(current.lines) });
|
||||
};
|
||||
for (const line of lines) {
|
||||
const h1 = /^#\s+(.*)$/.exec(line);
|
||||
const h2 = /^##\s+(.*)$/.exec(line);
|
||||
if (h1 && title === null && !current) { title = h1[1].trim(); continue; }
|
||||
if (h2) { flush(); current = { title: h2[1].trim(), lines: [] }; continue; }
|
||||
if (current) current.lines.push(line);
|
||||
else if (line.trim()) meta.push(line.trim());
|
||||
}
|
||||
flush();
|
||||
|
||||
const facts = meta.flatMap((line) => line.split(/\s+·\s+/))
|
||||
.map((part) => /^([^:]{2,40}):\s*(.+)$/.exec(part))
|
||||
.filter((m): m is RegExpExecArray => m !== null)
|
||||
.map((m) => ({ label: m[1].trim(), value: m[2].trim() }));
|
||||
const target = facts.find((f) => /dura[cç][aã]o/i.test(f.label));
|
||||
const targetSeconds = target ? Number((/\d+/.exec(target.value) ?? [""])[0]) || null : null;
|
||||
const shots = extractShots(sections);
|
||||
const narrationWords = shots.reduce((sum, s) => sum + countWords(s.narration), 0);
|
||||
return { title, meta, facts, sections, shots, targetSeconds, narrationWords };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Configurações gerais do painel (tabela app_settings, chave → valor em texto). Hoje: publicação pausada,
|
||||
// horários bons por rede, fuso e de quanto em quanto tempo ler os números dos posts. Valores ausentes ou estragados voltam ao padrão (nunca derrubam o despachante).
|
||||
import { all, db, run } from "./db";
|
||||
import { DEFAULT_SLOTS, DEFAULT_TIMEZONE, isValidTimezone, normalizeSlots } from "./publishing-rules";
|
||||
import { UserError } from "./stories";
|
||||
import { PLATFORMS, type AppSettings, type SlotMap } from "./types";
|
||||
|
||||
/** Intervalos oferecidos para ler os números dos posts sozinho (0 = só pelo botão do dashboard). */
|
||||
export const METRICS_EVERY_HOURS = [0, 3, 6, 12, 24] as const;
|
||||
const DEFAULT_METRICS_EVERY_HOURS = 6;
|
||||
|
||||
function readRaw(): Record<string, string> {
|
||||
return Object.fromEntries(all<{ key: string; value: string }>("SELECT key, value FROM app_settings").map((r) => [r.key, r.value]));
|
||||
}
|
||||
|
||||
function parseSlots(raw: string | undefined): SlotMap {
|
||||
const slots: SlotMap = { ...DEFAULT_SLOTS };
|
||||
if (!raw) return slots;
|
||||
try {
|
||||
const data = JSON.parse(raw) as Record<string, unknown>;
|
||||
for (const p of PLATFORMS) {
|
||||
const list = normalizeSlots(data[p]);
|
||||
if (list) slots[p] = list;
|
||||
}
|
||||
} catch { /* JSON estragado: fica o padrão */ }
|
||||
return slots;
|
||||
}
|
||||
|
||||
export function getSettings(): AppSettings {
|
||||
const raw = readRaw();
|
||||
const timezone = raw.timezone && isValidTimezone(raw.timezone) ? raw.timezone : DEFAULT_TIMEZONE;
|
||||
const every = Number(raw.metrics_every_hours);
|
||||
const metricsEveryHours = (METRICS_EVERY_HOURS as readonly number[]).includes(every) && raw.metrics_every_hours !== undefined
|
||||
? every : DEFAULT_METRICS_EVERY_HOURS;
|
||||
return { publishingPaused: raw.publishing_paused === "1", slots: parseSlots(raw.slots), timezone, metricsEveryHours };
|
||||
}
|
||||
|
||||
/** Atualiza só o que veio: {publishingPaused?, slots?: {youtube?: ["12:00", ...]}, timezone?}. */
|
||||
export function updateSettings(input: { publishingPaused?: unknown; slots?: unknown; timezone?: unknown; metricsEveryHours?: unknown }): AppSettings {
|
||||
const current = getSettings();
|
||||
const next: AppSettings = { ...current, slots: { ...current.slots } };
|
||||
if (input.publishingPaused !== undefined) {
|
||||
if (typeof input.publishingPaused !== "boolean") throw new UserError("publishingPaused precisa ser verdadeiro ou falso.");
|
||||
next.publishingPaused = input.publishingPaused;
|
||||
}
|
||||
if (input.slots !== undefined) {
|
||||
if (!input.slots || typeof input.slots !== "object") throw new UserError("Horários bons inválidos.");
|
||||
for (const [platform, list] of Object.entries(input.slots as Record<string, unknown>)) {
|
||||
if (!PLATFORMS.includes(platform as never)) throw new UserError(`Rede desconhecida nos horários: ${platform}.`);
|
||||
const clean = normalizeSlots(list);
|
||||
if (!clean) throw new UserError("Cada horário precisa estar no formato HH:MM (ex.: 08:00, 19:30).");
|
||||
if (clean.length === 0) throw new UserError("Deixe pelo menos um horário bom em cada rede.");
|
||||
next.slots[platform as keyof SlotMap] = clean;
|
||||
}
|
||||
}
|
||||
if (input.timezone !== undefined) {
|
||||
const tz = String(input.timezone).trim();
|
||||
if (!tz || !isValidTimezone(tz)) throw new UserError("Fuso horário inválido (use um nome como America/Sao_Paulo).");
|
||||
next.timezone = tz;
|
||||
}
|
||||
if (input.metricsEveryHours !== undefined) {
|
||||
const every = Number(input.metricsEveryHours);
|
||||
if (!(METRICS_EVERY_HOURS as readonly number[]).includes(every)) throw new UserError("Escolha 3, 6, 12 ou 24 horas, ou “só quando eu pedir”.");
|
||||
next.metricsEveryHours = every;
|
||||
}
|
||||
const upsert = "INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value";
|
||||
db().exec("BEGIN");
|
||||
try {
|
||||
run(upsert, "publishing_paused", next.publishingPaused ? "1" : "0");
|
||||
run(upsert, "slots", JSON.stringify(next.slots));
|
||||
run(upsert, "timezone", next.timezone);
|
||||
run(upsert, "metrics_every_hours", String(next.metricsEveryHours));
|
||||
db().exec("COMMIT");
|
||||
} catch (error) {
|
||||
db().exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
return getSettings();
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// Texto escrito → texto falado (pt-BR), para a voz sintética ler bem: números por extenso
|
||||
// ("55" → "cinquenta e cinco"), decimais ("0,0055" → "zero vírgula zero zero cinquenta e cinco"),
|
||||
// unidades ("km" → "quilômetros", "m²" → "metros quadrados", "%" → "por cento") e sem marcas de
|
||||
// markdown. É um ponto de partida: o admin revê e corrige o texto falado de cada trecho no painel.
|
||||
|
||||
const UNITS = ["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez",
|
||||
"onze", "doze", "treze", "catorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"];
|
||||
const TENS = ["", "", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"];
|
||||
const HUNDREDS = ["", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"];
|
||||
|
||||
function below1000(n: number): string {
|
||||
if (n === 100) return "cem";
|
||||
const h = Math.floor(n / 100);
|
||||
const rest = n % 100;
|
||||
const parts: string[] = [];
|
||||
if (h) parts.push(HUNDREDS[h]);
|
||||
if (rest) {
|
||||
if (rest < 20) parts.push(UNITS[rest]);
|
||||
else parts.push(TENS[Math.floor(rest / 10)] + (rest % 10 ? ` e ${UNITS[rest % 10]}` : ""));
|
||||
}
|
||||
return parts.join(" e ");
|
||||
}
|
||||
|
||||
/** Inteiro por extenso (0 a 999.999.999.999). */
|
||||
export function numberToWords(n: number): string {
|
||||
if (!Number.isFinite(n) || n < 0 || n > 999_999_999_999 || !Number.isInteger(n)) return String(n);
|
||||
if (n < 20) return UNITS[n];
|
||||
const groups: [number, string, string][] = [
|
||||
[1_000_000_000, "bilhão", "bilhões"], [1_000_000, "milhão", "milhões"], [1000, "mil", "mil"],
|
||||
];
|
||||
const parts: string[] = [];
|
||||
let rest = n;
|
||||
for (const [size, one, many] of groups) {
|
||||
const q = Math.floor(rest / size);
|
||||
if (!q) continue;
|
||||
parts.push(size === 1000 && q === 1 ? "mil" : `${below1000(q)} ${q === 1 ? one : many}`);
|
||||
rest %= size;
|
||||
}
|
||||
if (rest) parts.push(below1000(rest));
|
||||
// "e" antes do último grupo quando ele é < 100 ou uma centena redonda: "mil e cinco", "dois mil e trezentos".
|
||||
if (parts.length > 1 && rest && (rest < 100 || rest % 100 === 0)) {
|
||||
const last = parts.pop()!;
|
||||
return `${parts.join(" ")} e ${last}`;
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
/** Parte decimal lida dígito a dígito nos zeros à esquerda e depois como número: "0055" → "zero zero cinquenta e cinco". */
|
||||
function decimalToWords(digits: string): string {
|
||||
const zeros = /^0*/.exec(digits)![0].length;
|
||||
const rest = digits.slice(zeros);
|
||||
return [...Array(zeros).fill("zero"), ...(rest ? [numberToWords(Number(rest))] : [])].join(" ");
|
||||
}
|
||||
|
||||
const UNIT_WORDS: [RegExp, string, string][] = [
|
||||
[/^km²$/i, "quilômetro quadrado", "quilômetros quadrados"],
|
||||
[/^m²$/i, "metro quadrado", "metros quadrados"],
|
||||
[/^km$/i, "quilômetro", "quilômetros"],
|
||||
[/^m$/, "metro", "metros"],
|
||||
[/^cm$/i, "centímetro", "centímetros"],
|
||||
[/^kg$/i, "quilo", "quilos"],
|
||||
[/^ha$/i, "hectare", "hectares"],
|
||||
[/^s$/, "segundo", "segundos"],
|
||||
];
|
||||
|
||||
/** Converte o texto escrito no que a voz deve falar. */
|
||||
export function toSpokenText(written: string): string {
|
||||
let text = written
|
||||
.replace(/\*\*|__|[*_`]/g, "")
|
||||
.replace(/[“”"]/g, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
// "por m²" (sem número) → "por metro quadrado"
|
||||
text = text.replace(/\bpor m²/gi, "por metro quadrado").replace(/\bpor km\b/gi, "por quilômetro");
|
||||
// Número (com milhar "1.500" e decimal "0,0055"), opcionalmente seguido de unidade ou %.
|
||||
text = text.replace(/(\d{1,3}(?:\.\d{3})+|\d+)(?:,(\d+))?(\s*%|\s?(?:km²|m²|km|cm|kg|ha|m|s)\b|(?<=\d)\s?(?:km²|m²))?/g,
|
||||
(_match, intPart: string, decPart: string | undefined, unitRaw: string | undefined) => {
|
||||
const int = Number(intPart.replace(/\./g, ""));
|
||||
let spoken = numberToWords(int);
|
||||
if (decPart) spoken += ` vírgula ${decimalToWords(decPart)}`;
|
||||
const unit = unitRaw?.trim();
|
||||
if (!unit) return spoken;
|
||||
if (unit === "%") return `${spoken} por cento`;
|
||||
const rule = UNIT_WORDS.find(([re]) => re.test(unit));
|
||||
if (!rule) return `${spoken} ${unit}`;
|
||||
return `${spoken} ${int === 1 && !decPart ? rule[1] : rule[2]}`;
|
||||
});
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// Histórias e episódios. Cada história tem pasta própria em stories/<id>/ (roteiros e
|
||||
// assets exclusivos dela); a cena renderizável de cada episódio fica em
|
||||
// config/<id>-<file_key>.json (ep01, ep02-b...). O estágio do episódio é derivado do que existe.
|
||||
//
|
||||
// História interativa = árvore: cada episódio termina numa decisão com 1–4 vertentes (story.branch_count).
|
||||
// As vertentes são episódios `candidate` do nível seguinte; a que vence a votação vira `main` e as
|
||||
// outras ficam `discarded` (guardadas para o histórico do fluxo).
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, db, get, now, run } from "./db";
|
||||
import {
|
||||
DATA_DIR,
|
||||
SLUG_RE, episodeChoicesPath, episodeConfigPath, episodeFileKey, episodeScriptPath, readTextIfExists, rel, slugify,
|
||||
storyAssetsDir, storyDir,
|
||||
} from "./paths";
|
||||
import { CHOICES, STORY_KINDS, type Choice, type Decision, type Episode, type EpisodeView, type RenderJob, type Story, type StoryKind } from "./types";
|
||||
|
||||
export class UserError extends Error {}
|
||||
|
||||
export function listStories(): Story[] {
|
||||
return all<Story>(`SELECT s.*, (SELECT COUNT(*) FROM episodes e WHERE e.story_id = s.id AND e.status = 'main') AS episode_count
|
||||
FROM stories s ORDER BY s.updated_at DESC`);
|
||||
}
|
||||
|
||||
export function getStory(id: string): Story | undefined {
|
||||
return get<Story>("SELECT * FROM stories WHERE id = ?", id);
|
||||
}
|
||||
|
||||
export function createStory(input: { title: string; id?: string; logline?: string; kind: StoryKind; branchCount?: number }): Story {
|
||||
const title = input.title.trim();
|
||||
if (title.length < 2 || title.length > 80) throw new UserError("Título precisa ter entre 2 e 80 caracteres.");
|
||||
const id = (input.id?.trim() || slugify(title));
|
||||
if (!SLUG_RE.test(id)) throw new UserError("Identificador inválido: use minúsculas, números e '-'.");
|
||||
if (getStory(id)) throw new UserError(`Já existe uma história com o identificador "${id}".`);
|
||||
if (!STORY_KINDS.includes(input.kind)) throw new UserError("Tipo de história inválido.");
|
||||
// Linear e documental não têm decisão: 1 vertente (o episódio seguinte). Interativa: 2–4, escolhido pelo administrador.
|
||||
const branchCount = input.kind !== "interactive" ? 1 : Number(input.branchCount ?? 2);
|
||||
if (!Number.isInteger(branchCount) || branchCount < 1 || branchCount > 4) throw new UserError("Vertentes precisam ser de 1 a 4.");
|
||||
if (input.kind === "interactive" && branchCount < 2) throw new UserError("História interativa precisa de pelo menos 2 vertentes.");
|
||||
const ts = now();
|
||||
run("INSERT INTO stories (id, title, logline, kind, branch_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
id, title, (input.logline ?? "").trim().slice(0, 500), input.kind, branchCount, ts, ts);
|
||||
fs.mkdirSync(storyAssetsDir(id), { recursive: true });
|
||||
return getStory(id)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclui uma história do painel. O banco apaga episódios, comentários, decisões, publicações e
|
||||
* vínculos com contas (ON DELETE CASCADE); execuções de agente e renders ficam no histórico, sem a
|
||||
* história. Os arquivos NÃO são apagados: stories/<id>/ e config/<id>-*.json vão para
|
||||
* data/trash/<id>-<data>/, de onde dá para recuperar à mão. Arquivos primeiro, banco depois: se o
|
||||
* banco falhar, nada se perde (os arquivos estão na lixeira).
|
||||
*/
|
||||
export function deleteStory(id: string): { trashDir: string } {
|
||||
const story = getStory(id);
|
||||
if (!story) throw new UserError("História não encontrada.");
|
||||
if (get("SELECT 1 AS busy FROM agent_runs WHERE story_id = ? AND status = 'running'", id)) {
|
||||
throw new UserError("Um agente está trabalhando nesta história. Cancele a execução antes de excluir.");
|
||||
}
|
||||
if (get("SELECT 1 AS busy FROM renders r JOIN episodes e ON e.id = r.episode_id WHERE e.story_id = ? AND r.status = 'running'", id)) {
|
||||
throw new UserError("Há um render desta história em andamento. Cancele antes de excluir.");
|
||||
}
|
||||
const trashDir = path.join(DATA_DIR, "trash", `${id}-${now().replace(/[:.]/g, "-")}`);
|
||||
fs.mkdirSync(trashDir, { recursive: true });
|
||||
if (fs.existsSync(storyDir(id))) fs.renameSync(storyDir(id), path.join(trashDir, "stories"));
|
||||
const keys = all<{ file_key: string }>("SELECT file_key FROM episodes WHERE story_id = ?", id);
|
||||
for (const { file_key } of keys) {
|
||||
const config = episodeConfigPath(id, file_key);
|
||||
if (!fs.existsSync(config)) continue;
|
||||
fs.mkdirSync(path.join(trashDir, "config"), { recursive: true });
|
||||
fs.renameSync(config, path.join(trashDir, "config", path.basename(config)));
|
||||
}
|
||||
db().exec("BEGIN");
|
||||
try {
|
||||
// Assets exclusivos da história: os arquivos foram junto com a pasta para a lixeira.
|
||||
run("DELETE FROM assets WHERE scope = 'story' AND story_id = ?", id);
|
||||
run("DELETE FROM stories WHERE id = ?", id);
|
||||
db().exec("COMMIT");
|
||||
} catch (error) {
|
||||
db().exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
return { trashDir: rel(trashDir) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Depois que a IA monta a história, ela grava stories/<id>/meta.json com o título e a premissa
|
||||
* definitivos. O identificador (pasta) não muda. Campos inválidos são ignorados.
|
||||
*/
|
||||
export function syncStoryMeta(id: string): boolean {
|
||||
const text = readTextIfExists(`${storyDir(id)}/meta.json`);
|
||||
if (!text) return false;
|
||||
try {
|
||||
const meta = JSON.parse(text) as { title?: unknown; logline?: unknown };
|
||||
const title = typeof meta.title === "string" ? meta.title.trim() : "";
|
||||
const logline = typeof meta.logline === "string" ? meta.logline.trim().slice(0, 500) : null;
|
||||
if (title.length < 2 || title.length > 80) return false;
|
||||
run("UPDATE stories SET title = ?, logline = COALESCE(?, logline), updated_at = ? WHERE id = ?", title, logline, now(), id);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Título provisório a partir do texto do usuário (a IA define o definitivo em meta.json). */
|
||||
export function provisionalTitle(text: string): string {
|
||||
const first = text.trim().split(/[.!?\n]/)[0].trim().replace(/\s+/g, " ");
|
||||
const words = first.split(" ").slice(0, 7).join(" ");
|
||||
return (words.length >= 2 ? words : "Nova história").slice(0, 60);
|
||||
}
|
||||
|
||||
export function touchStory(id: string): void {
|
||||
run("UPDATE stories SET updated_at = ? WHERE id = ?", now(), id);
|
||||
}
|
||||
|
||||
/** Caminho que foi ao ar (episódios `main`), em ordem. */
|
||||
export function listEpisodes(storyId: string): EpisodeView[] {
|
||||
return all<Episode>("SELECT * FROM episodes WHERE story_id = ? AND status = 'main' ORDER BY number", storyId).map(view);
|
||||
}
|
||||
|
||||
/** Todos os nós da árvore (principal, vertentes candidatas e descartadas), para o fluxo. */
|
||||
export function listAllEpisodes(storyId: string): EpisodeView[] {
|
||||
return all<Episode>("SELECT * FROM episodes WHERE story_id = ? ORDER BY number, parent_choice", storyId).map(view);
|
||||
}
|
||||
|
||||
/** Episódio do caminho principal no nível `number`. */
|
||||
export function getEpisode(storyId: string, number: number): EpisodeView | undefined {
|
||||
const ep = get<Episode>("SELECT * FROM episodes WHERE story_id = ? AND number = ? AND status = 'main'", storyId, number);
|
||||
return ep ? view(ep) : undefined;
|
||||
}
|
||||
|
||||
/** Qualquer nó pela chave de arquivo (ep02-b). */
|
||||
export function getEpisodeByKey(storyId: string, fileKey: string): EpisodeView | undefined {
|
||||
const ep = get<Episode>("SELECT * FROM episodes WHERE story_id = ? AND file_key = ?", storyId, fileKey);
|
||||
return ep ? view(ep) : undefined;
|
||||
}
|
||||
|
||||
export function childEpisodes(episodeId: number): Episode[] {
|
||||
return all<Episode>("SELECT * FROM episodes WHERE parent_episode_id = ? ORDER BY parent_choice", episodeId);
|
||||
}
|
||||
|
||||
export function getEpisodeById(id: number): EpisodeView | undefined {
|
||||
const ep = get<Episode>("SELECT * FROM episodes WHERE id = ?", id);
|
||||
return ep ? view(ep) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Novo episódio do caminho principal. Com episódio anterior decidido, se a vertente vencedora já foi
|
||||
* preparada pela IA, ela é promovida (não cria outro); senão cria o episódio da vencedora.
|
||||
*/
|
||||
export function createEpisode(storyId: string, input: { title?: string; parentEpisodeId?: number } = {}): EpisodeView {
|
||||
const story = getStory(storyId);
|
||||
if (!story) throw new UserError("História não encontrada.");
|
||||
let parentChoice: Choice | null = null;
|
||||
if (input.parentEpisodeId) {
|
||||
const decision = get<Decision>("SELECT * FROM decisions WHERE episode_id = ?", input.parentEpisodeId);
|
||||
if (!decision && story.kind === "interactive") throw new UserError("O episódio anterior ainda não tem decisão fechada.");
|
||||
parentChoice = decision?.winner ?? null;
|
||||
const prepared = childEpisodes(input.parentEpisodeId).find((c) => c.parent_choice === parentChoice);
|
||||
if (prepared) {
|
||||
promoteWinner(input.parentEpisodeId, prepared.parent_choice!);
|
||||
return getEpisodeById(prepared.id)!;
|
||||
}
|
||||
}
|
||||
const next = (get<{ n: number }>("SELECT COALESCE(MAX(number), 0) + 1 AS n FROM episodes WHERE story_id = ? AND status = 'main'", storyId)!).n;
|
||||
const fileKey = uniqueFileKey(storyId, episodeFileKey(next, null));
|
||||
run(`INSERT INTO episodes (story_id, number, file_key, title, parent_episode_id, parent_choice, status, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'main', ?)`,
|
||||
storyId, next, fileKey, (input.title ?? "").trim().slice(0, 80), input.parentEpisodeId ?? null, parentChoice, now());
|
||||
touchStory(storyId);
|
||||
return getEpisodeByKey(storyId, fileKey)!;
|
||||
}
|
||||
|
||||
/** ep03 já usado (ex.: por uma vertente antiga com outro nome)? Usa ep03-2, ep03-3... */
|
||||
function uniqueFileKey(storyId: string, base: string): string {
|
||||
let key = base;
|
||||
for (let n = 2; get("SELECT 1 FROM episodes WHERE story_id = ? AND file_key = ?", storyId, key); n++) key = `${base}-${n}`;
|
||||
return key;
|
||||
}
|
||||
|
||||
/** Cria (ou devolve) as vertentes candidatas A..N do nível seguinte a um episódio. */
|
||||
export function ensureCandidates(episodeId: number): Episode[] {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (!ep) throw new UserError("Episódio não encontrado.");
|
||||
const story = getStory(ep.story_id)!;
|
||||
const existing = childEpisodes(episodeId);
|
||||
for (const letter of CHOICES.slice(0, story.branch_count)) {
|
||||
if (existing.some((c) => c.parent_choice === letter)) continue;
|
||||
const fileKey = uniqueFileKey(story.id, episodeFileKey(ep.number + 1, letter));
|
||||
run(`INSERT INTO episodes (story_id, number, file_key, title, parent_episode_id, parent_choice, status, created_at)
|
||||
VALUES (?, ?, ?, '', ?, ?, 'candidate', ?)`, story.id, ep.number + 1, fileKey, episodeId, letter, now());
|
||||
}
|
||||
touchStory(story.id);
|
||||
return childEpisodes(episodeId);
|
||||
}
|
||||
|
||||
/** A vertente vencedora entra no caminho principal; as irmãs ficam descartadas. */
|
||||
export function promoteWinner(parentEpisodeId: number, winner: Choice): Episode | undefined {
|
||||
const children = childEpisodes(parentEpisodeId);
|
||||
for (const child of children) {
|
||||
run("UPDATE episodes SET status = ? WHERE id = ?", child.parent_choice === winner ? "main" : "discarded", child.id);
|
||||
}
|
||||
const promoted = children.find((c) => c.parent_choice === winner);
|
||||
if (promoted) touchStory(promoted.story_id);
|
||||
return promoted ? get<Episode>("SELECT * FROM episodes WHERE id = ?", promoted.id) : undefined;
|
||||
}
|
||||
|
||||
/** Opções da decisão de um episódio: rótulos das vertentes filhas; senão choices.json; senão overlay A/B. */
|
||||
function decisionChoices(ep: Episode, overlay: EpisodeView["overlay"]): EpisodeView["choices"] {
|
||||
const story = getStory(ep.story_id);
|
||||
if (!story || story.kind !== "interactive") return [];
|
||||
const children = childEpisodes(ep.id);
|
||||
let fromFile: Record<string, string> = {};
|
||||
const text = readTextIfExists(episodeChoicesPath(ep.story_id, ep.file_key));
|
||||
if (text) {
|
||||
try {
|
||||
fromFile = JSON.parse(text) as Record<string, string>;
|
||||
} catch {
|
||||
fromFile = {};
|
||||
}
|
||||
}
|
||||
const fromOverlay: Record<string, string | undefined> = { A: overlay?.choiceA, B: overlay?.choiceB };
|
||||
return CHOICES.slice(0, story.branch_count).map((letter) => {
|
||||
const child = children.find((c) => c.parent_choice === letter);
|
||||
const label = child?.branch_label || (typeof fromFile[letter] === "string" ? fromFile[letter] : "") || fromOverlay[letter] || "";
|
||||
return { letter, label, episodeId: child?.id ?? null, fileKey: child?.file_key ?? null, status: child?.status ?? null };
|
||||
});
|
||||
}
|
||||
|
||||
function view(ep: Episode): EpisodeView {
|
||||
const scriptAbs = episodeScriptPath(ep.story_id, ep.file_key);
|
||||
const configAbs = episodeConfigPath(ep.story_id, ep.file_key);
|
||||
const hasScript = fs.existsSync(scriptAbs);
|
||||
const configText = readTextIfExists(configAbs);
|
||||
let overlay: EpisodeView["overlay"] = null;
|
||||
if (configText) {
|
||||
try {
|
||||
overlay = (JSON.parse(configText).overlay as EpisodeView["overlay"]) ?? null;
|
||||
} catch {
|
||||
overlay = null;
|
||||
}
|
||||
}
|
||||
const lastRender = get<RenderJob>("SELECT * FROM renders WHERE episode_id = ? ORDER BY id DESC LIMIT 1", ep.id) ?? null;
|
||||
const decision = get<Decision>("SELECT * FROM decisions WHERE episode_id = ?", ep.id) ?? null;
|
||||
const rendered = !!get("SELECT 1 FROM renders WHERE episode_id = ? AND status = 'success'", ep.id);
|
||||
const stage = decision ? "decidido" : rendered ? "renderizado" : configText ? "cena" : hasScript ? "roteiro" : "rascunho";
|
||||
return {
|
||||
...ep, stage, overlay, lastRender, decision, hasScript, hasConfig: configText !== null,
|
||||
scriptPath: rel(scriptAbs), configPath: rel(configAbs), choices: decisionChoices(ep, overlay),
|
||||
};
|
||||
}
|
||||
|
||||
export { storyDir };
|
||||
@@ -0,0 +1,354 @@
|
||||
// Formas dos registros do banco (nomes de coluna em snake_case, como no SQLite).
|
||||
|
||||
// documentary: vídeo único sobre fatos reais (nomes reais permitidos, fatos com fonte, sem votação).
|
||||
export type StoryKind = "interactive" | "linear" | "documentary";
|
||||
export const STORY_KINDS: StoryKind[] = ["interactive", "linear", "documentary"];
|
||||
/** Vertente de uma decisão: até 4 opções por episódio. */
|
||||
export type Choice = "A" | "B" | "C" | "D";
|
||||
export const CHOICES: Choice[] = ["A", "B", "C", "D"];
|
||||
export type StoryStatus = "active" | "finished";
|
||||
|
||||
export type Story = {
|
||||
id: string;
|
||||
title: string;
|
||||
logline: string;
|
||||
kind: StoryKind;
|
||||
/** Quantas vertentes cada decisão tem (1–4), escolhido ao criar a história. */
|
||||
branch_count: number;
|
||||
status: StoryStatus;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
episode_count?: number;
|
||||
};
|
||||
|
||||
/** main = caminho que foi ao ar; candidate = vertente preparada esperando a votação; discarded = perdeu. */
|
||||
export type EpisodeStatus = "main" | "candidate" | "discarded";
|
||||
export type BranchesStatus = "none" | "queued" | "running" | "ready" | "error";
|
||||
|
||||
export type Episode = {
|
||||
id: number;
|
||||
story_id: string;
|
||||
/** Nível na história (1 = início). */
|
||||
number: number;
|
||||
/** Nome dos arquivos de roteiro e cena: ep01, ep02-b. */
|
||||
file_key: string;
|
||||
title: string;
|
||||
parent_episode_id: number | null;
|
||||
parent_choice: Choice | null;
|
||||
/** Texto da opção (no episódio pai) que leva a este episódio. */
|
||||
branch_label: string;
|
||||
status: EpisodeStatus;
|
||||
/** Preparo das vertentes deste episódio pela IA. */
|
||||
branches_status: BranchesStatus;
|
||||
branches_run_id: number | null;
|
||||
created_at: string;
|
||||
/** Aprovação para publicar (botão "Aprovar para publicar"): render final escolhido, título e legenda. */
|
||||
approved_at: string | null;
|
||||
approved_render_id: number | null;
|
||||
publish_title: string | null;
|
||||
publish_caption: string | null;
|
||||
};
|
||||
|
||||
/** Etapa derivada dos arquivos e registros (não fica gravada). */
|
||||
export type EpisodeStage = "rascunho" | "roteiro" | "cena" | "renderizado" | "decidido";
|
||||
|
||||
export type EpisodeView = Episode & {
|
||||
stage: EpisodeStage;
|
||||
scriptPath: string;
|
||||
configPath: string;
|
||||
hasScript: boolean;
|
||||
hasConfig: boolean;
|
||||
overlay: { title?: string; choiceA?: string; choiceB?: string } | null;
|
||||
lastRender: RenderJob | null;
|
||||
decision: Decision | null;
|
||||
/** Opções da decisão deste episódio (interativa): uma por vertente, com o nó filho se já existe. */
|
||||
choices: { letter: Choice; label: string; episodeId: number | null; fileKey: string | null; status: EpisodeStatus | null }[];
|
||||
};
|
||||
|
||||
export type RenderStatus = "running" | "success" | "failed" | "cancelled" | "interrupted";
|
||||
|
||||
export type RenderJob = {
|
||||
id: number;
|
||||
episode_id: number | null;
|
||||
config_path: string;
|
||||
/** documentary: montagem do vídeo documental (FFmpeg), não o render do Godot. */
|
||||
profile: "preview" | "final" | "documentary";
|
||||
status: RenderStatus;
|
||||
run_dir: string | null;
|
||||
mp4: string | null;
|
||||
error: string | null;
|
||||
log_path: string | null;
|
||||
started_at: string;
|
||||
finished_at: string | null;
|
||||
};
|
||||
|
||||
// image/video: fotos e clipes da montagem documental (um por trecho do roteiro).
|
||||
export type AssetKind = "model" | "texture" | "background" | "image" | "video" | "audio" | "other";
|
||||
|
||||
export type Asset = {
|
||||
id: string;
|
||||
scope: "library" | "story";
|
||||
story_id: string | null;
|
||||
kind: AssetKind;
|
||||
name: string;
|
||||
version: number;
|
||||
file_path: string;
|
||||
license: string;
|
||||
source: string;
|
||||
notes: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type Comment = {
|
||||
id: number;
|
||||
episode_id: number;
|
||||
source: string;
|
||||
external_id: string;
|
||||
author_id: string;
|
||||
author_name: string;
|
||||
text: string;
|
||||
choice: Choice | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type Decision = {
|
||||
episode_id: number;
|
||||
closed_at: string;
|
||||
/** JSON {"A": 3, "B": 5, ...} */
|
||||
votes_json: string;
|
||||
winner: Choice;
|
||||
method: "votes" | "manual";
|
||||
rule: string;
|
||||
snapshot_json: string;
|
||||
};
|
||||
|
||||
export type Provider = "claude" | "codex";
|
||||
// godot: o agente constrói uma cena nova na biblioteca do Godot (godot/library/, doc/godot/cenas.md).
|
||||
export type AgentKind = "free" | "story" | "script" | "scene" | "branches" | "godot";
|
||||
export const AGENT_KINDS: AgentKind[] = ["free", "story", "script", "scene", "branches", "godot"];
|
||||
export type AgentStatus = "running" | "success" | "error" | "cancelled" | "interrupted";
|
||||
|
||||
export type AgentRun = {
|
||||
id: number;
|
||||
provider: Provider;
|
||||
model: string;
|
||||
kind: AgentKind;
|
||||
prompt: string;
|
||||
story_id: string | null;
|
||||
episode_id: number | null;
|
||||
resume_of: number | null;
|
||||
status: AgentStatus;
|
||||
session_id: string | null;
|
||||
cost_usd: number | null;
|
||||
num_turns: number | null;
|
||||
result: string | null;
|
||||
error: string | null;
|
||||
log_path: string;
|
||||
started_at: string;
|
||||
finished_at: string | null;
|
||||
};
|
||||
|
||||
/** Evento normalizado de um agente (Claude ou Codex), mostrado ao vivo no painel. */
|
||||
export type AgentEvent = {
|
||||
kind: "system" | "text" | "tool" | "tool_result" | "result" | "error" | "stderr";
|
||||
text: string;
|
||||
isError?: boolean;
|
||||
costUsd?: number;
|
||||
turns?: number;
|
||||
at: string;
|
||||
};
|
||||
|
||||
// ---------- contas vinculadas, publicações e métricas ----------
|
||||
export type Platform = "tiktok" | "instagram" | "youtube";
|
||||
export const PLATFORMS: Platform[] = ["tiktok", "instagram", "youtube"];
|
||||
|
||||
/** Aprovação dos vídeos novos: manual = você aprova cada um; auto = o despachante aprova sozinho. */
|
||||
export type ApprovalMode = "manual" | "auto";
|
||||
/** Quando publicar: na hora ou no próximo horário bom da rede (app_settings.slots). */
|
||||
export type PublishTiming = "now" | "best_slot";
|
||||
/** Rótulo "conteúdo feito com IA": auto = só quando o episódio usa voz de personagem (RVC) ou clonada. */
|
||||
export type AiLabel = "auto" | "always" | "never";
|
||||
|
||||
/** Canal de publicação (na UI); no banco e nas rotas continua `accounts`. */
|
||||
export type Account = {
|
||||
id: string;
|
||||
name: string;
|
||||
niche: string;
|
||||
notes: string;
|
||||
approval_mode: ApprovalMode;
|
||||
timing: PublishTiming;
|
||||
ai_label: AiLabel;
|
||||
/** Quando a aprovação automática foi ligada (cortes mais antigos não são aprovados sozinhos). */
|
||||
auto_since: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type ConnectionMode = "official" | "session";
|
||||
export type NetworkStatus = "disconnected" | "connecting" | "connected" | "needs_login" | "expired" | "error";
|
||||
export const NETWORK_STATUSES: NetworkStatus[] = ["disconnected", "connecting", "connected", "needs_login", "expired", "error"];
|
||||
export type Privacy = "public" | "unlisted" | "private";
|
||||
export type TiktokMode = "direct" | "draft";
|
||||
|
||||
/**
|
||||
* Perfil do canal numa rede (linha de account_networks). O estado espelha o `Profile` do Publicador
|
||||
* (profileId = "<accountId>--<platform>"). Redes que o canal nunca configurou não têm linha: a UI usa
|
||||
* os padrões (desconectado, ligado, 3 por dia, público, TikTok direto).
|
||||
*/
|
||||
export type AccountNetwork = {
|
||||
id: number;
|
||||
account_id: string;
|
||||
platform: Platform;
|
||||
/** @ da rede; NULL até a rede informar. */
|
||||
handle: string | null;
|
||||
status: NetworkStatus;
|
||||
mode: ConnectionMode | null;
|
||||
/** 1 = publica nesta rede; 0 = pausada só aqui. */
|
||||
enabled: number;
|
||||
daily_limit: number;
|
||||
privacy: Privacy;
|
||||
tiktok_mode: TiktokMode;
|
||||
display_name: string | null;
|
||||
last_error: string | null;
|
||||
checked_at: string | null;
|
||||
/** Validade do token/sessão longa, quando a rede informa. */
|
||||
expires_at: string | null;
|
||||
connected_at: string | null;
|
||||
};
|
||||
|
||||
/** Próximo passo de uma conexão (igual ao `Next` do contrato do Publicador). */
|
||||
export type ConnectNext =
|
||||
| { kind: "open_url"; url: string }
|
||||
| { kind: "paste_token"; help: string }
|
||||
| { kind: "browser_opened"; help: string }
|
||||
| { kind: "none" };
|
||||
|
||||
/** Canal de live (Clipador) ligado à conta: os cortes dele saem nas redes desta conta. */
|
||||
export type AccountChannel = {
|
||||
account_id: string;
|
||||
channel_id: string;
|
||||
status: "active" | "ended";
|
||||
linked_at: string;
|
||||
ended_at: string | null;
|
||||
};
|
||||
|
||||
export type AccountStory = {
|
||||
account_id: string;
|
||||
story_id: string;
|
||||
status: "active" | "ended";
|
||||
linked_at: string;
|
||||
ended_at: string | null;
|
||||
};
|
||||
|
||||
export type Publication = {
|
||||
id: number;
|
||||
/** Episódio publicado (NULL quando é corte do Clipador). */
|
||||
episode_id: number | null;
|
||||
/** Corte do Clipador publicado (NULL quando é episódio). */
|
||||
clip_id: number | null;
|
||||
account_id: string;
|
||||
platform: Platform;
|
||||
url: string;
|
||||
published_at: string;
|
||||
simulated: number;
|
||||
/** Job da fila de publicação que gerou este registro (só nas reais). */
|
||||
job_id: number | null;
|
||||
};
|
||||
|
||||
// ---------- fila de publicação ----------
|
||||
export type PublishJobStatus =
|
||||
| "awaiting_approval" | "scheduled" | "queued" | "publishing" | "published" | "failed" | "needs_login" | "canceled";
|
||||
export const PUBLISH_JOB_STATUSES: PublishJobStatus[] =
|
||||
["awaiting_approval", "scheduled", "queued", "publishing", "published", "failed", "needs_login", "canceled"];
|
||||
export type PublishSourceKind = "clip" | "episode";
|
||||
/** Ações que a UI pode oferecer num job (POST /api/publishing/jobs/[id]/<ação>; reschedule = PATCH scheduledAt). */
|
||||
export type PublishJobAction = "approve" | "publish-now" | "retry" | "cancel" | "reschedule" | "edit" | "relogin" | "mark-published" | "removed";
|
||||
|
||||
export type PublishJob = {
|
||||
id: number;
|
||||
accountId: string;
|
||||
accountName: string;
|
||||
platform: Platform;
|
||||
sourceKind: PublishSourceKind;
|
||||
/** Id do corte (Clipador) ou do episódio, como texto. */
|
||||
sourceId: string;
|
||||
/** Fonte do corte (ex.: twitch-alanzoka) ou "História · ep01". */
|
||||
sourceLabel: string;
|
||||
/** MP4 e capa relativos à raiz (para mostrar: /api/files?path=...). */
|
||||
file: string;
|
||||
cover: string | null;
|
||||
title: string;
|
||||
caption: string;
|
||||
status: PublishJobStatus;
|
||||
/** Horário marcado (ISO, UTC). Em `queued` = quando entrou na fila. */
|
||||
scheduledAt: string | null;
|
||||
/** Texto curto em pt-BR: o que está acontecendo ou por que está esperando. */
|
||||
step: string;
|
||||
/** 0..1 */
|
||||
progress: number;
|
||||
remoteId: string | null;
|
||||
url: string | null;
|
||||
/** true = foi para rascunho/inbox (TikTok), não está público. */
|
||||
draft: boolean;
|
||||
error: string | null;
|
||||
/** Tentativas explícitas (sobe em "Tentar de novo"/reaprovação); o envio usa clientRef = "<id>:<attempts>". */
|
||||
attempts: number;
|
||||
/** unlinked = a fonte (corte) ou a história (episódio) foi desligada do canal. */
|
||||
cancelReason: "user" | "source_changed" | "unapproved" | "unlinked" | null;
|
||||
/** Origem do horário: auto (agenda do despachante), manual (escolhido por você), now (Publicar agora / Tentar de novo). */
|
||||
scheduleSource: "auto" | "manual" | "now";
|
||||
/**
|
||||
* O envio anterior chegou ao Publicador e terminou sem confirmação (ex.: caiu no meio): o vídeo PODE já estar na rede.
|
||||
* A UI pede confirmação ("Confira na rede se o vídeo já saiu antes de tentar de novo") e manda {confirm: true} no retry.
|
||||
*/
|
||||
mayBeLive: boolean;
|
||||
publishedAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
/** Estado do perfil da rede neste canal (null = rede nunca configurada). */
|
||||
network: { status: NetworkStatus; mode: ConnectionMode | null; handle: string | null; displayName: string | null; enabled: boolean } | null;
|
||||
actions: PublishJobAction[];
|
||||
};
|
||||
|
||||
export type SlotMap = Record<Platform, string[]>;
|
||||
|
||||
/** Configurações gerais (app_settings), em GET/PUT /api/settings. */
|
||||
export type AppSettings = {
|
||||
publishingPaused: boolean;
|
||||
/** Horários bons por rede, "HH:MM" no fuso `timezone`, em ordem. */
|
||||
slots: SlotMap;
|
||||
/** Fuso IANA (padrão America/Sao_Paulo). */
|
||||
timezone: string;
|
||||
/** De quantas em quantas horas o painel lê sozinho os números dos posts (0 = só quando você pedir). */
|
||||
metricsEveryHours: number;
|
||||
};
|
||||
|
||||
/** Contagens da fila (menu e dashboard) e saúde do despachante. */
|
||||
export type PublishingSummary = {
|
||||
counts: Record<PublishJobStatus, number>;
|
||||
awaitingApproval: number;
|
||||
/** Com problema = failed + needs_login. */
|
||||
problems: number;
|
||||
paused: boolean;
|
||||
dispatcher: {
|
||||
running: boolean;
|
||||
lastTickAt: string | null;
|
||||
lastError: string | null;
|
||||
publisherOnline: boolean | null;
|
||||
clipperOnline: boolean | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type MetricTotals = {
|
||||
views: number;
|
||||
likes: number;
|
||||
comments: number;
|
||||
shares: number;
|
||||
saves: number;
|
||||
publications: number;
|
||||
/** Média ponderada por views; null sem dados. */
|
||||
completionRate: number | null;
|
||||
/** (likes + comentários + compartilhamentos + salvos) / views. */
|
||||
engagementRate: number | null;
|
||||
};
|
||||
@@ -0,0 +1,487 @@
|
||||
// Ponte do painel com o serviço de voz local (voice/, 127.0.0.1:4510).
|
||||
// O painel lê a chave e a porta de voice/.env, fala com o serviço por HTTP e cuida do que é arquivo:
|
||||
// vozes de personagem (data/voice/user-voices.json + .pth/.index) e configurações (voice/.env).
|
||||
// Mudou o voice/.env → o `pnpm dev` (scripts/dev.ts) reinicia o serviço sozinho.
|
||||
import { spawn } from "node:child_process";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { REPO_ROOT, slugify } from "./paths";
|
||||
import { UserError } from "./stories";
|
||||
|
||||
export const VOICE_DIR = path.join(REPO_ROOT, "voice");
|
||||
const ENV_FILE = path.join(VOICE_DIR, ".env");
|
||||
const LOCK_FILE = path.join(VOICE_DIR, "models.lock.json");
|
||||
const APPLIO_INFER = path.join(VOICE_DIR, "vendor", "applio", "rvc", "infer", "infer.py");
|
||||
const VENV_PYTHON = path.join(VOICE_DIR, ".venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
|
||||
export const DEVICES = ["auto", "cuda", "cpu"] as const;
|
||||
export const STT_MODELS = ["base", "small", "medium", "large-v3-turbo"] as const;
|
||||
export const F0_METHODS = ["rmvpe", "fcpe", "crepe"] as const;
|
||||
export const LANGUAGES = ["pt-BR", "en", "es"] as const;
|
||||
export const DETAILS = ["text", "segments", "words"] as const;
|
||||
const VOICE_ID_RE = /^[a-z0-9][a-z0-9-]{1,47}$/; // mesmo padrão do serviço (schemas.py)
|
||||
const MAX_MODEL_BYTES = 1024 * 1024 * 1024;
|
||||
|
||||
type Device = (typeof DEVICES)[number];
|
||||
type SttModel = (typeof STT_MODELS)[number];
|
||||
|
||||
export type VoiceSettings = {
|
||||
device: Device; sttModel: SttModel; enableRvc: boolean; sttModelsInstalled: string[];
|
||||
/** Azure Speech: só diz se há chave; a chave nunca sai do servidor. */
|
||||
azureConfigured: boolean; azureRegion: string;
|
||||
};
|
||||
export type VoiceJob = { kind: "download"; status: "running" | "done" | "error"; message: string };
|
||||
|
||||
// ---------- voice/.env ----------
|
||||
export function readVoiceEnv(): 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;
|
||||
}
|
||||
|
||||
/** Troca só as chaves pedidas, preservando comentários e a ordem do arquivo. */
|
||||
function writeVoiceEnv(values: Record<string, string>): void {
|
||||
if (!fs.existsSync(ENV_FILE)) throw new UserError("voice/.env não existe: rode o setup.bat.");
|
||||
const lines = fs.readFileSync(ENV_FILE, "utf8").split(/\r?\n/);
|
||||
const pending = new Map(Object.entries(values));
|
||||
const out = lines.map((line) => {
|
||||
const name = line.split("=", 1)[0].trim();
|
||||
if (!line.trimStart().startsWith("#") && pending.has(name)) {
|
||||
const value = pending.get(name)!;
|
||||
pending.delete(name);
|
||||
return `${name}=${value}`;
|
||||
}
|
||||
return line;
|
||||
});
|
||||
for (const [name, value] of pending) out.push(`${name}=${value}`);
|
||||
const tmp = `${ENV_FILE}.tmp`;
|
||||
fs.writeFileSync(tmp, out.join("\n"), "utf8");
|
||||
fs.renameSync(tmp, ENV_FILE);
|
||||
}
|
||||
|
||||
function resolveFromRoot(value: string | undefined, fallback: string): string {
|
||||
if (!value) return fallback;
|
||||
return path.isAbsolute(value) ? value : path.join(REPO_ROOT, value);
|
||||
}
|
||||
|
||||
export const modelsDir = () => resolveFromRoot(readVoiceEnv().VOICE_MODELS_DIR, path.join(REPO_ROOT, "data", "voice", "models"));
|
||||
const userCatalogPath = () =>
|
||||
resolveFromRoot(readVoiceEnv().VOICE_USER_CATALOG, path.join(REPO_ROOT, "data", "voice", "user-voices.json"));
|
||||
export const applioInstalled = () => fs.existsSync(APPLIO_INFER);
|
||||
const CLONE_PYTHON = path.join(VOICE_DIR, ".venv-clone", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
||||
/** Clonagem de voz instalada (setup.bat -Clone): venv próprio com o Chatterbox. */
|
||||
export const cloneInstalled = () => fs.existsSync(CLONE_PYTHON);
|
||||
|
||||
// ---------- HTTP com o serviço ----------
|
||||
function serviceUrl(pathname: string): { url: string; key: string } {
|
||||
const env = readVoiceEnv();
|
||||
if (!env.VOICE_SERVICE_KEY) throw new UserError("Serviço de voz não instalado: rode o setup.bat.");
|
||||
return { url: `http://127.0.0.1:${env.VOICE_PORT || "4510"}${pathname}`, key: env.VOICE_SERVICE_KEY };
|
||||
}
|
||||
|
||||
async function voiceFetch(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("Serviço de voz fora do ar (127.0.0.1). Suba com start.bat ou pnpm dev.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Erro do serviço `{error:{code,message}}` → UserError com a mensagem dele. */
|
||||
async function serviceError(response: Response): Promise<UserError> {
|
||||
try {
|
||||
const body = (await response.json()) as { error?: { code?: string; message?: string } };
|
||||
return new UserError(body.error?.message ?? `Serviço de voz respondeu ${response.status}.`);
|
||||
} catch {
|
||||
return new UserError(`Serviço de voz respondeu ${response.status}.`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- configurações ----------
|
||||
function installedSttModels(): string[] {
|
||||
const lock = JSON.parse(fs.readFileSync(LOCK_FILE, "utf8")) as { files: { path: string; group?: string }[] };
|
||||
const dir = modelsDir();
|
||||
return STT_MODELS.filter((model) => {
|
||||
const files = lock.files.filter((f) => f.group === `stt-${model}`);
|
||||
// Existência e tamanho; o sha256 completo o serviço confere na subida.
|
||||
return files.length > 0 && files.every((f) => fs.existsSync(path.join(dir, f.path)) && fs.statSync(path.join(dir, f.path)).size > 0);
|
||||
});
|
||||
}
|
||||
|
||||
export function readSettings(): VoiceSettings {
|
||||
const env = readVoiceEnv();
|
||||
const device = (DEVICES as readonly string[]).includes(env.VOICE_DEVICE) ? (env.VOICE_DEVICE as Device) : "auto";
|
||||
const sttModel = (STT_MODELS as readonly string[]).includes(env.VOICE_STT_MODEL) ? (env.VOICE_STT_MODEL as SttModel) : "small";
|
||||
return {
|
||||
device, sttModel, enableRvc: env.VOICE_ENABLE_RVC === "1", sttModelsInstalled: installedSttModels(),
|
||||
azureConfigured: Boolean(env.VOICE_AZURE_KEY), azureRegion: env.VOICE_AZURE_REGION || "eastus",
|
||||
};
|
||||
}
|
||||
|
||||
// Download de modelo em andamento (um por vez). Vive na memória do processo do painel.
|
||||
let job: VoiceJob | null = null;
|
||||
|
||||
export function updateSettings(input: { device?: unknown; sttModel?: unknown; enableRvc?: unknown }): { download: boolean } {
|
||||
const device = String(input.device);
|
||||
const sttModel = String(input.sttModel);
|
||||
const enableRvc = input.enableRvc === true;
|
||||
if (!(DEVICES as readonly string[]).includes(device)) throw new UserError("Dispositivo inválido.");
|
||||
if (!(STT_MODELS as readonly string[]).includes(sttModel)) throw new UserError("Modelo do Whisper inválido.");
|
||||
if (enableRvc && !applioInstalled()) throw new UserError("O Applio não está instalado: rode o setup.bat sem -NoRvc.");
|
||||
if (job?.status === "running") throw new UserError("Já há um download de modelo em andamento.");
|
||||
const values = { VOICE_DEVICE: device, VOICE_ENABLE_RVC: enableRvc ? "1" : "0", VOICE_STT_MODEL: sttModel };
|
||||
if (installedSttModels().includes(sttModel)) {
|
||||
writeVoiceEnv(values);
|
||||
return { download: false };
|
||||
}
|
||||
// Modelo ausente: baixa primeiro (com sha256) e só então grava o .env — senão o serviço não sobe.
|
||||
job = { kind: "download", status: "running", message: `Baixando Whisper ${sttModel}…` };
|
||||
const child = spawn(VENV_PYTHON, [path.join(VOICE_DIR, "scripts", "fetch_models.py"), "--group", `stt-${sttModel}`], {
|
||||
cwd: VOICE_DIR,
|
||||
windowsHide: true,
|
||||
env: { ...process.env, VOICE_MODELS_DIR: modelsDir(), PYTHONUTF8: "1" },
|
||||
});
|
||||
let tail = "";
|
||||
const keep = (chunk: Buffer) => {
|
||||
tail = (tail + chunk.toString("utf8")).slice(-400);
|
||||
};
|
||||
child.stdout.on("data", keep);
|
||||
child.stderr.on("data", keep);
|
||||
child.on("error", () => {
|
||||
job = { kind: "download", status: "error", message: "Não consegui iniciar o Python do voice/.venv; rode o setup.bat." };
|
||||
});
|
||||
child.on("exit", (code) => {
|
||||
if (code === 0) {
|
||||
writeVoiceEnv(values);
|
||||
job = { kind: "download", status: "done", message: `Whisper ${sttModel} instalado; o serviço de voz está reiniciando.` };
|
||||
} else {
|
||||
job = { kind: "download", status: "error", message: `Download falhou: ${tail.trim().split("\n").pop() ?? code}` };
|
||||
}
|
||||
});
|
||||
return { download: true };
|
||||
}
|
||||
|
||||
// ---------- Azure Speech ----------
|
||||
const AZURE_REGION_RE = /^[a-z0-9]{2,32}$/;
|
||||
const AZURE_KEY_RE = /^[A-Za-z0-9]{20,128}$/;
|
||||
|
||||
/**
|
||||
* Grava região e chave do Azure no voice/.env (o pnpm dev reinicia o serviço sozinho).
|
||||
* `key` vazio mantém a chave atual; `clear: true` apaga a chave (as vozes Azure somem da lista).
|
||||
*/
|
||||
export function updateAzure(input: { region?: unknown; key?: unknown; clear?: unknown }): void {
|
||||
const region = String(input.region ?? "").trim().toLowerCase();
|
||||
const key = String(input.key ?? "").trim();
|
||||
if (!AZURE_REGION_RE.test(region)) throw new UserError("Região inválida (ex.: eastus, brazilsouth).");
|
||||
if (key && !AZURE_KEY_RE.test(key)) throw new UserError("A chave do Azure tem só letras e números (copie a \"KEY 1\" do recurso de Fala).");
|
||||
const values: Record<string, string> = { VOICE_AZURE_REGION: region };
|
||||
if (input.clear === true) values.VOICE_AZURE_KEY = "";
|
||||
else if (key) values.VOICE_AZURE_KEY = key;
|
||||
else if (!readVoiceEnv().VOICE_AZURE_KEY) throw new UserError("Cole a chave do Azure.");
|
||||
writeVoiceEnv(values);
|
||||
}
|
||||
|
||||
// ---------- estado ----------
|
||||
export async function getStatus() {
|
||||
const base = { applioInstalled: applioInstalled(), cloneInstalled: cloneInstalled(), settings: readSettings(), job };
|
||||
try {
|
||||
const [status, voices] = await Promise.all([voiceFetch("/v1/status", {}, 5_000), voiceFetch("/v1/voices?limit=100", {}, 5_000)]);
|
||||
if (!status.ok) throw await serviceError(status);
|
||||
if (!voices.ok) throw await serviceError(voices);
|
||||
const s = (await status.json()) as { device: unknown; rvc: boolean; engines: unknown };
|
||||
const v = (await voices.json()) as { items: unknown[] };
|
||||
return { ...base, online: true, device: s.device, rvc: s.rvc, engines: s.engines, voices: v.items };
|
||||
} catch (error) {
|
||||
// Fora do ar, as vozes de personagem ainda aparecem (lidas do arquivo local) para poder removê-las.
|
||||
let voices: unknown[] = [];
|
||||
try {
|
||||
voices = readUserCatalog().voices.map((v) => v.kind === "clone" ? {
|
||||
id: v.id, name: v.name, languages: ["pt-BR"], engine: "tts", default: false,
|
||||
description: v.description ?? null, gender: v.gender ?? null, ageRange: null, provider: "clone", baseVoice: null,
|
||||
user: true, offline: true, rvc: null,
|
||||
} : {
|
||||
id: v.id, name: v.name, languages: ["pt-BR"], engine: "tts+rvc", default: false,
|
||||
description: v.description ?? null, gender: null, ageRange: null, provider: "edge", baseVoice: v.baseVoice ?? null,
|
||||
user: true, offline: false,
|
||||
rvc: {
|
||||
pitch: Number(v.rvc?.pitch ?? 0), f0Method: String(v.rvc?.f0Method ?? "rmvpe"),
|
||||
indexRate: Number(v.rvc?.indexRate ?? 0.5), protect: Number(v.rvc?.protect ?? 0.33), hasIndex: Boolean(v.rvc?.index),
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// catálogo local ilegível: segue sem vozes
|
||||
}
|
||||
return { ...base, online: false, error: error instanceof Error ? error.message : String(error), voices };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- síntese ----------
|
||||
export async function synthesize(input: { voiceId?: unknown; text?: unknown; speed?: unknown }): Promise<Response> {
|
||||
const voiceId = String(input.voiceId ?? "");
|
||||
const text = String(input.text ?? "").trim();
|
||||
const speed = Number(input.speed ?? 1);
|
||||
if (!VOICE_ID_RE.test(voiceId)) throw new UserError("Voz inválida.");
|
||||
if (!text) throw new UserError("Escreva um texto para ouvir.");
|
||||
if (!(speed >= 0.5 && speed <= 2)) throw new UserError("Velocidade precisa estar entre 0,5 e 2.");
|
||||
const response = await voiceFetch(
|
||||
"/v1/synthesize",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ requestId: `panel-${crypto.randomUUID()}`.slice(0, 64), text, voiceId, params: { speed, format: "ogg_opus" } }),
|
||||
},
|
||||
300_000,
|
||||
);
|
||||
if (!response.ok) throw await serviceError(response);
|
||||
return new Response(response.body, {
|
||||
headers: { "Content-Type": "audio/ogg", "Cache-Control": "no-store", "X-Audio-Duration-Ms": response.headers.get("X-Audio-Duration-Ms") ?? "" },
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- transcrição / legenda ----------
|
||||
type Segment = { start: number; end: number; text: string; words?: { start: number; end: number; text: string; p: number }[] };
|
||||
|
||||
function srtTime(seconds: number): string {
|
||||
const ms = Math.max(0, Math.round(seconds * 1000));
|
||||
const h = Math.floor(ms / 3_600_000);
|
||||
const m = Math.floor((ms % 3_600_000) / 60_000);
|
||||
const s = Math.floor((ms % 60_000) / 1000);
|
||||
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
|
||||
return `${pad(h)}:${pad(m)}:${pad(s)},${pad(ms % 1000, 3)}`;
|
||||
}
|
||||
|
||||
/** Segmentos com tempo → SubRip (.srt). */
|
||||
export function toSrt(segments: Segment[]): string {
|
||||
return segments
|
||||
.filter((seg) => seg.text.trim())
|
||||
.map((seg, i) => `${i + 1}\n${srtTime(seg.start)} --> ${srtTime(seg.end)}\n${seg.text.trim()}\n`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
export async function transcribe(file: File, language: string, detail: string) {
|
||||
if (!(LANGUAGES as readonly string[]).includes(language)) throw new UserError("Idioma inválido.");
|
||||
if (!(DETAILS as readonly string[]).includes(detail)) throw new UserError("Detalhe inválido.");
|
||||
if (file.size === 0) throw new UserError("Arquivo de áudio vazio.");
|
||||
const audio = Buffer.from(await file.arrayBuffer());
|
||||
let response = await voiceFetch(
|
||||
"/v1/transcribe",
|
||||
{
|
||||
method: "POST",
|
||||
body: audio,
|
||||
headers: {
|
||||
"Content-Type": file.type && file.type.includes("/") ? file.type : "application/octet-stream",
|
||||
"X-Idempotency-Key": `panel-${crypto.randomUUID()}`,
|
||||
"X-Language": language,
|
||||
"X-Detail": detail,
|
||||
},
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
// 202 = ainda transcrevendo: o painel espera o job (até 20 min, o teto do serviço para 30 min de áudio na CPU).
|
||||
const deadline = Date.now() + 20 * 60_000;
|
||||
while (response.status === 202 && Date.now() < deadline) {
|
||||
const pending = (await response.json()) as { jobRef: string; retryAfterMs: number };
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.min(10_000, Math.max(500, pending.retryAfterMs))));
|
||||
response = await voiceFetch(`/v1/transcribe/jobs/${encodeURIComponent(pending.jobRef)}`, {}, 30_000);
|
||||
}
|
||||
if (response.status === 202) throw new UserError("A transcrição passou de 20 minutos; tente um áudio menor.");
|
||||
if (!response.ok) throw await serviceError(response);
|
||||
const result = (await response.json()) as { text: string; noSpeechProb: number; durationS?: number; segments?: Segment[] };
|
||||
return { ...result, srt: result.segments ? toSrt(result.segments) : undefined };
|
||||
}
|
||||
|
||||
// ---------- vozes de personagem ----------
|
||||
type UserVoiceEntry = {
|
||||
id: string;
|
||||
name: string;
|
||||
/** "clone" = voz clonada de uma gravação; ausente = voz de personagem RVC. */
|
||||
kind?: "clone";
|
||||
baseVoice?: string;
|
||||
description?: string;
|
||||
gender?: "female" | "male";
|
||||
source: string;
|
||||
license: string;
|
||||
consent?: boolean;
|
||||
consentAt?: string;
|
||||
rvc?: Record<string, string | number>;
|
||||
clone?: Record<string, string | number>;
|
||||
};
|
||||
|
||||
function readUserCatalog(): { voices: UserVoiceEntry[] } {
|
||||
const file = userCatalogPath();
|
||||
if (!fs.existsSync(file)) return { voices: [] };
|
||||
return JSON.parse(fs.readFileSync(file, "utf8")) as { voices: UserVoiceEntry[] };
|
||||
}
|
||||
|
||||
/**
|
||||
* A voz é do catálogo do usuário (personagem RVC ou voz clonada)? Usado no rótulo "feito com IA" da publicação
|
||||
* (ai_label = auto). Sem catálogo = nenhuma voz do usuário; catálogo ilegível LANÇA erro — quem chama decide
|
||||
* com cautela (a publicação liga o rótulo de IA).
|
||||
*/
|
||||
export function isUserVoice(voiceId: string): boolean {
|
||||
if (!voiceId) return false;
|
||||
return readUserCatalog().voices.some((v) => v.id === voiceId);
|
||||
}
|
||||
|
||||
function writeUserCatalog(catalog: { voices: UserVoiceEntry[] }): void {
|
||||
const file = userCatalogPath();
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const tmp = `${file}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(catalog, null, 2) + "\n", "utf8");
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
|
||||
async function reloadService(): Promise<void> {
|
||||
try {
|
||||
const response = await voiceFetch("/v1/voices/reload", { method: "POST" }, 120_000);
|
||||
if (!response.ok) throw await serviceError(response);
|
||||
} catch {
|
||||
// Serviço fora do ar: ele lê o catálogo novo quando subir.
|
||||
}
|
||||
}
|
||||
|
||||
function numberIn(raw: FormDataEntryValue | null, fallback: number, min: number, max: number, label: string): number {
|
||||
const value = raw === null || raw === "" ? fallback : Number(raw);
|
||||
if (!Number.isFinite(value) || value < min || value > max) throw new UserError(`${label} precisa estar entre ${min} e ${max}.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** .pth do RVC é um checkpoint do torch: zip (formato atual) ou pickle (formato antigo). */
|
||||
function looksLikeTorchCheckpoint(head: Buffer): boolean {
|
||||
const zip = head[0] === 0x50 && head[1] === 0x4b && head[2] === 0x03 && head[3] === 0x04;
|
||||
const pickle = head[0] === 0x80 && head[1] >= 2 && head[1] <= 5;
|
||||
return zip || pickle;
|
||||
}
|
||||
|
||||
export async function addUserVoice(form: FormData): Promise<{ id: string }> {
|
||||
if (!applioInstalled()) throw new UserError("O Applio não está instalado: rode o setup.bat sem -NoRvc.");
|
||||
const text = (key: string) => String(form.get(key) ?? "").trim();
|
||||
const name = text("name");
|
||||
const baseVoice = text("baseVoice");
|
||||
const source = text("source");
|
||||
const license = text("license");
|
||||
if (name.length < 2 || name.length > 60) throw new UserError("Nome precisa ter entre 2 e 60 caracteres.");
|
||||
if (!source || !license) throw new UserError("Informe a origem e a licença da voz.");
|
||||
if (!VOICE_ID_RE.test(baseVoice)) throw new UserError("Escolha a voz base.");
|
||||
const f0Method = text("f0Method") || "rmvpe";
|
||||
if (!(F0_METHODS as readonly string[]).includes(f0Method)) throw new UserError("Método de f0 inválido.");
|
||||
const pitch = Math.round(numberIn(form.get("pitch"), 0, -24, 24, "Pitch"));
|
||||
const indexRate = numberIn(form.get("indexRate"), 0.5, 0, 1, "Index rate");
|
||||
const protect = numberIn(form.get("protect"), 0.33, 0, 0.5, "Protect");
|
||||
|
||||
const model = form.get("model");
|
||||
const index = form.get("index");
|
||||
if (!(model instanceof File) || !model.name.toLowerCase().endsWith(".pth")) throw new UserError("Envie o modelo .pth.");
|
||||
if (model.size > MAX_MODEL_BYTES) throw new UserError("Modelo acima de 1 GB.");
|
||||
const hasIndex = index instanceof File && index.size > 0;
|
||||
if (hasIndex && !index.name.toLowerCase().endsWith(".index")) throw new UserError("O arquivo de índice precisa ser .index.");
|
||||
if (hasIndex && index.size > MAX_MODEL_BYTES) throw new UserError("Índice acima de 1 GB.");
|
||||
|
||||
const catalog = readUserCatalog();
|
||||
const status = await getStatus();
|
||||
const known = new Set<string>([...catalog.voices.map((v) => v.id), ...(status.voices as { id: string }[]).map((v) => v.id)]);
|
||||
if (status.online && !known.has(baseVoice)) throw new UserError("Voz base desconhecida.");
|
||||
let id = slugify(name);
|
||||
if (!VOICE_ID_RE.test(id)) throw new UserError("Nome precisa ter letras ou números.");
|
||||
for (let n = 2; known.has(id); n++) id = `${slugify(name).slice(0, 44)}-${n}`;
|
||||
|
||||
const modelBytes = Buffer.from(await model.arrayBuffer());
|
||||
if (!looksLikeTorchCheckpoint(modelBytes.subarray(0, 4))) throw new UserError("O .pth não parece um modelo do torch/RVC.");
|
||||
const folder = path.join(modelsDir(), "rvc", id);
|
||||
fs.mkdirSync(folder, { recursive: true });
|
||||
const sha = (data: Buffer) => crypto.createHash("sha256").update(data).digest("hex");
|
||||
fs.writeFileSync(path.join(folder, `${id}.pth`), modelBytes);
|
||||
const rvc: Record<string, string | number> = {
|
||||
model: `rvc/${id}/${id}.pth`,
|
||||
modelSha256: sha(modelBytes),
|
||||
pitch,
|
||||
f0Method,
|
||||
indexRate,
|
||||
protect,
|
||||
};
|
||||
if (hasIndex) {
|
||||
const indexBytes = Buffer.from(await (index as File).arrayBuffer());
|
||||
fs.writeFileSync(path.join(folder, `${id}.index`), indexBytes);
|
||||
rvc.index = `rvc/${id}/${id}.index`;
|
||||
rvc.indexSha256 = sha(indexBytes);
|
||||
}
|
||||
const description = text("description");
|
||||
catalog.voices.push({ id, name, baseVoice, ...(description ? { description } : {}), source, license, rvc });
|
||||
writeUserCatalog(catalog);
|
||||
await reloadService();
|
||||
return { id };
|
||||
}
|
||||
|
||||
const CLONE_AUDIO_EXT = [".wav", ".mp3", ".ogg", ".m4a", ".flac", ".webm", ".opus"];
|
||||
const MAX_CLONE_BYTES = 30 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Voz clonada: grava a referência em models/clone/<id>/ (com sha256) e registra no user-voices.json.
|
||||
* Exige consentimento explícito: a pessoa da gravação autorizou o uso da voz.
|
||||
*/
|
||||
export async function addCloneVoice(form: FormData): Promise<{ id: string }> {
|
||||
if (!cloneInstalled()) throw new UserError("A clonagem não está instalada: rode setup.bat -Clone e reinicie o start.bat.");
|
||||
const text = (key: string) => String(form.get(key) ?? "").trim();
|
||||
const name = text("name");
|
||||
const source = text("source");
|
||||
const gender = text("gender");
|
||||
if (name.length < 2 || name.length > 60) throw new UserError("Nome precisa ter entre 2 e 60 caracteres.");
|
||||
if (!source) throw new UserError("Diga de quem é a voz e de onde veio a gravação.");
|
||||
if (form.get("consent") !== "on") throw new UserError("Confirme que a pessoa da gravação autorizou o uso da voz.");
|
||||
if (gender !== "female" && gender !== "male") throw new UserError("Escolha se a voz é feminina ou masculina.");
|
||||
const exaggeration = numberIn(form.get("exaggeration"), 0.5, 0.25, 1.5, "Expressividade");
|
||||
const cfgWeight = numberIn(form.get("cfgWeight"), 0.5, 0, 1, "Ritmo");
|
||||
|
||||
const audio = form.get("audio");
|
||||
if (!(audio instanceof File) || audio.size === 0) throw new UserError("Envie a gravação da voz.");
|
||||
const ext = path.extname(audio.name).toLowerCase();
|
||||
if (!CLONE_AUDIO_EXT.includes(ext)) throw new UserError(`Formato não aceito (${CLONE_AUDIO_EXT.join(", ")}).`);
|
||||
if (audio.size > MAX_CLONE_BYTES) throw new UserError("Gravação acima de 30 MB: 10 a 30 segundos bastam.");
|
||||
if (audio.size < 30 * 1024) throw new UserError("Gravação muito curta: envie de 10 a 30 segundos de fala limpa.");
|
||||
|
||||
const catalog = readUserCatalog();
|
||||
const status = await getStatus();
|
||||
const known = new Set<string>([...catalog.voices.map((v) => v.id), ...(status.voices as { id: string }[]).map((v) => v.id)]);
|
||||
const slug = slugify(name);
|
||||
let id = `clone-${slug}`.slice(0, 48);
|
||||
if (!VOICE_ID_RE.test(id)) throw new UserError("Nome precisa ter letras ou números.");
|
||||
for (let n = 2; known.has(id); n++) id = `clone-${slug.slice(0, 38)}-${n}`;
|
||||
|
||||
const bytes = Buffer.from(await audio.arrayBuffer());
|
||||
const folder = path.join(modelsDir(), "clone", id);
|
||||
fs.mkdirSync(folder, { recursive: true });
|
||||
fs.writeFileSync(path.join(folder, `reference${ext}`), bytes);
|
||||
const description = text("description");
|
||||
catalog.voices.push({
|
||||
id, name, kind: "clone", gender, ...(description ? { description } : {}), source,
|
||||
license: "Voz clonada com autorização da pessoa da gravação (registrada no painel).",
|
||||
consent: true, consentAt: new Date().toISOString(),
|
||||
clone: {
|
||||
reference: `clone/${id}/reference${ext}`,
|
||||
referenceSha256: crypto.createHash("sha256").update(bytes).digest("hex"),
|
||||
language: "pt", exaggeration, cfgWeight,
|
||||
},
|
||||
});
|
||||
writeUserCatalog(catalog);
|
||||
await reloadService();
|
||||
return { id };
|
||||
}
|
||||
|
||||
export async function removeUserVoice(id: string): Promise<void> {
|
||||
if (!VOICE_ID_RE.test(id)) throw new UserError("Voz inválida.");
|
||||
const catalog = readUserCatalog();
|
||||
if (!catalog.voices.some((v) => v.id === id)) throw new UserError("Só vozes de personagem adicionadas pelo painel podem ser removidas.");
|
||||
writeUserCatalog({ voices: catalog.voices.filter((v) => v.id !== id) });
|
||||
fs.rmSync(path.join(modelsDir(), "rvc", id), { recursive: true, force: true });
|
||||
fs.rmSync(path.join(modelsDir(), "clone", id), { recursive: true, force: true });
|
||||
await reloadService();
|
||||
}
|
||||
Reference in New Issue
Block a user