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,90 @@
|
||||
import Link from "next/link";
|
||||
import { connection } from "next/server";
|
||||
import { AccountCreateForm, AccountDetail, NetworkHandles } from "@/components/account-manager";
|
||||
import { ArrowRightIcon, PlusIcon, PublishIcon, SettingsIcon, UsersIcon } from "@/components/icons";
|
||||
import { EmptyState, LinkButton, Meta, PageHeader, cx } from "@/components/ui";
|
||||
import { listAccounts } from "@/lib/accounts";
|
||||
import { listStories } from "@/lib/stories";
|
||||
|
||||
export const metadata = { title: "Canais de publicação" };
|
||||
|
||||
/**
|
||||
* Canais de publicação (no código: accounts): lista densa à esquerda e o detalhe (ou a criação) ao lado.
|
||||
* `?account=<id>` abre o detalhe; `?new=1` abre o formulário de novo canal.
|
||||
*/
|
||||
export default async function AccountsPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
await connection();
|
||||
const sp = await searchParams;
|
||||
const accounts = listAccounts();
|
||||
const selected = sp.account ? accounts.find((a) => a.id === sp.account) : undefined;
|
||||
const creating = sp.new === "1" || (accounts.length === 0 && !sp.account);
|
||||
const stories = listStories().map((s) => ({ id: s.id, title: s.title, kind: s.kind }));
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Distribuição" title="Canais de publicação"
|
||||
description="Cada canal reúne os seus perfis no YouTube, no TikTok e no Instagram. Ligue histórias e fontes de corte a ele: o que você aprovar sai nas redes do canal."
|
||||
meta={<>
|
||||
<Meta icon={<PublishIcon size={15} />}>Fila e horários em <Link href="/publishing" className="text-fg-muted underline underline-offset-2 hover:text-fg">Publicações</Link></Meta>
|
||||
<Meta icon={<SettingsIcon size={15} />}>Apps das redes e horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
</>}
|
||||
actions={<LinkButton variant="primary" href="/accounts?new=1"><PlusIcon size={16} />Novo canal</LinkButton>} />
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(26rem,34rem)]">
|
||||
<section aria-labelledby="lista-contas" className="grid min-w-0 gap-3">
|
||||
<h2 id="lista-contas" className="sr-only">Lista de canais de publicação</h2>
|
||||
{accounts.length === 0 ? (
|
||||
<EmptyState icon={<UsersIcon />} title="Nenhum canal de publicação ainda">
|
||||
Crie o primeiro canal ao lado, conecte as redes dele e escolha quais histórias e fontes de corte ele publica.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
|
||||
<li aria-hidden="true"
|
||||
className="hidden grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)_6.5rem_1rem] gap-x-5 bg-raised/60 px-5 py-2.5 text-[0.6875rem] font-semibold tracking-[0.12em] text-fg-subtle uppercase md:grid">
|
||||
<span>Canal</span><span>Redes</span><span className="text-right">Histórias</span><span />
|
||||
</li>
|
||||
{accounts.map((a) => {
|
||||
const active = a.stories.filter((s) => s.status === "active").length;
|
||||
const current = a.id === selected?.id;
|
||||
return (
|
||||
<li key={a.id}>
|
||||
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} aria-current={current ? "true" : undefined}
|
||||
className={cx("group relative grid items-center gap-x-5 gap-y-1.5 px-5 py-3 transition-colors md:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)_6.5rem_1rem]",
|
||||
current ? "bg-raised" : "hover:bg-raised/50")}>
|
||||
<span aria-hidden="true" className={cx("absolute inset-y-2.5 left-0 w-[3px] rounded-r-full bg-accent", current ? "opacity-100" : "opacity-0")} />
|
||||
<span className="grid min-w-0 gap-0.5">
|
||||
<span className="truncate text-sm font-semibold text-fg">{a.name}</span>
|
||||
<span className="truncate text-xs text-fg-subtle">{a.niche || "sem nicho"}</span>
|
||||
</span>
|
||||
<NetworkHandles networks={a.networks} />
|
||||
<span className="text-xs text-fg-muted md:text-right">
|
||||
<span className="font-display text-base font-semibold text-fg tabular-nums">{active}</span> ativa{active === 1 ? "" : "s"}
|
||||
</span>
|
||||
<ArrowRightIcon size={16} className="text-fg-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-fg max-md:hidden" />
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Em tela estreita, o painel aberto vem antes da lista. */}
|
||||
<div className={cx("grid min-w-0 gap-6 xl:sticky xl:top-8", (creating || selected) && "max-xl:order-first")}>
|
||||
{creating ? <AccountCreateForm />
|
||||
: selected ? <AccountDetail key={selected.id} account={selected} stories={stories} />
|
||||
: sp.account ? (
|
||||
<EmptyState compact icon={<UsersIcon />} title="Canal não encontrado"
|
||||
action={<LinkButton href="/accounts">Ver todos</LinkButton>}>
|
||||
Ele pode ter sido apagado.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<EmptyState compact icon={<UsersIcon />} title="Escolha um canal">
|
||||
Abra um canal da lista para conectar as redes, ajustar como publicar e ligar histórias e fontes.
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
"use server";
|
||||
// Ações de formulário (server actions). Devolvem { error } ou { message } para o formulário.
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prepareBranches } from "@/lib/branches";
|
||||
import { addManualComments, closeDecision, decisionVotes } from "@/lib/decisions";
|
||||
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
|
||||
import { slugify } from "@/lib/paths";
|
||||
import { UserError, createEpisode, createStory, deleteStory, getEpisodeById, getStory, provisionalTitle } from "@/lib/stories";
|
||||
import { CHOICES, type Choice, type Provider, type StoryKind } from "@/lib/types";
|
||||
|
||||
export type FormState = { error?: string; message?: string } | null;
|
||||
|
||||
function failure(error: unknown): FormState {
|
||||
if (error instanceof UserError) return { error: error.message };
|
||||
console.error(error);
|
||||
return { error: "Erro interno. Veja o terminal do painel." };
|
||||
}
|
||||
|
||||
export async function createStoryAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
let id: string;
|
||||
try {
|
||||
id = createStory({
|
||||
title: String(form.get("title") ?? ""),
|
||||
id: String(form.get("id") ?? ""),
|
||||
logline: String(form.get("logline") ?? ""),
|
||||
kind: String(form.get("kind") ?? "interactive") as StoryKind,
|
||||
branchCount: Number(form.get("branchCount") ?? 2),
|
||||
}).id;
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
revalidatePath("/");
|
||||
redirect(`/stories/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Criar história com IA": o criador manda um texto (ideia, sinopse ou rascunho) e a IA monta
|
||||
* bíblia, ep01 e título. Por padrão usa o Codex (GPT) para enredo; cai para o Claude se o Codex
|
||||
* não estiver disponível. Campos: text (obrigatório), title (opcional), kind, provider ("" = automático).
|
||||
*/
|
||||
export async function createStoryFromTextAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
let target: string;
|
||||
try {
|
||||
const text = String(form.get("text") ?? "").trim();
|
||||
if (text.length < 20) throw new UserError("Escreva pelo menos uma ou duas frases sobre a história (mínimo 20 caracteres).");
|
||||
if (text.length > 20_000) throw new UserError("Texto longo demais (máx. 20 mil caracteres).");
|
||||
const kind = String(form.get("kind") ?? "interactive") as StoryKind;
|
||||
const title = String(form.get("title") ?? "").trim() || provisionalTitle(text);
|
||||
// Identificador único: título provisório + sufixo se já existir.
|
||||
const base = slugify(title) || "historia";
|
||||
let id = base;
|
||||
for (let n = 2; getStory(id); n++) id = `${base}-${n}`;
|
||||
const story = createStory({ title, id, logline: "", kind, branchCount: Number(form.get("branchCount") ?? 2) });
|
||||
// Documental é um vídeo só: sem título de episódio ("Abertura" só faz sentido numa série).
|
||||
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
|
||||
const chosen = String(form.get("provider") ?? "");
|
||||
const provider: Provider = chosen === "claude" || chosen === "codex" ? chosen : defaultProviderFor("story");
|
||||
// Modelo escolhido no formulário; vazio = padrão da tarefa (no Codex, o do config.toml). startRun valida.
|
||||
const model = String(form.get("model") ?? "") || defaultModelFor("story", provider);
|
||||
const run = startRun({
|
||||
provider, model, kind: "story", request: text,
|
||||
storyId: story.id, episodeId: ep.id,
|
||||
});
|
||||
target = `/agent?run=${run.id}`;
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
revalidatePath("/");
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
/** Exclui uma história (arquivos vão para data/trash/). Campo: storyId. Volta para a página inicial. */
|
||||
export async function deleteStoryAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
try {
|
||||
deleteStory(String(form.get("storyId") ?? ""));
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
revalidatePath("/");
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
export async function createEpisodeAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
let target: string;
|
||||
try {
|
||||
const storyId = String(form.get("storyId") ?? "");
|
||||
const parent = Number(form.get("parentEpisodeId") ?? 0) || undefined;
|
||||
const ep = createEpisode(storyId, { title: String(form.get("title") ?? ""), parentEpisodeId: parent });
|
||||
target = `/stories/${storyId}/episodes/${ep.number}`;
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
redirect(target);
|
||||
}
|
||||
|
||||
export async function addCommentsAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
try {
|
||||
const episodeId = Number(form.get("episodeId"));
|
||||
const r = addManualComments(episodeId, String(form.get("comments") ?? ""));
|
||||
revalidateEpisode(episodeId);
|
||||
return {
|
||||
message: `${r.added} comentário(s) adicionado(s)` + (r.duplicates ? `, ${r.duplicates} repetido(s) ignorado(s)` : "") +
|
||||
(r.rejected.length ? `. Linhas sem "autor: texto" ignoradas: ${r.rejected.length}` : "."),
|
||||
};
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function closeDecisionAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
try {
|
||||
const episodeId = Number(form.get("episodeId"));
|
||||
const manualWinner = String(form.get("manualWinner") ?? "");
|
||||
const d = closeDecision(episodeId, (CHOICES as string[]).includes(manualWinner)
|
||||
? { winner: manualWinner as Choice, reason: String(form.get("reason") ?? "") } : undefined);
|
||||
revalidateEpisode(episodeId);
|
||||
const votes = Object.entries(decisionVotes(d)).map(([letter, n]) => `${letter}: ${n}`).join(" × ");
|
||||
return { message: `Votação fechada: venceu ${d.winner} (${votes}, ${d.method === "manual" ? "decisão manual" : "por votos"}). A vertente vencedora entrou no caminho principal.` };
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** "Preparar vertentes": a IA escreve opções, roteiro e cena de cada vertente do próximo nível. */
|
||||
export async function prepareBranchesAction(_prev: FormState, form: FormData): Promise<FormState> {
|
||||
try {
|
||||
const episodeId = Number(form.get("episodeId"));
|
||||
const ep = prepareBranches(episodeId, { regenerate: form.get("regenerate") === "1" });
|
||||
revalidateEpisode(episodeId);
|
||||
return { message: ep.branches_status === "queued"
|
||||
? "Vertentes na fila: a IA começa assim que terminar o trabalho atual."
|
||||
: "A IA está preparando as vertentes (opções, roteiro e cena de cada uma)." };
|
||||
} catch (error) {
|
||||
return failure(error);
|
||||
}
|
||||
}
|
||||
|
||||
function revalidateEpisode(episodeId: number): void {
|
||||
const ep = getEpisodeById(episodeId);
|
||||
if (ep) revalidatePath(`/stories/${ep.story_id}/episodes/${ep.number}`);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { connection } from "next/server";
|
||||
import { AgentConsole, RunHistory, type AgentDefaults } from "@/components/agent-console";
|
||||
import { ClockIcon } from "@/components/icons";
|
||||
import { Card, PageHeader } from "@/components/ui";
|
||||
import { PREFERRED_PROVIDER, models, defaultModelFor, defaultProviderFor, getRun, listRuns, providers } from "@/lib/agents";
|
||||
import { listEpisodes, listStories } from "@/lib/stories";
|
||||
import { AGENT_KINDS, type AgentKind } from "@/lib/types";
|
||||
|
||||
export const metadata = { title: "Agente" };
|
||||
|
||||
export default async function AgentPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
await connection();
|
||||
const sp = await searchParams;
|
||||
const runId = sp.run ? Number(sp.run) : undefined;
|
||||
const viewing = runId ? getRun(runId) ?? null : null;
|
||||
const stories = listStories().map((s) => ({
|
||||
id: s.id, title: s.title, kind: s.kind,
|
||||
episodes: listEpisodes(s.id).map((e) => ({ id: e.id, number: e.number, title: e.title })),
|
||||
}));
|
||||
const kind = ((AGENT_KINDS as string[]).includes(sp.kind ?? "") ? sp.kind : viewing?.kind) as AgentKind | undefined;
|
||||
|
||||
// Agente e modelo padrão de cada tarefa (enredo e roteiro com o GPT via Codex; cai para o outro se faltar).
|
||||
const map = <T,>(fn: (k: AgentKind) => T) => Object.fromEntries(AGENT_KINDS.map((k) => [k, fn(k)])) as Record<AgentKind, T>;
|
||||
const defaults: AgentDefaults = {
|
||||
provider: map(defaultProviderFor),
|
||||
preferred: PREFERRED_PROVIDER,
|
||||
model: map((k) => ({ claude: defaultModelFor(k, "claude"), codex: defaultModelFor(k, "codex") })),
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Agentes de código" title="Console do agente"
|
||||
description="Peça uma história, um roteiro, uma cena ou um ajuste. Enredo e roteiro saem com o GPT (Codex); a cena, com o Claude. Um agente roda por vez, sempre dentro do projeto." />
|
||||
<div className="grid items-start gap-8 xl:grid-cols-[minmax(0,1fr)_20rem] 2xl:grid-cols-[minmax(0,1fr)_26rem]">
|
||||
<AgentConsole
|
||||
key={runId ?? "novo"}
|
||||
providers={providers().map((p) => ({ id: p.id, available: p.available, version: p.version, note: p.note }))}
|
||||
models={models()}
|
||||
defaults={defaults}
|
||||
stories={stories}
|
||||
initial={{
|
||||
storyId: sp.story ?? viewing?.story_id ?? undefined,
|
||||
episodeId: sp.episode ? Number(sp.episode) : viewing?.episode_id ?? undefined,
|
||||
kind, runId,
|
||||
// Pedido pronto vindo de outra página (ex.: "Peça uma cena nova ao agente" na montagem).
|
||||
request: sp.prompt?.slice(0, 2000),
|
||||
}}
|
||||
viewing={viewing}
|
||||
/>
|
||||
<Card title={<span className="flex items-center gap-2"><ClockIcon size={16} />Histórico</span>} description="Últimas 30 execuções" className="xl:sticky xl:top-8">
|
||||
<RunHistory runs={listRuns()} activeId={runId} />
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { endChannel } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/** Encerra o canal nesta conta (fica no histórico). */
|
||||
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string; channelId: string }> }) {
|
||||
try {
|
||||
const { id, channelId } = await ctx.params;
|
||||
return Response.json(endChannel(id, channelId));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { linkChannel } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/** Liga um canal de live do Clipador à conta: {channelId} (ex.: "twitch-alanzoka"). */
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = (await request.json()) as { channelId?: string };
|
||||
return Response.json(linkChannel((await ctx.params).id, String(body.channelId ?? "")));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { checkNetwork } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** Confere a conexão ("Já entrei" no modo sessão; relê o perfil na API oficial) → AccountNetwork. */
|
||||
export async function POST(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
return Response.json(await checkNetwork(id, platform));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { connectNetwork } from "@/lib/accounts";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** Começa a conexão: {mode: "official"|"session"} → {network: AccountNetwork, next: ConnectNext}. */
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
const body = await readJson<{ mode: string }>(request);
|
||||
return Response.json(await connectNetwork(id, platform, body.mode));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { networkCreatorInfo } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** TikTok oficial: {nickname, privacyOptions, maxDurationS, commentDisabled, duetDisabled, stitchDisabled}. */
|
||||
export async function GET(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
return Response.json(await networkCreatorInfo(id, platform));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { reopenNetwork } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** Modo sessão: reabre o navegador para entrar de novo → {network, next}. */
|
||||
export async function POST(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
return Response.json(await reopenNetwork(id, platform));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { disconnectNetwork, updateNetworkSettings } from "@/lib/accounts";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** Ajustes da rede no canal: {enabled?, dailyLimit?, privacy?, tiktokMode?} → AccountNetwork. */
|
||||
export async function PUT(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
return Response.json(updateNetworkSettings(id, platform, await readJson(request)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Desconecta (o Publicador apaga tokens e o perfil de navegador) → AccountView. Os ajustes da rede ficam. */
|
||||
export async function DELETE(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
return Response.json(await disconnectNetwork(id, platform));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { pasteNetworkToken } from "@/lib/accounts";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; platform: string }> };
|
||||
|
||||
/** Instagram oficial: {accessToken} vai para o cofre do Publicador → AccountNetwork (o token nunca volta). */
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, platform } = await ctx.params;
|
||||
const body = await readJson<{ accessToken: string }>(request);
|
||||
return Response.json(await pasteNetworkToken(id, platform, body.accessToken));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { linkNetwork } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/** Vincula um perfil: {platform: "tiktok"|"instagram"|"youtube", handle: "@usuario"} (simulado). */
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = (await request.json()) as { platform?: string; handle?: string };
|
||||
return Response.json(linkNetwork((await ctx.params).id, String(body.platform ?? ""), String(body.handle ?? "")));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { deleteAccount, getAccount, updateAccount } from "@/lib/accounts";
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
|
||||
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const account = getAccount((await ctx.params).id);
|
||||
return account ? Response.json(account) : Response.json({ error: "Canal de publicação não encontrado." }, { status: 404 });
|
||||
}
|
||||
|
||||
/** Edita nome, nicho, notas e regras: {name?, niche?, notes?, approvalMode?: "manual"|"auto", timing?: "now"|"best_slot", aiLabel?: "auto"|"always"|"never"}. */
|
||||
export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = await readJson<{ name: string; niche: string; notes: string; approvalMode: string; timing: string; aiLabel: string }>(request);
|
||||
return Response.json(updateAccount((await ctx.params).id, body));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apaga o canal (perfis, vínculos, fila e publicações dele saem junto; as histórias ficam). */
|
||||
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
deleteAccount((await ctx.params).id);
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { endStory } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/** Encerra a história nesta conta (fica no histórico e nas métricas). */
|
||||
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string; storyId: string }> }) {
|
||||
try {
|
||||
const { id, storyId } = await ctx.params;
|
||||
return Response.json(endStory(id, storyId));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { linkStory } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
/** Liga uma história à conta: {storyId}. Várias ativas ao mesmo tempo. */
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = (await request.json()) as { storyId?: string };
|
||||
return Response.json(linkStory((await ctx.params).id, String(body.storyId ?? "")));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createAccount, listAccounts } from "@/lib/accounts";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
return Response.json(listAccounts(), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
/** Cria uma conta: {name, niche?, notes?}. */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = (await request.json()) as { name?: string; niche?: string; notes?: string };
|
||||
return Response.json(createAccount({ name: String(body.name ?? ""), niche: body.niche, notes: body.notes }));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { cancelRun } from "@/lib/agents";
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
cancelRun(parseId((await ctx.params).id));
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Server-Sent Events: primeiro o histórico gravado, depois os eventos ao vivo.
|
||||
// Leitura do histórico e inscrição acontecem na mesma passagem síncrona; eventos novos só
|
||||
// chegam em callbacks posteriores, então nada se perde entre as duas etapas.
|
||||
import { followUpRunOf, getRun, isActive, readEvents, subscribe } from "@/lib/agents";
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
|
||||
export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
if (!getRun(id)) return Response.json({ error: "Execução não encontrada." }, { status: 404 });
|
||||
const encoder = new TextEncoder();
|
||||
let unsubscribe = () => {};
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
let closed = false;
|
||||
const send = (event: string, data: unknown) => {
|
||||
if (!closed) controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
|
||||
};
|
||||
const finish = (live: boolean) => {
|
||||
// followUpRunId: a continuação criada por uma mensagem enviada durante a execução. Só ao
|
||||
// vivo: abrir uma execução antiga do histórico não deve pular para a continuação dela.
|
||||
const run = getRun(id);
|
||||
send("end", run ? { ...run, followUpRunId: live ? followUpRunOf(id) : null } : null);
|
||||
unsubscribe();
|
||||
closed = true;
|
||||
controller.close();
|
||||
};
|
||||
readEvents(id).forEach((e) => send("event", e));
|
||||
if (!isActive(id)) return finish(false);
|
||||
unsubscribe = subscribe(id, (e) => (e === null ? finish(true) : send("event", e)));
|
||||
request.signal.addEventListener("abort", () => {
|
||||
closed = true;
|
||||
unsubscribe();
|
||||
});
|
||||
},
|
||||
cancel() {
|
||||
unsubscribe();
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" },
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Mensagem do usuário durante a execução: { text, mode: "now" | "queue" }.
|
||||
// "now" interrompe e retoma a sessão com a correção; "queue" envia quando o agente terminar.
|
||||
import { sendFollowUp } from "@/lib/agents";
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
const body = (await request.json()) as { text?: unknown; mode?: unknown };
|
||||
const mode = body.mode === "queue" ? "queue" : "now";
|
||||
sendFollowUp(id, typeof body.text === "string" ? body.text : "", mode);
|
||||
return Response.json({ ok: true, mode });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { startRun } from "@/lib/agents";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import type { AgentKind, Provider } from "@/lib/types";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = (await request.json()) as {
|
||||
provider: Provider; model?: string; kind: AgentKind; request: string;
|
||||
storyId?: string | null; episodeId?: number | null; resumeRunId?: number | null;
|
||||
};
|
||||
const run = startRun({ ...body, model: body.model ?? "" });
|
||||
return Response.json({ id: run.id });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { promoteAsset } from "@/lib/assets";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
return Response.json(promoteAsset((await ctx.params).id));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createAsset } from "@/lib/assets";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import type { AssetKind } from "@/lib/types";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const form = await request.formData();
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo." }, { status: 400 });
|
||||
const text = (key: string) => String(form.get(key) ?? "");
|
||||
const asset = await createAsset({
|
||||
file,
|
||||
name: text("name"),
|
||||
kind: text("kind") as AssetKind,
|
||||
scope: text("scope") === "story" ? "story" : "library",
|
||||
storyId: text("storyId") || undefined,
|
||||
license: text("license"),
|
||||
source: text("source"),
|
||||
notes: text("notes"),
|
||||
});
|
||||
return Response.json(asset);
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { proxy } from "@/lib/clipper";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ path: string[] }> };
|
||||
|
||||
/** Repassa a página /clipper ao serviço do Clipador (lista de caminhos permitidos em lib/clipper.ts). */
|
||||
async function handle(request: Request, ctx: Ctx): Promise<Response> {
|
||||
try {
|
||||
return await proxy(request, (await ctx.params).path);
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export { handle as GET, handle as POST, handle as PATCH, handle as PUT, handle as DELETE };
|
||||
@@ -0,0 +1,23 @@
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
import { collectMetrics, isCollecting, listMetricSyncs } from "@/lib/metrics-sync";
|
||||
|
||||
/** Última leitura dos números de cada rede de cada canal (e se há uma leitura em andamento). */
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const accountId = new URL(request.url).searchParams.get("accountId") || undefined;
|
||||
return Response.json({ running: isCollecting(), syncs: listMetricSyncs(accountId) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** "Atualizar números": lê agora todos os posts publicados (do canal, se vier `accountId`). Pode levar minutos. */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = (await readJson(request).catch(() => ({}))) as { accountId?: unknown };
|
||||
const accountId = typeof body.accountId === "string" && body.accountId ? body.accountId : undefined;
|
||||
return Response.json(await collectMetrics({ accountId, force: true }));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { dashboard } from "@/lib/metrics";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Totais e desempenho (por rede, conta, história e episódio). `?account=<id>` filtra por conta. */
|
||||
export async function GET(request: Request) {
|
||||
const account = new URL(request.url).searchParams.get("account") || undefined;
|
||||
return Response.json(dashboard({ accountId: account }), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { clearSimulated, simulateMetrics } from "@/lib/metrics";
|
||||
|
||||
/** Gera publicações e métricas SIMULADAS para as contas e histórias vinculadas (selo "simulado"). */
|
||||
export async function POST() {
|
||||
try {
|
||||
return Response.json(simulateMetrics());
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apaga todos os dados simulados (os reais ficam). */
|
||||
export async function DELETE() {
|
||||
try {
|
||||
return Response.json({ removed: clearSimulated() });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { errorResponse, parseId, readJson } from "@/lib/http";
|
||||
import { approveEpisode, episodeApproval, unapproveEpisode } from "@/lib/publishing";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
/** Estado da aprovação: renders finais possíveis, título/legenda, canais que recebem e jobs. */
|
||||
export async function GET(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
return Response.json(episodeApproval(parseId((await ctx.params).id)), { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** "Aprovar para publicar": {renderId, title, caption} → EpisodeApproval (cria/atualiza os jobs). */
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
return Response.json(approveEpisode(parseId((await ctx.params).id), await readJson(request)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Desfaz a aprovação (cancela o que ainda não saiu). */
|
||||
export async function DELETE(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
return Response.json(await unapproveEpisode(parseId((await ctx.params).id)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { prepareBranches } from "@/lib/branches";
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
|
||||
/** Prepara (ou refaz, com {"regenerate": true}) as vertentes do próximo nível de um episódio. */
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = (await request.json().catch(() => ({}))) as { regenerate?: boolean };
|
||||
const ep = prepareBranches(parseId((await ctx.params).id), { regenerate: body.regenerate === true });
|
||||
return Response.json({ episodeId: ep.id, branchesStatus: ep.branches_status, runId: ep.branches_run_id });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// "Gerar de novo" de um trecho ({ index }): outra variação da cena do Godot ou outra imagem da internet.
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { regenerateShot } from "@/lib/montage";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
const body = (await request.json()) as { index?: unknown; target?: unknown };
|
||||
const target = body.target === "inset" || body.target === "remove-inset" ? body.target : "visual";
|
||||
return Response.json({ montage: await regenerateShot(id, Number(body.index), target) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// POST começa a montagem do MP4 ({ auto: true } = um clique: plano, narração, cenas 2D e montagem);
|
||||
// DELETE ?render=<id> cancela a que está em andamento.
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { cancelMontageRender, startMontageRender } from "@/lib/montage";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const body = (await request.json().catch(() => ({}))) as { auto?: unknown; replan?: unknown };
|
||||
return Response.json(startMontageRender(parseId((await ctx.params).id), { auto: body.auto === true, replan: body.replan === true }));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
cancelMontageRender(parseId(new URL(request.url).searchParams.get("render") ?? ""));
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Montagem documental: GET devolve o estado (trechos, áudios, visuais, opções e montagens);
|
||||
// PATCH ajusta voz, velocidade, legenda e, por trecho, o texto falado e o visual.
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { VISUAL_KINDS, listMontageRenders, loadMontage, montageJob, updateMontage, visualOptions } from "@/lib/montage";
|
||||
import { DOC2D_TEMPLATES } from "@/lib/montage-godot";
|
||||
import { listLibrary } from "@/lib/scene-library";
|
||||
import { getEpisodeById } from "@/lib/stories";
|
||||
|
||||
function state(id: number) {
|
||||
return { storyId: getEpisodeById(id)?.story_id ?? "", montage: loadMontage(id), kinds: VISUAL_KINDS, templates: DOC2D_TEMPLATES, library: listLibrary(), options: visualOptions(id), renders: listMontageRenders(id), job: montageJob(id) };
|
||||
}
|
||||
|
||||
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
return Response.json(state(parseId((await ctx.params).id)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
updateMontage(id, await request.json());
|
||||
return Response.json(state(id));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Renderiza no Godot a cena 2D de UM trecho ({ index }), para ver antes de montar o vídeo.
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { renderShotScene } from "@/lib/montage";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
const body = (await request.json()) as { index?: unknown };
|
||||
return Response.json({ montage: await renderShotScene(id, Number(body.index)) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Envia a imagem ou o clipe de um trecho (multipart: file, index, credit, license, sourceUrl).
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { uploadShotVisual } from "@/lib/montage";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const id = parseId((await ctx.params).id);
|
||||
const form = await request.formData();
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo." }, { status: 400 });
|
||||
const text = (key: string) => String(form.get(key) ?? "");
|
||||
const montage = await uploadShotVisual(id, Number(text("index")), {
|
||||
file, credit: text("credit"), license: text("license"), sourceUrl: text("sourceUrl"),
|
||||
});
|
||||
return Response.json({ montage });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { startRender } from "@/lib/renders";
|
||||
|
||||
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { profile } = (await request.json()) as { profile?: string };
|
||||
if (profile !== "preview" && profile !== "final") return Response.json({ error: "Perfil inválido." }, { status: 400 });
|
||||
const job = startRender(parseId((await ctx.params).id), profile);
|
||||
return Response.json(job);
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Entrega arquivos do repositório ao navegador (vídeos, imagens, roteiros, assets),
|
||||
// só de output/, stories/ e assets/. Suporta Range para o player de vídeo.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { SERVABLE_ROOTS, resolveInside } from "@/lib/paths";
|
||||
|
||||
const TYPES: Record<string, string> = {
|
||||
".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mkv": "video/x-matroska", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
|
||||
".md": "text/markdown; charset=utf-8", ".json": "application/json; charset=utf-8", ".txt": "text/plain; charset=utf-8",
|
||||
".wav": "audio/wav", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".glb": "model/gltf-binary", ".gltf": "model/gltf+json",
|
||||
};
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const rel = new URL(request.url).searchParams.get("path") ?? "";
|
||||
const full = rel ? resolveInside(rel, SERVABLE_ROOTS) : null;
|
||||
if (!full || !fs.existsSync(full) || !fs.statSync(full).isFile()) {
|
||||
return Response.json({ error: "Arquivo não encontrado ou fora das pastas permitidas." }, { status: 404 });
|
||||
}
|
||||
const size = fs.statSync(full).size;
|
||||
const type = TYPES[path.extname(full).toLowerCase()] ?? "application/octet-stream";
|
||||
const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get("range") ?? "");
|
||||
if (range) {
|
||||
const start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]));
|
||||
const end = range[1] && range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;
|
||||
if (start >= size || start > end) {
|
||||
return new Response(null, { status: 416, headers: { "Content-Range": `bytes */${size}` } });
|
||||
}
|
||||
const stream = Readable.toWeb(fs.createReadStream(full, { start, end })) as ReadableStream;
|
||||
return new Response(stream, {
|
||||
status: 206,
|
||||
headers: { "Content-Type": type, "Content-Length": String(end - start + 1), "Content-Range": `bytes ${start}-${end}/${size}`, "Accept-Ranges": "bytes", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
const stream = Readable.toWeb(fs.createReadStream(full)) as ReadableStream;
|
||||
return new Response(stream, {
|
||||
headers: { "Content-Type": type, "Content-Length": String(size), "Accept-Ranges": "bytes", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { publisherStatus } from "@/lib/publisher";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Saúde do Publicador sem falhar: {online: true, browser: {found, kind, path}, worker, queue}
|
||||
* ou {online: false, reason}.
|
||||
*/
|
||||
export async function GET() {
|
||||
return Response.json(await publisherStatus(), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { errorResponse, parseId, readJson } from "@/lib/http";
|
||||
import { publishClip } from "@/lib/publishing";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* POST /api/publishing/clips/[id] — "Publicar" no cartão de um corte aprovado do Clipador.
|
||||
* Corpo (JSON): {accountId, platforms: ["youtube"|"tiktok"|"instagram"], timing?: "now"|"best_slot"}.
|
||||
* → {jobs, skipped: [{platform, reason}], placed}. Não precisa da fonte ligada ao canal (jobs com origem manual).
|
||||
*/
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id } = await ctx.params;
|
||||
const body = await readJson<{ accountId: string; platforms: string[]; timing: string }>(request);
|
||||
return Response.json(await publishClip(parseId(id), body));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { errorResponse, isJsonRequest, parseId, readJson } from "@/lib/http";
|
||||
import { approveJob, cancelPublishJob, markPublished, markRemoved, publishNow, retryJob } from "@/lib/publishing";
|
||||
import type { PublishJob } from "@/lib/types";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string; action: string }> };
|
||||
type Body = { confirm?: unknown; url?: unknown };
|
||||
|
||||
const ACTIONS: Record<string, (id: number, body: Body) => PublishJob | Promise<PublishJob>> = {
|
||||
approve: (id) => approveJob(id),
|
||||
"publish-now": (id) => publishNow(id),
|
||||
retry: (id, body) => retryJob(id, body),
|
||||
cancel: (id) => cancelPublishJob(id),
|
||||
"mark-published": (id, body) => markPublished(id, body),
|
||||
removed: (id) => markRemoved(id),
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/publishing/jobs/[id]/(approve|publish-now|retry|cancel|mark-published) → PublishJob. Corpo opcional (JSON):
|
||||
* `retry` aceita {confirm: true} — exigido quando o job tem `mayBeLive` (senão 409 com a mensagem para confirmar);
|
||||
* `mark-published` exige {url} — o link do vídeo na rede ("Já saiu: informar o link");
|
||||
* `removed` — você apagou o vídeo na rede: libera a rede para publicar de novo ("Apaguei na rede").
|
||||
*/
|
||||
export async function POST(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const { id, action } = await ctx.params;
|
||||
const handler = ACTIONS[action];
|
||||
if (!handler) return Response.json({ error: "Ação desconhecida." }, { status: 404 });
|
||||
const body = isJsonRequest(request) ? await readJson<{ confirm: boolean; url: string }>(request) : {};
|
||||
return Response.json(await handler(parseId(id), body));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { errorResponse, parseId, readJson } from "@/lib/http";
|
||||
import { getJobView, updateJob } from "@/lib/publishing";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const job = getJobView(parseId((await ctx.params).id));
|
||||
return job ? Response.json(job) : Response.json({ error: "Publicação não encontrada." }, { status: 404 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Muda horário, título ou legenda: {scheduledAt?: ISO, title?, caption?} → PublishJob. */
|
||||
export async function PATCH(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
return Response.json(updateJob(parseId((await ctx.params).id), await readJson(request)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { listJobs } from "@/lib/publishing";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Fila de publicação: ?status=a,b&accountId=&sourceKind=clip|episode&sourceId=&limit= → PublishJob[]. */
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const q = new URL(request.url).searchParams;
|
||||
const status = (q.get("status") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
||||
return Response.json(listJobs({
|
||||
status, accountId: q.get("accountId") || undefined, sourceKind: q.get("sourceKind") || undefined,
|
||||
sourceId: q.get("sourceId") || undefined, limit: q.get("limit") ? Number(q.get("limit")) : undefined,
|
||||
}), { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { publishingSummary } from "@/lib/publishing";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Contagens da fila por estado (menu e dashboard) e saúde do despachante. */
|
||||
export async function GET() {
|
||||
try {
|
||||
return Response.json(publishingSummary(), { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { errorResponse, parseId } from "@/lib/http";
|
||||
import { cancelRender, getRender } from "@/lib/renders";
|
||||
|
||||
/** Estado do render (o painel consulta a cada poucos segundos enquanto roda). */
|
||||
export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const job = getRender(parseId((await ctx.params).id));
|
||||
return job ? Response.json(job) : Response.json({ error: "Render não encontrado." }, { status: 404 });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancela o render em andamento. */
|
||||
export async function DELETE(_request: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
cancelRender(parseId((await ctx.params).id));
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
import { deleteApp, getApps, putApp } from "@/lib/publisher";
|
||||
import { mustPlatform } from "@/lib/publishing";
|
||||
import { UserError } from "@/lib/stories";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Ctx = { params: Promise<{ platform: string }> };
|
||||
|
||||
/** Estado do app de uma rede: {configured, clientId, redirectUri, notes} (o segredo nunca volta). */
|
||||
export async function GET(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const platform = mustPlatform((await ctx.params).platform);
|
||||
return Response.json((await getApps())[platform], { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Grava o app da rede no cofre do Publicador: {clientId, clientSecret} (no Instagram o secret é opcional). Resposta sem o segredo. */
|
||||
export async function PUT(request: Request, ctx: Ctx) {
|
||||
try {
|
||||
const platform = mustPlatform((await ctx.params).platform);
|
||||
const body = await readJson<{ clientId: string; clientSecret: string }>(request);
|
||||
const clientId = typeof body.clientId === "string" ? body.clientId.trim() : "";
|
||||
const clientSecret = typeof body.clientSecret === "string" ? body.clientSecret.trim() : "";
|
||||
if (!clientId || clientId.length > 512) throw new UserError("Preencha o Client ID.");
|
||||
if (clientSecret.length > 1024) throw new UserError("Client Secret longo demais.");
|
||||
if (!clientSecret && platform !== "instagram") throw new UserError("Preencha o Client Secret.");
|
||||
return Response.json(await putApp(platform, { clientId, clientSecret: clientSecret || undefined }));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apaga o app da rede do cofre do Publicador. */
|
||||
export async function DELETE(_request: Request, ctx: Ctx) {
|
||||
try {
|
||||
return Response.json(await deleteApp(mustPlatform((await ctx.params).platform)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { getApps } from "@/lib/publisher";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Apps das três redes no Publicador: {youtube, tiktok, instagram} com {configured, clientId, redirectUri, notes}. Sem segredo. */
|
||||
export async function GET() {
|
||||
try {
|
||||
return Response.json(await getApps(), { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { errorResponse, readJson } from "@/lib/http";
|
||||
import { getSettings, updateSettings } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Configurações gerais: {publishingPaused, slots: {youtube: ["12:00", ...], ...}, timezone}. */
|
||||
export async function GET() {
|
||||
try {
|
||||
return Response.json(getSettings(), { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Atualiza só o que vier: {publishingPaused?, slots?: {<rede>?: ["HH:MM", ...]}, timezone?}. */
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
return Response.json(updateSettings(await readJson(request)));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { storyFlow } from "@/lib/flow";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Árvore da história (nós e arestas) para o editor de fluxo. */
|
||||
export async function GET(_request: Request, ctx: { params: Promise<{ storyId: string }> }) {
|
||||
const flow = storyFlow((await ctx.params).storyId);
|
||||
if (!flow) return Response.json({ error: "História não encontrada." }, { status: 404 });
|
||||
return Response.json(flow, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Criar história com IA pela API (o mesmo que o formulário "Nova história com IA"): cria a história
|
||||
// e o primeiro episódio e põe o agente para escrever. { text, title?, kind?, provider?, model? }
|
||||
// → { storyId, episodeId, runId }. Útil para automação (o coordenador dispara o agente do painel).
|
||||
import { defaultModelFor, defaultProviderFor, startRun } from "@/lib/agents";
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { slugify } from "@/lib/paths";
|
||||
import { UserError, createEpisode, createStory, getStory, provisionalTitle } from "@/lib/stories";
|
||||
import { STORY_KINDS, type Provider, type StoryKind } from "@/lib/types";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = (await request.json()) as { text?: unknown; title?: unknown; kind?: unknown; provider?: unknown; model?: unknown };
|
||||
const text = String(body.text ?? "").trim();
|
||||
if (text.length < 20) throw new UserError("Escreva pelo menos uma ou duas frases (mínimo 20 caracteres).");
|
||||
if (text.length > 20_000) throw new UserError("Texto longo demais (máx. 20 mil caracteres).");
|
||||
const kind = (STORY_KINDS as string[]).includes(String(body.kind)) ? (body.kind as StoryKind) : "documentary";
|
||||
const title = String(body.title ?? "").trim() || provisionalTitle(text);
|
||||
const base = slugify(title) || "historia";
|
||||
let id = base;
|
||||
for (let n = 2; getStory(id); n++) id = `${base}-${n}`;
|
||||
const story = createStory({ title, id, logline: "", kind, branchCount: 2 });
|
||||
const ep = createEpisode(story.id, { title: kind === "documentary" ? "" : "Abertura" });
|
||||
const provider: Provider = body.provider === "claude" || body.provider === "codex" ? body.provider : defaultProviderFor("story");
|
||||
const model = String(body.model ?? "") || defaultModelFor("story", provider);
|
||||
const run = startRun({ provider, model, kind: "story", request: text, storyId: story.id, episodeId: ep.id });
|
||||
return Response.json({ storyId: story.id, episodeId: ep.id, runId: run.id });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { updateAzure } from "@/lib/voice";
|
||||
|
||||
/** Grava região e chave do Azure Speech no voice/.env (o pnpm dev reinicia o serviço sozinho). A chave não volta. */
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
updateAzure(await request.json());
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { addCloneVoice } from "@/lib/voice";
|
||||
|
||||
/** Clona uma voz a partir de uma gravação (10–30 s), com consentimento registrado. */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
return Response.json(await addCloneVoice(await request.formData()));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { updateSettings } from "@/lib/voice";
|
||||
|
||||
/** Grava dispositivo, modelo do Whisper e RVC no voice/.env (o pnpm dev reinicia o serviço sozinho). */
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
const result = updateSettings(await request.json());
|
||||
return Response.json({ ok: true, ...result });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { getStatus } from "@/lib/voice";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Estado do serviço de voz + vozes + configurações (nunca falha: offline vira `online: false`). */
|
||||
export async function GET() {
|
||||
return Response.json(await getStatus(), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { synthesize } from "@/lib/voice";
|
||||
|
||||
/** Gera a fala (OGG/Opus) para ouvir no painel. */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
return await synthesize(await request.json());
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { transcribe } from "@/lib/voice";
|
||||
|
||||
/** Transcreve um áudio enviado (texto, frases ou palavras com tempo) e devolve o .srt quando há tempos. */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const form = await request.formData();
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File)) return Response.json({ error: "Envie um arquivo de áudio." }, { status: 400 });
|
||||
return Response.json(await transcribe(file, String(form.get("language") ?? "pt-BR"), String(form.get("detail") ?? "segments")));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { removeUserVoice } from "@/lib/voice";
|
||||
|
||||
/** Remove uma voz de personagem adicionada pelo painel (as vozes base não saem). */
|
||||
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
await removeUserVoice((await params).id);
|
||||
return Response.json({ ok: true });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { errorResponse } from "@/lib/http";
|
||||
import { addUserVoice } from "@/lib/voice";
|
||||
|
||||
/** Adiciona uma voz de personagem: voz base + modelo RVC (.pth e .index opcional). */
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
return Response.json(await addUserVoice(await request.formData()));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { connection } from "next/server";
|
||||
import { AssetTable } from "@/components/asset-table";
|
||||
import { AssetUpload } from "@/components/asset-upload";
|
||||
import { FilmIcon, LibraryIcon, UploadIcon } from "@/components/icons";
|
||||
import { Card, Meta, PageHeader, SectionHeader } from "@/components/ui";
|
||||
import { ASSET_KINDS, listAssets } from "@/lib/assets";
|
||||
import { listStories } from "@/lib/stories";
|
||||
|
||||
export const metadata = { title: "Assets" };
|
||||
|
||||
export default async function AssetsPage() {
|
||||
await connection();
|
||||
const stories = listStories();
|
||||
const library = listAssets({ scope: "library" });
|
||||
const perStory = listAssets({ scope: "story" });
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Recursos" title="Assets"
|
||||
description="Modelos, texturas, fundos e áudios. A biblioteca serve a qualquer história; os exclusivos ficam na pasta da história e podem ser promovidos."
|
||||
meta={<>
|
||||
<Meta icon={<LibraryIcon size={15} />}>{library.length} na biblioteca · <code>assets/library/</code></Meta>
|
||||
<Meta icon={<FilmIcon size={15} />}>{perStory.length} em histórias · <code>stories/<história>/assets/</code></Meta>
|
||||
</>} />
|
||||
|
||||
<section aria-labelledby="biblioteca" className="grid gap-5">
|
||||
<SectionHeader id="biblioteca" eyebrow="Compartilhada" title="Biblioteca" />
|
||||
<AssetTable assets={library} />
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="por-historia" className="grid gap-5">
|
||||
<SectionHeader id="por-historia" eyebrow="Exclusivos" title="Assets das histórias"
|
||||
description="Cada asset tem um asset.json com licença, origem e metadados; escala, orientação e capacidades ficam “a definir” até o asset ser testado num render." />
|
||||
<AssetTable assets={perStory} showStory />
|
||||
</section>
|
||||
|
||||
<Card eyebrow={<><UploadIcon size={13} />Envio</>} title="Enviar asset" description="O arquivo vai para a biblioteca ou para a pasta da história escolhida.">
|
||||
<AssetUpload stories={stories.map((s) => ({ id: s.id, title: s.title }))} kinds={ASSET_KINDS} />
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ClipEditor } from "@/components/clip-editor";
|
||||
|
||||
export const metadata = { title: "Editor de corte" };
|
||||
|
||||
/**
|
||||
* Editor de cortes do Clipador: prévia 9:16, transcrição clicável, timeline com forma de onda e chat, legenda
|
||||
* animada, gancho, zoom, narração e exportação. Tudo é buscado no navegador (/api/clipper/clips/<id>/edit…).
|
||||
*/
|
||||
export default async function ClipEditPage({ params }: { params: Promise<{ clipId: string }> }) {
|
||||
const { clipId } = await params;
|
||||
const id = Number(clipId);
|
||||
if (!Number.isInteger(id) || id <= 0) notFound();
|
||||
return <ClipEditor clipId={id} />;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { connection } from "next/server";
|
||||
import type { ChannelAccounts } from "@/components/clipper-channels";
|
||||
import { ClipperStudio } from "@/components/clipper-studio";
|
||||
import Link from "next/link";
|
||||
import { BroadcastIcon, PublishIcon, ScissorsIcon, SparkIcon } from "@/components/icons";
|
||||
import { Meta, PageHeader } from "@/components/ui";
|
||||
import { listAccounts } from "@/lib/accounts";
|
||||
|
||||
export const metadata = { title: "Clipador" };
|
||||
|
||||
/**
|
||||
* Clipador: cortes automáticos de lives (Twitch, YouTube, Kick). O estado muda a cada segundo
|
||||
* (gravação, IA, render), então a página busca /api/clipper/* no navegador e consulta de novo
|
||||
* enquanto houver trabalho. Do servidor vem só em quais canais de publicação cada fonte está ligada.
|
||||
*/
|
||||
export default async function ClipperPage() {
|
||||
await connection();
|
||||
const channelAccounts: ChannelAccounts = {};
|
||||
for (const account of listAccounts()) {
|
||||
for (const link of account.channels) {
|
||||
if (link.status !== "active") continue;
|
||||
(channelAccounts[link.channel_id] ??= []).push({ id: account.id, name: account.name });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Cortes de live" title="Clipador"
|
||||
description="Grava lives de terceiros, acha os picos de reação do chat, pede o veredito da IA e entrega cortes verticais com legenda, prontos para você aprovar."
|
||||
meta={<>
|
||||
<Meta icon={<BroadcastIcon size={15} />}>Twitch, YouTube e Kick</Meta>
|
||||
<Meta icon={<SparkIcon size={15} />}>Juiz: Codex ou Claude pela CLI</Meta>
|
||||
<Meta icon={<ScissorsIcon size={15} />}>MP4 1080×1920 com legenda</Meta>
|
||||
<Meta icon={<PublishIcon size={15} />}>Cortes aprovados saem nas redes dos <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">canais de publicação</Link></Meta>
|
||||
</>} />
|
||||
<ClipperStudio channelAccounts={channelAccounts} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { connection } from "next/server";
|
||||
import { DashboardFilter, MetricsSyncControls, SimulatedControls } from "@/components/dashboard-controls";
|
||||
import {
|
||||
AlertIcon, ChartIcon, CheckIcon, EyeIcon, FilmIcon, HeartIcon, LinkIcon, PlayIcon, SendIcon, TrendDownIcon, TrophyIcon, UsersIcon,
|
||||
} from "@/components/icons";
|
||||
import { DailyViewsChart, Kpi, MetricTable, VideoTable, type MetricRow } from "@/components/metrics-view";
|
||||
import { PLATFORM_META } from "@/components/platforms";
|
||||
import { Card, LinkButton, PageHeader, cx, formatCompact, formatInteger, formatPercent } from "@/components/ui";
|
||||
import { listAccounts } from "@/lib/accounts";
|
||||
import { dashboard, type Dashboard } from "@/lib/metrics";
|
||||
import { getSettings } from "@/lib/settings";
|
||||
|
||||
export const metadata = { title: "Dashboard" };
|
||||
|
||||
/** Número do episódio a partir da chave de arquivo (ep02, ep02-b → 2), para o link da página do episódio. */
|
||||
function episodeNumber(fileKey: string): number | null {
|
||||
const m = /^ep(\d+)/i.exec(fileKey);
|
||||
return m ? Number(m[1]) : null;
|
||||
}
|
||||
|
||||
export default async function DashboardPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
await connection();
|
||||
const sp = await searchParams;
|
||||
const accounts = listAccounts();
|
||||
const accountId = sp.account && accounts.some((a) => a.id === sp.account) ? sp.account : "";
|
||||
const data = dashboard({ accountId: accountId || undefined });
|
||||
const empty = data.totals.publications === 0;
|
||||
const accountName = accounts.find((a) => a.id === accountId)?.name;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Desempenho" title="Dashboard"
|
||||
description={accountName
|
||||
? <>O que funciona e o que não no canal <strong className="font-semibold text-fg">{accountName}</strong>.</>
|
||||
: "O que funciona e o que não: views de cada vídeo, engajamento por rede, canal de publicação, história e episódio."}
|
||||
meta={data.simulated ? <SimulatedSeal /> : undefined}
|
||||
actions={accounts.length > 0 && <DashboardFilter accounts={accounts.map((a) => ({ id: a.id, name: a.name }))} value={accountId} />} />
|
||||
|
||||
{data.simulated && (
|
||||
<div role="note" className="flex flex-wrap items-center justify-between gap-4 rounded-card border border-warning/35 bg-warning-soft px-5 py-4">
|
||||
<p className="flex max-w-[75ch] items-start gap-3 text-sm text-fg">
|
||||
<AlertIcon size={18} className="mt-0.5 text-warning" />
|
||||
<span><strong className="font-semibold text-warning">Dados simulados.</strong> Parte dos números abaixo é de exemplo, gerada no painel (não veio das redes). Apague os simulados antes de tomar decisões com eles.</span>
|
||||
</p>
|
||||
<SimulatedControls simulated />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!empty && (
|
||||
<MetricsSyncControls syncs={data.syncs} accountId={accountId || undefined} everyHours={getSettings().metricsEveryHours}
|
||||
showAccount={!accountId && accounts.length > 1} />
|
||||
)}
|
||||
|
||||
{empty ? <EmptyDashboard data={data} filtered={!!accountId} /> : <DashboardBody data={data} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SimulatedSeal() {
|
||||
return (
|
||||
<span className="inline-flex h-7 items-center gap-2 rounded-full border border-warning/50 bg-warning-soft px-3 text-xs font-bold tracking-[0.08em] text-warning uppercase">
|
||||
<AlertIcon size={14} />Dados simulados
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardBody({ data }: { data: Dashboard }) {
|
||||
const t = data.totals;
|
||||
const best = data.byEpisode.slice(0, Math.min(5, Math.ceil(data.byEpisode.length / 2)));
|
||||
const worst = data.byEpisode.slice(best.length).slice(-5).reverse();
|
||||
const episodeRow = (e: Dashboard["byEpisode"][number]): MetricRow => {
|
||||
const n = episodeNumber(e.fileKey);
|
||||
return {
|
||||
key: String(e.episodeId), totals: e,
|
||||
label: <><span className="font-mono text-xs text-fg-subtle">{e.fileKey.toUpperCase()}</span> {e.title || "Sem título"}</>,
|
||||
sub: e.storyTitle,
|
||||
href: n ? `/stories/${e.storyId}/episodes/${n}` : `/stories/${e.storyId}`,
|
||||
};
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section aria-labelledby="kpis">
|
||||
<h2 id="kpis" className="sr-only">Totais</h2>
|
||||
<dl className="grid grid-cols-2 gap-3 md:grid-cols-3 2xl:grid-cols-6">
|
||||
<Kpi emphasis icon={<EyeIcon size={14} />} label="Views" value={formatCompact(t.views)} hint={`${formatInteger(t.views)} no total`} />
|
||||
<Kpi icon={<HeartIcon size={14} />} label="Engajamento" value={formatPercent(t.engagementRate)}
|
||||
hint={`${formatCompact(t.likes + t.comments + t.shares + t.saves)} interações`} />
|
||||
<Kpi icon={<PlayIcon size={14} />} label="Conclusão" value={formatPercent(t.completionRate)} hint="assistiram até o fim" />
|
||||
<Kpi icon={<SendIcon size={14} />} label="Publicações" value={formatInteger(t.publications)} hint={`${data.byVideo.length} vídeo${data.byVideo.length === 1 ? "" : "s"}`} />
|
||||
<Kpi icon={<UsersIcon size={14} />} label="Canais" value={formatInteger(data.counts.accounts)} hint={`${data.counts.networks} redes vinculadas`} />
|
||||
<Kpi icon={<FilmIcon size={14} />} label="Histórias ativas" value={formatInteger(data.counts.activeStories)} hint={`de ${data.counts.stories}`} />
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<Card eyebrow={<><EyeIcon size={13} />Views</>} title="Views de cada vídeo"
|
||||
description="Somadas as redes em que o vídeo saiu. Clique no número de uma rede para abrir o post.">
|
||||
<VideoTable videos={data.byVideo} />
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
|
||||
<Card eyebrow={<><ChartIcon size={13} />Alcance</>} title="Views por dia" description="Pelo dia da publicação (últimos 30 dias com dado).">
|
||||
<DailyViewsChart daily={data.daily} />
|
||||
</Card>
|
||||
<Card title="Por rede" description="Onde as histórias rendem mais.">
|
||||
<MetricTable caption="Desempenho por rede" firstColumn="Rede"
|
||||
rows={data.byPlatform.slice().sort((a, b) => b.views - a.views).map((p) => {
|
||||
const meta = PLATFORM_META[p.platform];
|
||||
const Icon = meta.icon;
|
||||
return { key: p.platform, totals: p, label: <span className="inline-flex items-center gap-2"><Icon size={15} className="text-fg-subtle" />{meta.label}</span> };
|
||||
})} />
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{data.byEpisode.length > 0 && <div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-2">
|
||||
<Card title="Melhores episódios" eyebrow={<><TrophyIcon size={13} />Maior engajamento</>}
|
||||
description="O que repetir: tom, gancho e escolhas desses episódios.">
|
||||
<MetricTable caption="Melhores episódios por engajamento" firstColumn="Episódio" rows={best.map(episodeRow)} />
|
||||
</Card>
|
||||
<Card title="Piores episódios" eyebrow={<span className="inline-flex items-center gap-2 text-danger"><TrendDownIcon size={13} />Menor engajamento</span>}
|
||||
description="O que rever antes do próximo." >
|
||||
<MetricTable caption="Piores episódios por engajamento" firstColumn="Episódio" rows={worst.map(episodeRow)}
|
||||
empty="Poucos episódios publicados para comparar." />
|
||||
</Card>
|
||||
</div>}
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-6 2xl:grid-cols-2">
|
||||
<Card title="Por canal de publicação">
|
||||
<MetricTable caption="Desempenho por canal de publicação" firstColumn="Canal"
|
||||
rows={data.byAccount.map((a) => ({ key: a.accountId, totals: a, label: a.name, href: `/accounts?account=${encodeURIComponent(a.accountId)}` }))} />
|
||||
</Card>
|
||||
{data.byStory.length > 0 && <Card title="Por história">
|
||||
<MetricTable caption="Desempenho por história" firstColumn="História"
|
||||
rows={data.byStory.map((s) => ({ key: s.storyId, totals: s, label: s.title, href: `/stories/${s.storyId}` }))} />
|
||||
</Card>}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Sem publicações: diz o que falta, passo a passo, e oferece gerar dados simulados. */
|
||||
function EmptyDashboard({ data, filtered }: { data: Dashboard; filtered: boolean }) {
|
||||
const steps = [
|
||||
{ done: data.counts.accounts > 0, label: "Crie um canal de publicação", hint: "Em Canais de publicação, “Novo canal”." },
|
||||
{ done: data.counts.networks > 0, label: "Vincule uma rede", hint: "Conecte TikTok, Instagram ou YouTube." },
|
||||
{ done: data.counts.activeStories > 0, label: "Vincule uma história", hint: "Com pelo menos um episódio." },
|
||||
];
|
||||
const ready = steps.every((s) => s.done);
|
||||
return (
|
||||
<section aria-labelledby="sem-dados" className="grid gap-6 rounded-card border border-dashed border-line-strong bg-sunken/30 px-6 py-10 md:px-10">
|
||||
<div className="grid max-w-[65ch] gap-2">
|
||||
<span className="grid size-12 place-items-center rounded-2xl border border-line-strong bg-raised text-accent"><ChartIcon /></span>
|
||||
<h2 id="sem-dados" className="mt-2 font-display text-title text-fg">{filtered ? "Este canal ainda não tem publicações" : "Ainda não há publicações para medir"}</h2>
|
||||
<p className="text-sm leading-relaxed text-fg-muted">
|
||||
Quando um vídeo sai numa rede, o painel lê sozinho as views, curtidas e comentários dele e mostra aqui. Enquanto nada foi
|
||||
publicado, dá para gerar dados simulados e ver como o dashboard aponta o que funciona e o que não. Os simulados ficam marcados e saem com um clique.
|
||||
</p>
|
||||
</div>
|
||||
<ol className="grid gap-3 md:grid-cols-3">
|
||||
{steps.map((s, i) => (
|
||||
<li key={s.label} className={cx("flex items-start gap-3 rounded-control border px-4 py-3",
|
||||
s.done ? "border-success/25 bg-success-soft/50" : "border-line bg-surface")}>
|
||||
<span className={cx("grid size-6 shrink-0 place-items-center rounded-full text-xs font-bold",
|
||||
s.done ? "bg-success text-sunken" : "bg-raised text-fg-muted")}>
|
||||
{s.done ? <CheckIcon size={14} /> : i + 1}
|
||||
</span>
|
||||
<span className="grid gap-0.5">
|
||||
<span className="text-sm font-medium text-fg">{s.label}<span className="sr-only">{s.done ? " (feito)" : " (pendente)"}</span></span>
|
||||
<span className="text-xs text-fg-subtle">{s.hint}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div className="flex flex-wrap items-start gap-3">
|
||||
<LinkButton href="/accounts"><LinkIcon size={16} />Abrir Canais de publicação</LinkButton>
|
||||
<SimulatedControls simulated={data.simulated} />
|
||||
</div>
|
||||
{!ready && <p className="text-xs text-fg-subtle">Sem os três passos, “Gerar dados simulados” não tem o que publicar.</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
/* A camada do @xyflow/react (editor de fluxo) fica ABAIXO das do Tailwind: utilitários e tokens vencem. */
|
||||
@layer xyflow, theme, base, components, utilities;
|
||||
@import "tailwindcss";
|
||||
|
||||
/*
|
||||
* Design system do painel CenaForge — "estúdio à noite".
|
||||
* Tema escuro por padrão (uso prolongado, vídeo em destaque). As páginas usam estes tokens
|
||||
* (bg-surface, text-fg-muted, border-line, bg-accent...) e nunca cores soltas.
|
||||
* Contrastes contra bg-surface (#111114): fg 17:1, fg-muted 8:1, fg-subtle 5,2:1, accent 7:1 (WCAG AA).
|
||||
*/
|
||||
@theme {
|
||||
/* Superfícies, da mais funda para a mais alta */
|
||||
--color-sunken: #060608;
|
||||
--color-canvas: #0a0a0c;
|
||||
--color-surface: #111114;
|
||||
--color-raised: #18181d;
|
||||
--color-overlay: #222229;
|
||||
|
||||
/* Bordas */
|
||||
--color-line: #1f1f26;
|
||||
--color-line-strong: #2f2f39;
|
||||
|
||||
/* Texto */
|
||||
--color-fg: #f4f4f6;
|
||||
--color-fg-muted: #a9a9b4;
|
||||
--color-fg-subtle: #858591;
|
||||
|
||||
/* Destaque da marca: brasa da forja (laranja) com a chama (rosa) para o que é IA */
|
||||
--color-accent: #ff7a1a;
|
||||
--color-accent-hover: #ff9142;
|
||||
--color-accent-fg: #1c0a00;
|
||||
--color-accent-soft: #2a1407;
|
||||
--color-flame: #ff4d7d;
|
||||
--color-glow: #ffb547;
|
||||
|
||||
/* Opção B da votação (A usa o destaque) */
|
||||
--color-option-b: #2dd4e8;
|
||||
--color-option-b-soft: #062a31;
|
||||
/* Opções C e D (histórias com 3 ou 4 vertentes por decisão) */
|
||||
--color-option-c: #b19bff;
|
||||
--color-option-c-soft: #1f1a3d;
|
||||
--color-option-d: #a3e05a;
|
||||
--color-option-d-soft: #18280b;
|
||||
|
||||
/* Estados */
|
||||
--color-success: #3ddc84;
|
||||
--color-success-soft: #0b2a1a;
|
||||
--color-warning: #fbbf24;
|
||||
--color-warning-soft: #2e2208;
|
||||
--color-danger: #ff6b6b;
|
||||
--color-danger-hover: #ff9a9a;
|
||||
--color-danger-soft: #34121a;
|
||||
--color-info: #5cbcff;
|
||||
--color-info-soft: #0b2236;
|
||||
--color-violet: #b19bff;
|
||||
--color-violet-soft: #1f1a3d;
|
||||
|
||||
/* Editor de cortes (/clipper/edit): tema de editor de vídeo, neutro e denso. Valores do tema "darkest" do
|
||||
FilmCraft (MIT/Apache-2.0), que por sua vez mede o padrão dos editores profissionais: fundo preto entre os
|
||||
painéis, painel cinza-chumbo, texto cinza claro, azul só para foco, tempo e valores editáveis. */
|
||||
--color-nle-app: #000000;
|
||||
--color-nle-panel: #1d1d1d;
|
||||
--color-nle-well: #0e0e0e;
|
||||
--color-nle-row: #232323;
|
||||
--color-nle-hover: #2c2c2c;
|
||||
--color-nle-pressed: #3a3a3a;
|
||||
--color-nle-line: #303030;
|
||||
--color-nle-text: #d1d1d1;
|
||||
--color-nle-dim: #b0b0b0;
|
||||
--color-nle-faint: #6e6e6e;
|
||||
--color-nle-accent: #2f6bdf;
|
||||
--color-nle-hot: #4096f3;
|
||||
--color-nle-focus: #5794ec;
|
||||
--color-nle-danger: #dc513d;
|
||||
|
||||
/* Raios */
|
||||
--radius-control: 0.625rem;
|
||||
--radius-card: 1rem;
|
||||
--radius-panel: 1.375rem;
|
||||
|
||||
/* Sombras */
|
||||
--shadow-card: 0 1px 0 0 rgb(255 255 255 / 0.04) inset, 0 1px 2px rgb(0 0 0 / 0.4), 0 12px 32px -16px rgb(0 0 0 / 0.7);
|
||||
--shadow-pop: 0 24px 64px -12px rgb(0 0 0 / 0.85), 0 0 0 1px rgb(255 255 255 / 0.05);
|
||||
--shadow-glow: 0 0 0 1px rgb(255 122 26 / 0.35), 0 10px 30px -10px rgb(255 122 26 / 0.55);
|
||||
|
||||
/* Escala tipográfica: display (título da página), title (seção), lead (texto de abertura) */
|
||||
--text-display: 2.75rem;
|
||||
--text-display--line-height: 1.05;
|
||||
--text-display--letter-spacing: -0.035em;
|
||||
--text-display--font-weight: 650;
|
||||
--text-title: 1.25rem;
|
||||
--text-title--line-height: 1.3;
|
||||
--text-title--letter-spacing: -0.015em;
|
||||
--text-title--font-weight: 600;
|
||||
--text-lead: 1.0625rem;
|
||||
--text-lead--line-height: 1.6;
|
||||
--text-eyebrow: 0.6875rem;
|
||||
--text-eyebrow--line-height: 1;
|
||||
--text-eyebrow--letter-spacing: 0.16em;
|
||||
|
||||
/* Fontes locais (o painel funciona offline). Segoe UI Variable tem cortes Display e Text no Windows 11. */
|
||||
--font-sans: "Segoe UI Variable Text", "Segoe UI Variable", ui-sans-serif, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
--font-display: "Segoe UI Variable Display", "Segoe UI Variable", ui-sans-serif, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
--font-mono: ui-monospace, "Cascadia Code", "Cascadia Mono", "SF Mono", Consolas, "Liberation Mono", monospace;
|
||||
|
||||
/* Largura da barra lateral */
|
||||
--spacing-rail: 4.5rem;
|
||||
--spacing-rail-open: 15.5rem;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
html {
|
||||
scrollbar-color: var(--color-line-strong) transparent;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--color-canvas);
|
||||
/* Luz quente vinda do alto, como um set iluminado: dá profundidade sem competir com o conteúdo. */
|
||||
background-image:
|
||||
radial-gradient(60rem 28rem at 70% -12rem, rgb(255 122 26 / 0.07), transparent 70%),
|
||||
radial-gradient(40rem 24rem at 15% -10rem, rgb(255 77 125 / 0.04), transparent 70%);
|
||||
background-repeat: no-repeat;
|
||||
color: var(--color-fg);
|
||||
font-family: var(--font-sans);
|
||||
font-feature-settings: "ss01", "cv11";
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--font-display);
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
p {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: var(--color-accent);
|
||||
color: var(--color-accent-fg);
|
||||
}
|
||||
|
||||
/* Foco visível em todo elemento interativo */
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85em;
|
||||
background: var(--color-raised);
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.05em 0.35em;
|
||||
color: var(--color-fg);
|
||||
}
|
||||
|
||||
pre code {
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Select com seta própria (a nativa some no tema escuro do Windows) */
|
||||
select:not([multiple]) {
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a9a9b4' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 0.7rem center;
|
||||
background-size: 1rem;
|
||||
padding-right: 2.25rem;
|
||||
}
|
||||
|
||||
select option {
|
||||
background: var(--color-raised);
|
||||
color: var(--color-fg);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Barra lateral: recolhida (só ícones) e expandida POR CIMA do conteúdo ao passar o mouse ou ao
|
||||
* focar pelo teclado (:focus-visible — um clique do mouse não a deixa presa aberta).
|
||||
*/
|
||||
@layer components {
|
||||
.rail {
|
||||
width: var(--spacing-rail);
|
||||
background-color: rgb(10 10 12 / 0.92);
|
||||
backdrop-filter: blur(20px);
|
||||
transition: width 220ms cubic-bezier(0.2, 0.8, 0.2, 1), box-shadow 220ms ease, background-color 220ms ease;
|
||||
}
|
||||
|
||||
.rail:hover,
|
||||
.rail:has(:focus-visible) {
|
||||
width: var(--spacing-rail-open);
|
||||
background-color: var(--color-surface);
|
||||
box-shadow: 24px 0 64px -16px rgb(0 0 0 / 0.85), 1px 0 0 0 var(--color-line-strong);
|
||||
}
|
||||
|
||||
/* Pequena intenção antes de abrir: passar o mouse de raspão não abre a barra. */
|
||||
.rail:hover {
|
||||
transition-delay: 90ms;
|
||||
}
|
||||
|
||||
.rail-label {
|
||||
opacity: 0;
|
||||
transform: translateX(-6px);
|
||||
transition: opacity 160ms ease, transform 200ms ease;
|
||||
}
|
||||
|
||||
.rail:hover .rail-label,
|
||||
.rail:has(:focus-visible) .rail-label {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
transition-delay: 110ms;
|
||||
}
|
||||
|
||||
/* Texto com o degradê da chama, para o que é feito pela IA */
|
||||
.text-flame {
|
||||
background: linear-gradient(95deg, var(--color-glow), var(--color-accent) 45%, var(--color-flame));
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
/* Borda em degradê para o painel de destaque */
|
||||
.flame-frame {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.flame-frame::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
padding: 1px;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(135deg, rgb(255 181 71 / 0.7), rgb(255 122 26 / 0.35) 35%, rgb(255 77 125 / 0.25) 70%, rgb(255 255 255 / 0.04));
|
||||
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Editor de fluxo (@xyflow/react): as variáveis da biblioteca apontam para os tokens do tema,
|
||||
* para o canvas, os controles e o minimapa conversarem com o resto do painel.
|
||||
*/
|
||||
.react-flow.cf-flow {
|
||||
--xy-background-color: transparent;
|
||||
--xy-background-pattern-dots-color: var(--color-line-strong);
|
||||
--xy-edge-stroke: var(--color-line-strong);
|
||||
--xy-minimap-background-color: var(--color-sunken);
|
||||
--xy-minimap-mask-background-color: rgb(10 10 12 / 0.7);
|
||||
--xy-minimap-mask-stroke-color: var(--color-line-strong);
|
||||
--xy-minimap-node-background-color: var(--color-overlay);
|
||||
--xy-controls-button-background-color: var(--color-raised);
|
||||
--xy-controls-button-background-color-hover: var(--color-overlay);
|
||||
--xy-controls-button-color: var(--color-fg-muted);
|
||||
--xy-controls-button-color-hover: var(--color-fg);
|
||||
--xy-controls-button-border-color: var(--color-line-strong);
|
||||
--xy-controls-box-shadow: 0 1px 2px rgb(0 0 0 / 0.5);
|
||||
--xy-attribution-background-color: transparent;
|
||||
--xy-node-border-radius: var(--radius-card);
|
||||
font-family: var(--font-sans);
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__controls {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-line-strong);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__controls-button {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__controls-button:focus-visible,
|
||||
.cf-flow .react-flow__minimap:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__minimap {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-line-strong);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
/* Nós customizados: sem moldura da biblioteca (o cartão é nosso) e alças invisíveis (não há ligação manual). */
|
||||
.cf-flow .react-flow__node {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__handle {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__attribution {
|
||||
color: var(--color-fg-subtle);
|
||||
}
|
||||
|
||||
.cf-flow .react-flow__attribution a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
/* ---------- Editor de cortes ---------- */
|
||||
.nle {
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
color: var(--color-nle-text);
|
||||
scrollbar-color: #4b4b4b transparent;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.nle ::selection {
|
||||
background: rgb(47 107 223 / 0.55);
|
||||
}
|
||||
/* Controle deslizante fino, no padrão dos painéis de efeito. */
|
||||
.nle input[type="range"] {
|
||||
appearance: none;
|
||||
height: 14px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
.nle input[type="range"]::-webkit-slider-runnable-track {
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: #4a4a4a;
|
||||
}
|
||||
.nle input[type="range"]::-webkit-slider-thumb {
|
||||
appearance: none;
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
margin-top: -4.5px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid #d1d1d1;
|
||||
background: var(--color-nle-panel);
|
||||
}
|
||||
.nle input[type="range"]:hover::-webkit-slider-thumb {
|
||||
background: #d1d1d1;
|
||||
}
|
||||
.nle input[type="range"]::-moz-range-track {
|
||||
height: 2px;
|
||||
background: #4a4a4a;
|
||||
}
|
||||
.nle input[type="range"]::-moz-range-thumb {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid #d1d1d1;
|
||||
background: var(--color-nle-panel);
|
||||
}
|
||||
.nle input[type="range"]:focus-visible {
|
||||
outline: 1px solid var(--color-nle-focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.nle dialog::backdrop {
|
||||
background: rgb(0 0 0 / 0.72);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
transition-delay: 0ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="4" y1="2" x2="28" y2="30" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stop-color="#ffb547"/>
|
||||
<stop offset="0.5" stop-color="#ff7a1a"/>
|
||||
<stop offset="1" stop-color="#ff4d7d"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="32" height="32" rx="9" fill="url(#g)"/>
|
||||
<rect x="8" y="4" width="16" height="24" rx="4" fill="#1c0a00"/>
|
||||
<path d="M13.9 12.75v6.5a.75.75 0 0 0 1.14.64l5.05-3.25a.75.75 0 0 0 0-1.28l-5.05-3.25a.75.75 0 0 0-1.14.64Z" fill="url(#g)"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 612 B |
@@ -0,0 +1,35 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { ConfirmHost } from "@/components/confirm-dialog";
|
||||
import { Sidebar } from "@/components/sidebar-nav";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "CenaForge", template: "%s · CenaForge" },
|
||||
description: "Painel local de histórias, episódios, assets e agentes.",
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: "#0a0a0c",
|
||||
colorScheme: "dark",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="pt-BR" className="h-full antialiased">
|
||||
<body className="min-h-full">
|
||||
<a href="#conteudo"
|
||||
className="sr-only z-[60] rounded-control bg-accent px-4 py-2 font-semibold text-accent-fg focus:not-sr-only focus:fixed focus:top-3 focus:left-24">
|
||||
Pular para o conteúdo
|
||||
</a>
|
||||
<Sidebar />
|
||||
{/* O conteúdo reserva só a largura da barra recolhida (a expandida passa por cima) e usa todo o
|
||||
resto da tela, com gutters de 16/24/32 px. Medida de leitura (~75ch) só em textos longos. */}
|
||||
<main id="conteudo" className="min-h-screen pl-rail">
|
||||
<div className="grid w-full min-w-0 grid-cols-1 gap-12 px-4 pt-6 pb-20 md:px-6 md:pt-8 xl:px-8 xl:pt-10 max-md:gap-9">{children}</div>
|
||||
</main>
|
||||
{/* Modal de confirmação/aviso único do painel (askConfirm/showAlert). */}
|
||||
<ConfirmHost />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { ArrowLeftIcon } from "@/components/icons";
|
||||
import { Eyebrow, LinkButton } from "@/components/ui";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<section className="grid min-h-[70vh] place-items-center">
|
||||
<div className="grid max-w-lg justify-items-center gap-5 text-center">
|
||||
<span aria-hidden="true" className="font-display text-[8rem] leading-none font-bold tracking-[-0.06em] text-flame opacity-90">404</span>
|
||||
<Eyebrow tone="muted">Corta!</Eyebrow>
|
||||
<h1 className="text-display text-fg">Essa cena não existe</h1>
|
||||
<p className="text-lead text-fg-muted">A história ou o episódio pode ter outro identificador. Volte à lista e abra pelo painel.</p>
|
||||
<LinkButton variant="primary" size="lg" href="/" className="mt-2"><ArrowLeftIcon size={18} />Voltar às histórias</LinkButton>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import Link from "next/link";
|
||||
import { connection } from "next/server";
|
||||
import { DeleteStoryButton } from "@/components/delete-story-button";
|
||||
import { CreateStoryForm } from "@/components/forms";
|
||||
import { ArrowRightIcon, ChevronDownIcon, FilmIcon, PenIcon } from "@/components/icons";
|
||||
import { StoryComposer } from "@/components/story-composer";
|
||||
import { storyFormatLabel, unitTerms } from "@/components/story-formats";
|
||||
import {
|
||||
Badge, EmptyState, PageHeader, SectionHeader, StagePipeline, Stat, episodeCode, formatRelative, hueOf,
|
||||
} from "@/components/ui";
|
||||
import { defaultProviderFor, models, providers } from "@/lib/agents";
|
||||
import { listEpisodes, listStories } from "@/lib/stories";
|
||||
import type { EpisodeView, Story } from "@/lib/types";
|
||||
|
||||
export default async function HomePage() {
|
||||
await connection();
|
||||
const stories = listStories().map((s) => ({ story: s, episodes: listEpisodes(s.id) }));
|
||||
const totalEpisodes = stories.reduce((sum, s) => sum + s.episodes.length, 0);
|
||||
const rendered = stories.reduce((sum, s) => sum + s.episodes.filter((e) => e.stage === "renderizado" || e.stage === "decidido").length, 0);
|
||||
const openVotes = stories.reduce((sum, s) => sum + (s.story.kind === "interactive" ? s.episodes.filter((e) => e.stage === "renderizado").length : 0), 0);
|
||||
const available = Object.fromEntries(providers().map((p) => [p.id, p.available])) as Record<"claude" | "codex", boolean>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Estúdio CenaForge" title={<>Suas histórias, <span className="text-fg-subtle">episódio a episódio.</span></>}
|
||||
description="Escreva com IA, monte a cena, renderize o vertical e deixe o público decidir o próximo capítulo."
|
||||
actions={stories.length > 0 && (
|
||||
<dl className="flex gap-10 rounded-card border border-line bg-surface/60 px-7 py-5">
|
||||
<Stat label="Histórias" value={stories.length} />
|
||||
<Stat label="Episódios" value={totalEpisodes} />
|
||||
<Stat label="Renderizados" value={rendered} />
|
||||
{openVotes > 0 && <Stat label="Em votação" value={openVotes} />}
|
||||
</dl>
|
||||
)} />
|
||||
|
||||
<StoryComposer autoProvider={defaultProviderFor("story")} available={available} models={models()} />
|
||||
|
||||
<section aria-labelledby="lista-historias" className="grid gap-6">
|
||||
<SectionHeader id="lista-historias" eyebrow="Biblioteca" title="Em produção"
|
||||
description={stories.length > 0 ? "Abra uma história para continuar de onde parou." : undefined} />
|
||||
{stories.length === 0 ? (
|
||||
<EmptyState icon={<FilmIcon />} title="Nenhuma história ainda">
|
||||
Cole uma ideia no painel acima e a IA monta a primeira história com você.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<ul className="grid gap-5 lg:grid-cols-2 2xl:grid-cols-3">
|
||||
{stories.map(({ story, episodes }) => <StoryCard key={story.id} story={story} episodes={episodes} />)}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<details className="group rounded-card border border-line bg-surface/50 open:bg-surface">
|
||||
<summary className="flex cursor-pointer list-none items-center gap-4 rounded-card px-6 py-5 transition-colors hover:bg-raised/40 [&::-webkit-details-marker]:hidden">
|
||||
<span className="grid size-10 shrink-0 place-items-center rounded-xl border border-line-strong bg-raised text-fg-muted"><PenIcon size={18} /></span>
|
||||
<span className="grid min-w-0 flex-1 gap-0.5">
|
||||
<span className="font-display text-[0.9375rem] font-semibold text-fg">Prefere começar sem IA?</span>
|
||||
<span className="text-[0.8125rem] text-fg-subtle">Crie uma história vazia com título e premissa, e escreva você mesmo.</span>
|
||||
</span>
|
||||
<ChevronDownIcon size={18} className="shrink-0 text-fg-subtle transition-transform group-open:rotate-180" />
|
||||
</summary>
|
||||
<div className="border-t border-line px-6 pt-5 pb-6">
|
||||
<CreateStoryForm />
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cartão de história: um "pôster" vertical com a cor própria da história e o estado do último episódio. */
|
||||
function StoryCard({ story, episodes }: { story: Story; episodes: EpisodeView[] }) {
|
||||
const last = episodes.at(-1);
|
||||
const hue = hueOf(story.id);
|
||||
const interactive = story.kind === "interactive";
|
||||
const terms = unitTerms(story.kind);
|
||||
return (
|
||||
<li className="relative">
|
||||
{/* Fora do link: um botão dentro de <a> não é válido. Fica no canto inferior direito do cartão. */}
|
||||
<DeleteStoryButton storyId={story.id} title={story.title} compact className="absolute right-4 bottom-4 z-10" />
|
||||
<Link href={`/stories/${story.id}`}
|
||||
className="group flex h-full gap-5 rounded-card border border-line bg-surface p-4 shadow-card transition-[border-color,background-color,transform] duration-200 hover:-translate-y-0.5 hover:border-line-strong hover:bg-raised/60">
|
||||
<div aria-hidden="true"
|
||||
className="relative flex aspect-[9/16] w-24 shrink-0 flex-col justify-between overflow-hidden rounded-xl border border-white/10 p-2.5"
|
||||
style={{ background: `linear-gradient(160deg, oklch(0.55 0.16 ${hue}) 0%, oklch(0.32 0.12 ${(hue + 40) % 360}) 55%, oklch(0.16 0.04 ${(hue + 60) % 360}) 100%)` }}>
|
||||
<span className="font-mono text-[0.625rem] font-semibold text-white/80">{last ? terms.code(last.number) : terms.code(0)}</span>
|
||||
<span className="font-display text-[1.75rem] leading-none font-bold text-white/90">{story.title.charAt(0).toUpperCase()}</span>
|
||||
<span className="absolute inset-x-0 bottom-0 h-1/2 bg-linear-to-t from-black/50 to-transparent" />
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col py-1">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<h3 className="font-display text-[1.1875rem] leading-snug font-semibold tracking-[-0.015em] text-fg transition-colors group-hover:text-accent">{story.title}</h3>
|
||||
<ArrowRightIcon size={18} className="mt-1 shrink-0 text-fg-subtle opacity-0 transition-[opacity,transform] group-hover:translate-x-0.5 group-hover:opacity-100" />
|
||||
</div>
|
||||
<p className="mt-1.5 line-clamp-2 text-sm leading-relaxed text-fg-muted">{story.logline || "Sem premissa ainda."}</p>
|
||||
|
||||
<div className="mt-auto grid gap-3 pt-4">
|
||||
{last ? <StagePipeline stage={last.stage} /> : <span className="text-xs text-fg-subtle">Sem {terms.many}</span>}
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 pr-10 text-xs text-fg-subtle">
|
||||
<Badge tone={interactive ? "accent" : "neutral"}>{storyFormatLabel(story.kind)}</Badge>
|
||||
<span>{episodes.length} {episodes.length === 1 ? terms.one : terms.many}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>atualizada {formatRelative(story.updated_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Link from "next/link";
|
||||
import { ClockIcon, PublishIcon, SettingsIcon } from "@/components/icons";
|
||||
import { PublishingBoard } from "@/components/publishing-board";
|
||||
import { Meta, PageHeader } from "@/components/ui";
|
||||
|
||||
export const metadata = { title: "Publicações" };
|
||||
|
||||
/**
|
||||
* Publicações: a fila de envio para YouTube, TikTok e Instagram. Os dados mudam a cada segundo
|
||||
* (progresso do envio), então a página busca /api/publishing/* no navegador.
|
||||
*/
|
||||
export default function PublishingPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Distribuição" title="Publicações"
|
||||
description="Tudo o que vai para as redes: o que espera a sua aprovação, o que está agendado, o que está saindo agora e o que já foi publicado."
|
||||
meta={<>
|
||||
<Meta icon={<PublishIcon size={15} />}>Redes e regras em <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">Canais de publicação</Link></Meta>
|
||||
<Meta icon={<ClockIcon size={15} />}>Horários bons em <Link href="/settings" className="text-fg-muted underline underline-offset-2 hover:text-fg">Configurações</Link></Meta>
|
||||
<Meta icon={<SettingsIcon size={15} />}>O painel precisa estar aberto para publicar</Meta>
|
||||
</>} />
|
||||
<PublishingBoard />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { SettingsPanel } from "@/components/settings-panel";
|
||||
import { PageHeader } from "@/components/ui";
|
||||
|
||||
export const metadata = { title: "Configurações" };
|
||||
|
||||
/** Configurações do painel: publicação, apps das redes, navegador da sessão logada e a explicação dos modos. */
|
||||
export default function SettingsPage() {
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Painel" title="Configurações"
|
||||
description="Horários de publicação, os apps de cada rede e o navegador usado na sessão logada. Tudo fica só neste computador." />
|
||||
<SettingsPanel />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { connection } from "next/server";
|
||||
import path from "node:path";
|
||||
import { EpisodeApprove } from "@/components/episode-approve";
|
||||
import { CloseDecisionForm, CommentsForm, CreateEpisodeForm, PrepareBranchesForm } from "@/components/forms";
|
||||
import { BookIcon, ChatIcon, ClapperIcon, FolderIcon, PenIcon, PlayIcon, SparkIcon } from "@/components/icons";
|
||||
import { RenderControls } from "@/components/render-controls";
|
||||
import { MontageEditor } from "@/components/montage-editor";
|
||||
import { ScriptReader } from "@/components/script-reader";
|
||||
import { unitTerms } from "@/components/story-formats";
|
||||
import {
|
||||
Breadcrumb, CHOICE_STYLE, Card, ChoiceChip, EmptyState, LinkButton, Meta, PageHeader, StagePipeline, StatusBadge, cx, episodeCode, fileUrl, formatDate,
|
||||
} from "@/components/ui";
|
||||
import { DECISION_RULE, decisionVotes, leader, listComments, tally } from "@/lib/decisions";
|
||||
import { REPO_ROOT, readTextIfExists } from "@/lib/paths";
|
||||
import { episodeApproval, type EpisodeApproval } from "@/lib/publishing";
|
||||
import { listRenders } from "@/lib/renders";
|
||||
import { parseScript } from "@/lib/script-doc";
|
||||
import { getEpisode, getStory, listEpisodes } from "@/lib/stories";
|
||||
import type { Choice, EpisodeView } from "@/lib/types";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ storyId: string; number: string }> }) {
|
||||
const { storyId, number } = await params;
|
||||
const story = getStory(storyId);
|
||||
return { title: story ? `${unitTerms(story.kind).code(Number(number))} · ${story.title}` : "Episódio" };
|
||||
}
|
||||
|
||||
export default async function EpisodePage({ params }: { params: Promise<{ storyId: string; number: string }> }) {
|
||||
await connection();
|
||||
const { storyId, number } = await params;
|
||||
const story = getStory(storyId);
|
||||
const ep = story ? getEpisode(storyId, Number(number)) : undefined;
|
||||
if (!story || !ep) notFound();
|
||||
|
||||
const script = readTextIfExists(path.join(REPO_ROOT, ep.scriptPath));
|
||||
const renders = listRenders(ep.id);
|
||||
const running = renders.find((r) => r.status === "running") ?? null;
|
||||
const latestOk = renders.find((r) => r.status === "success" && r.mp4);
|
||||
const interactive = story.kind === "interactive";
|
||||
const documentary = story.kind === "documentary";
|
||||
const readingHref = `/stories/${story.id}/episodes/${ep.number}/roteiro`;
|
||||
const t = tally(ep.id);
|
||||
const comments = listComments(ep.id);
|
||||
const isLast = listEpisodes(storyId).at(-1)?.id === ep.id;
|
||||
const terms = unitTerms(story.kind);
|
||||
const label = terms.code(ep.number); // como a interface chama: ep01 ou vídeo
|
||||
const agentLink = (kind: string) => `/agent?story=${story.id}&episode=${ep.id}&kind=${kind}`;
|
||||
// Opções em jogo (2 a 4). Sem vertentes preparadas, valem A e B da cena.
|
||||
const options = choiceOptions(ep);
|
||||
const letters = options.map((o) => o.letter);
|
||||
const totalVotes = letters.reduce((sum, l) => sum + (t.votes[l] ?? 0), 0);
|
||||
// Aprovação para publicar (vídeo final, título, legenda, canais que recebem). Falha aqui não derruba a página.
|
||||
let approval: EpisodeApproval | null = null;
|
||||
try { approval = episodeApproval(ep.id); } catch { approval = null; }
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
breadcrumb={<Breadcrumb items={[{ href: "/", label: "Histórias" }, { href: `/stories/${story.id}`, label: story.title }, { label }]} />}
|
||||
eyebrow={documentary ? "Vídeo documental" : <>Episódio {ep.number} · {story.title}</>}
|
||||
// Documental: o título é o do roteiro (o vídeo é um só; "Abertura" era nome de episódio de série).
|
||||
title={(documentary && script ? parseScript(script).title : null) || ep.overlay?.title || ep.title || story.title}
|
||||
description={ep.parent_choice ? `Continua a escolha ${ep.parent_choice} do episódio anterior.` : undefined}
|
||||
meta={<>
|
||||
<StagePipeline stage={ep.stage} />
|
||||
{!documentary && <Meta icon={<FolderIcon size={15} />}><code>{ep.configPath}</code></Meta>}
|
||||
</>}
|
||||
actions={<>
|
||||
<LinkButton variant="ghost" href={agentLink("free")}>Outro pedido</LinkButton>
|
||||
{script && <LinkButton variant="secondary" href={readingHref}><BookIcon size={16} />Ler roteiro</LinkButton>}
|
||||
{/* A cena 3D (rua do entregador) não serve ao documental, que é montado com imagens e narração. */}
|
||||
{!documentary && <LinkButton href={agentLink("scene")}><ClapperIcon size={16} />Montar cena</LinkButton>}
|
||||
<LinkButton variant="flame" href={agentLink("script")}><SparkIcon size={16} />Roteiro com IA</LinkButton>
|
||||
</>} />
|
||||
|
||||
<div className={cx("grid items-start gap-8", interactive && "xl:grid-cols-[minmax(0,1fr)_24rem] 2xl:grid-cols-[minmax(0,1fr)_28rem]")}>
|
||||
<div className="grid min-w-0 content-start gap-8">
|
||||
<Card eyebrow={<><PlayIcon size={12} />Vídeo</>} title="Prévia e render">
|
||||
<div className="grid gap-8 md:grid-cols-[minmax(0,17rem)_minmax(0,1fr)]">
|
||||
<div className="grid min-w-0 content-start gap-4">
|
||||
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-2xl border border-line-strong bg-sunken shadow-pop">
|
||||
{latestOk?.mp4 ? (
|
||||
<video key={latestOk.mp4} controls className="size-full object-contain" src={fileUrl(latestOk.mp4)} />
|
||||
) : (
|
||||
<div className="grid size-full place-items-center bg-[radial-gradient(circle_at_50%_35%,rgb(255_122_26/0.08),transparent_65%)] p-5 text-center">
|
||||
<div className="grid justify-items-center gap-3">
|
||||
<span className="grid size-14 place-items-center rounded-full border border-line-strong bg-raised text-fg-muted"><PlayIcon size={22} /></span>
|
||||
<p className="font-display text-[0.9375rem] font-semibold">Sem vídeo ainda</p>
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
{documentary
|
||||
? "Monte o vídeo na seção Montagem: áudio por trecho, imagens e o botão “Montar vídeo”."
|
||||
: ep.hasConfig ? "Renderize a prévia para ver o primeiro corte." : "Escreva o roteiro e monte a cena; depois renderize."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{approval && <EpisodeApprove episodeId={ep.id} approval={approval} label={label} />}
|
||||
</div>
|
||||
|
||||
{documentary ? (
|
||||
<div className="grid min-w-0 content-start gap-4">
|
||||
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Como este vídeo é feito</h3>
|
||||
<ol className="grid gap-3 text-sm leading-relaxed text-fg-muted">
|
||||
<li><span className="font-semibold text-fg">1. Roteiro</span>: leia trecho a trecho abaixo ou no modo leitura.</li>
|
||||
<li><span className="font-semibold text-fg">2. Narração</span>: um áudio por trecho, com números por extenso (seção Montagem).</li>
|
||||
<li><span className="font-semibold text-fg">3. Imagens</span>: uma imagem ou clipe por trecho, de banco livre ou enviado por você.</li>
|
||||
<li><span className="font-semibold text-fg">4. Montagem</span>: imagens, texto na tela, narração e legenda num MP4 vertical, pelo botão “Montar vídeo”.</li>
|
||||
</ol>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid min-w-0 content-start gap-7">
|
||||
<div className="grid gap-3">
|
||||
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Cena</h3>
|
||||
{ep.hasConfig ? (
|
||||
<div className="grid gap-3">
|
||||
<p className="font-display text-[1.375rem] leading-snug font-semibold tracking-[-0.015em]">{ep.overlay?.title ?? "—"}</p>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{options.map((o) => <ChoiceTile key={o.letter} letter={o.letter} text={o.label} />)}
|
||||
</div>
|
||||
</div>
|
||||
) : <p className="text-sm text-fg-muted">Cena ainda não montada. Depois do roteiro, use “Montar cena”.</p>}
|
||||
</div>
|
||||
|
||||
<RenderControls episodeId={ep.id} hasConfig={ep.hasConfig} running={running} />
|
||||
|
||||
<div className="grid gap-3">
|
||||
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Histórico de renders</h3>
|
||||
{renders.length === 0 ? <p className="text-sm text-fg-subtle">Nenhum render ainda.</p> : (
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line text-sm">
|
||||
{renders.map((r) => (
|
||||
<li key={r.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3.5 py-2.5">
|
||||
<StatusBadge status={r.status} />
|
||||
<span className="font-medium text-fg-muted">{r.profile === "final" ? "final" : r.profile === "documentary" ? "montagem" : "prévia"}</span>
|
||||
<span className="text-xs text-fg-subtle">{formatDate(r.started_at)}</span>
|
||||
<span className="ml-auto flex gap-3">
|
||||
{r.mp4 && <a className="font-medium text-accent hover:underline" href={fileUrl(r.mp4)}>MP4</a>}
|
||||
{r.run_dir && r.profile !== "documentary" && <a className="text-fg-muted hover:text-fg hover:underline" href={fileUrl(`${r.run_dir}/inspect/contact-sheet.png`)}>quadros</a>}
|
||||
</span>
|
||||
{r.error && <span className="w-full truncate text-xs text-danger" title={r.error}>{r.error.split("\n")[0]}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* No documental o roteiro vem primeiro: é o que guia a narração e as imagens. */}
|
||||
<Card className={cx(documentary && "order-first")} eyebrow={<><PenIcon size={12} />Roteiro</>}
|
||||
title={documentary ? "Roteiro do vídeo" : `Roteiro do ${label}`} description={<code className="text-xs">{ep.scriptPath}</code>}
|
||||
actions={script ? <LinkButton size="sm" variant="ghost" href={agentLink("script")}><SparkIcon size={14} />Revisar com IA</LinkButton> : undefined}>
|
||||
{script ? (
|
||||
<ScriptReader markdown={script} readingHref={readingHref} />
|
||||
) : (
|
||||
<EmptyState compact icon={<SparkIcon />} title="Roteiro ainda não escrito"
|
||||
action={<LinkButton variant="primary" href={agentLink("script")}><SparkIcon size={16} />Escrever roteiro com IA</LinkButton>}>
|
||||
O roteiro sai com o GPT (Codex) por padrão.
|
||||
</EmptyState>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{documentary && script && (
|
||||
<Card className="order-first" eyebrow={<><ClapperIcon size={12} />Montagem</>} title="Montagem do vídeo"
|
||||
description="Um áudio por trecho (a voz fica natural) e um visual por trecho: foto, animação 2D, cena 3D do Godot, clipe ou cartela. Dá para misturar.">
|
||||
<MontageEditor episodeId={ep.id} />
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{interactive && (
|
||||
<div className="grid min-w-0 content-start gap-8 xl:sticky xl:top-8">
|
||||
<Card eyebrow="Decisão do público" title="Votação nos comentários">
|
||||
<div className="mb-5 grid gap-4">
|
||||
{options.map((o) => (
|
||||
<VoteBar key={o.letter} letter={o.letter} label={o.label} votes={t.votes[o.letter] ?? 0} total={totalVotes}
|
||||
winner={ep.decision?.winner === o.letter} />
|
||||
))}
|
||||
</div>
|
||||
<p className="mb-5 text-xs leading-relaxed text-fg-subtle">
|
||||
{t.totalComments} comentário(s), {t.ambiguousOrNoVote} sem voto válido. Regra: {DECISION_RULE}
|
||||
</p>
|
||||
{ep.decision ? (
|
||||
<div className="rounded-card border border-accent/30 bg-accent-soft p-4 text-sm">
|
||||
<div className="font-display text-base font-semibold text-accent">Venceu {ep.decision.winner}</div>
|
||||
<div className="mt-0.5 text-xs text-fg-muted">
|
||||
{Object.entries(decisionVotes(ep.decision)).map(([l, n]) => `${l}: ${n}`).join(" × ")}, {ep.decision.method === "manual" ? "decisão manual" : "por votos"} · {formatDate(ep.decision.closed_at)} · fotografia imutável
|
||||
</div>
|
||||
{isLast && <div className="mt-4"><CreateEpisodeForm storyId={story.id} parentEpisodeId={ep.id} label={`Criar ${episodeCode(ep.number + 1)} a partir de ${ep.decision.winner}`} /></div>}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 border-t border-line pt-5">
|
||||
<CommentsForm episodeId={ep.id} />
|
||||
<CloseDecisionForm episodeId={ep.id} tied={leader(t.votes) === null} letters={letters} />
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-5 text-xs text-fg-subtle">Integração com o Instagram ainda não existe: os comentários entram colados aqui.</p>
|
||||
</Card>
|
||||
|
||||
{ep.status === "main" && (
|
||||
<Card eyebrow={<><SparkIcon size={12} />Próximo nível</>} title="Vertentes"
|
||||
description={`A IA escreve as ${story.branch_count} opções, com roteiro e cena de cada uma, antes da votação. O vídeo não é gerado aqui.`}>
|
||||
{options.some((o) => o.fileKey) && (
|
||||
<ul className="mb-5 grid gap-1.5 text-sm">
|
||||
{options.filter((o) => o.fileKey).map((o) => (
|
||||
<li key={o.letter} className="flex items-center gap-2.5">
|
||||
<ChoiceChip letter={o.letter} size="sm" />
|
||||
<code>{o.fileKey}</code>
|
||||
<span className="text-xs text-fg-subtle">
|
||||
{o.status === "main" ? "caminho principal" : o.status === "discarded" ? "descartada" : "candidata"}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{ep.decision ? (
|
||||
<p className="text-sm text-fg-muted">Votação fechada: a vertente {ep.decision.winner} seguiu para o caminho principal.</p>
|
||||
) : (
|
||||
<PrepareBranchesForm episodeId={ep.id} status={ep.branches_status} runId={ep.branches_run_id} hasScript={ep.hasScript} />
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card title={<span className="flex items-center gap-2"><ChatIcon size={16} />Comentários</span>} description={comments.length ? `${comments.length} no total` : undefined}>
|
||||
{comments.length === 0 ? (
|
||||
<EmptyState compact icon={<ChatIcon />} title="Nenhum comentário">
|
||||
Cole os comentários do público no formulário da votação para apurar as opções.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<ul className="-mx-2 grid max-h-[40vh] gap-0.5 overflow-y-auto text-sm">
|
||||
{comments.map((c) => (
|
||||
<li key={c.id} className="flex items-start gap-3 rounded-lg px-2 py-2 hover:bg-raised/50">
|
||||
<span className={cx("grid size-6 shrink-0 place-items-center rounded-md text-xs font-bold",
|
||||
c.choice ? cx(CHOICE_STYLE[c.choice].soft, CHOICE_STYLE[c.choice].text) : "bg-raised text-fg-subtle")}>
|
||||
{c.choice ?? "·"}
|
||||
</span>
|
||||
<span className="min-w-0 leading-relaxed">
|
||||
<span className="font-medium text-fg-muted">{c.author_name}</span>{" "}
|
||||
<span className="text-fg">{c.text}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Opções da decisão deste episódio: as de `ep.choices` (2 a 4) ou, sem vertentes, A e B da cena. */
|
||||
function choiceOptions(ep: EpisodeView): { letter: Choice; label?: string; fileKey: string | null; status: EpisodeView["status"] | null }[] {
|
||||
const fromScene: Partial<Record<Choice, string | undefined>> = { A: ep.overlay?.choiceA, B: ep.overlay?.choiceB };
|
||||
if (ep.choices.length === 0) {
|
||||
return (["A", "B"] as Choice[]).map((letter) => ({ letter, label: fromScene[letter], fileKey: null, status: null }));
|
||||
}
|
||||
return ep.choices.map((c) => ({ letter: c.letter, label: c.label || fromScene[c.letter], fileKey: c.fileKey, status: c.status }));
|
||||
}
|
||||
|
||||
function ChoiceTile({ letter, text }: { letter: Choice; text?: string }) {
|
||||
const c = CHOICE_STYLE[letter];
|
||||
return (
|
||||
<div className={cx("flex gap-3 rounded-control border p-3", c.border, c.soft)}>
|
||||
<ChoiceChip letter={letter} solid />
|
||||
<span className="text-sm leading-snug text-fg">{text || "—"}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Barra de proporção de uma opção da votação. */
|
||||
function VoteBar({ letter, label, votes, total, winner }: { letter: Choice; label?: string; votes: number; total: number; winner?: boolean }) {
|
||||
const pct = total > 0 ? Math.round((votes / total) * 100) : 0;
|
||||
const c = CHOICE_STYLE[letter];
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-2 flex items-center gap-2.5">
|
||||
<span className={cx("grid size-6 shrink-0 place-items-center rounded-md text-xs font-bold", winner ? cx(c.fill, c.fillFg) : cx(c.soft, c.text))}>{letter}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm text-fg-muted" title={label}>{label || `Opção ${letter}`}</span>
|
||||
<span className="font-display text-2xl leading-none font-semibold tabular-nums">{votes}</span>
|
||||
<span className="w-9 text-right text-xs tabular-nums text-fg-subtle">{pct}%</span>
|
||||
</div>
|
||||
<div className={cx("h-2 overflow-hidden rounded-full", c.soft)} role="img"
|
||||
aria-label={`Opção ${letter}: ${votes} voto(s), ${pct}%${winner ? ", vencedora" : ""}`}>
|
||||
<div className={cx("h-full rounded-full transition-[width]", c.fill)} style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Modo leitura: só o roteiro, diagramado, em largura confortável.
|
||||
import path from "node:path";
|
||||
import { notFound } from "next/navigation";
|
||||
import { connection } from "next/server";
|
||||
import { ArrowLeftIcon, SparkIcon } from "@/components/icons";
|
||||
import { ScriptReader } from "@/components/script-reader";
|
||||
import { unitTerms } from "@/components/story-formats";
|
||||
import { Breadcrumb, EmptyState, LinkButton, PageHeader } from "@/components/ui";
|
||||
import { REPO_ROOT, readTextIfExists } from "@/lib/paths";
|
||||
import { parseScript } from "@/lib/script-doc";
|
||||
import { getEpisode, getStory } from "@/lib/stories";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ storyId: string; number: string }> }) {
|
||||
const { storyId } = await params;
|
||||
return { title: `Roteiro · ${getStory(storyId)?.title ?? "História"}` };
|
||||
}
|
||||
|
||||
export default async function ScriptPage({ params }: { params: Promise<{ storyId: string; number: string }> }) {
|
||||
await connection();
|
||||
const { storyId, number } = await params;
|
||||
const story = getStory(storyId);
|
||||
const ep = story ? getEpisode(storyId, Number(number)) : undefined;
|
||||
if (!story || !ep) notFound();
|
||||
const terms = unitTerms(story.kind);
|
||||
const label = terms.code(ep.number);
|
||||
const episodeHref = `/stories/${story.id}/episodes/${ep.number}`;
|
||||
const script = readTextIfExists(path.join(REPO_ROOT, ep.scriptPath));
|
||||
const title = script ? parseScript(script).title : null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto grid w-full max-w-5xl gap-8">
|
||||
<PageHeader
|
||||
breadcrumb={<Breadcrumb items={[
|
||||
{ href: "/", label: "Histórias" }, { href: `/stories/${story.id}`, label: story.title },
|
||||
{ href: episodeHref, label }, { label: "Roteiro" },
|
||||
]} />}
|
||||
eyebrow={<>Roteiro · {story.kind === "documentary" ? "vídeo documental" : `${terms.one} ${ep.number}`}</>}
|
||||
title={title || ep.title || story.title}
|
||||
description={<code className="text-xs">{ep.scriptPath}</code>}
|
||||
actions={<>
|
||||
<LinkButton variant="ghost" href={episodeHref}><ArrowLeftIcon size={16} />Voltar ao {terms.one}</LinkButton>
|
||||
<LinkButton variant="flame" href={`/agent?story=${story.id}&episode=${ep.id}&kind=script`}><SparkIcon size={16} />Revisar com IA</LinkButton>
|
||||
</>} />
|
||||
{script ? <ScriptReader markdown={script} /> : (
|
||||
<EmptyState icon={<SparkIcon />} title="Roteiro ainda não escrito"
|
||||
action={<LinkButton variant="primary" href={`/agent?story=${story.id}&episode=${ep.id}&kind=script`}><SparkIcon size={16} />Escrever roteiro com IA</LinkButton>}>
|
||||
Quando o roteiro existir, ele aparece aqui, trecho a trecho.
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { connection } from "next/server";
|
||||
import { AssetTable } from "@/components/asset-table";
|
||||
import { AssetUpload } from "@/components/asset-upload";
|
||||
import { DeleteStoryButton } from "@/components/delete-story-button";
|
||||
import { CreateEpisodeForm } from "@/components/forms";
|
||||
import { ArrowRightIcon, BookIcon, ClockIcon, FilmIcon, FlowIcon, FolderIcon, PenIcon, SparkIcon, UploadIcon, UsersIcon } from "@/components/icons";
|
||||
import { PLATFORM_META } from "@/components/platforms";
|
||||
import { StoryFlowView } from "@/components/story-flow";
|
||||
import { storyFormatLabel, unitTerms } from "@/components/story-formats";
|
||||
import { Tabs } from "@/components/tabs";
|
||||
import {
|
||||
Badge, Breadcrumb, CHOICE_STYLE, Card, EmptyState, LinkButton, Meta, PageHeader, SectionHeader, StagePipeline, episodeCode, formatDate, formatRelative,
|
||||
} from "@/components/ui";
|
||||
import { listAccounts, type AccountView } from "@/lib/accounts";
|
||||
import { ASSET_KINDS, listAssets } from "@/lib/assets";
|
||||
import { storyFlow } from "@/lib/flow";
|
||||
import { getStory, listEpisodes, listStories } from "@/lib/stories";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ storyId: string }> }) {
|
||||
const { storyId } = await params;
|
||||
return { title: getStory(storyId)?.title ?? "História" };
|
||||
}
|
||||
|
||||
export default async function StoryPage({ params }: { params: Promise<{ storyId: string }> }) {
|
||||
await connection();
|
||||
const { storyId } = await params;
|
||||
const story = getStory(storyId);
|
||||
if (!story) notFound();
|
||||
const episodes = listEpisodes(storyId);
|
||||
const assets = listAssets({ storyId });
|
||||
const last = episodes.at(-1);
|
||||
const interactive = story.kind === "interactive";
|
||||
const terms = unitTerms(story.kind);
|
||||
// Roteiro para o botão "Ler roteiro": o do último episódio que já tem roteiro (no documental, o vídeo).
|
||||
const withScript = [...episodes].reverse().find((e) => e.hasScript);
|
||||
const nextBlocked = interactive && last && !last.decision;
|
||||
const flow = storyFlow(storyId)!;
|
||||
const accounts = listAccounts().filter((a) => a.stories.some((l) => l.story_id === storyId));
|
||||
const activeAccounts = accounts.filter((a) => a.stories.some((l) => l.story_id === storyId && l.status === "active")).length;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
breadcrumb={<Breadcrumb items={[{ href: "/", label: "Histórias" }, { label: story.title }]} />}
|
||||
eyebrow={<>{story.kind === "documentary" ? "Vídeo documental" : `História ${storyFormatLabel(story.kind)}`}</>}
|
||||
title={story.title}
|
||||
description={story.logline || <span className="text-fg-subtle">Sem premissa definida ainda.</span>}
|
||||
meta={<>
|
||||
<Meta icon={<FilmIcon size={15} />}>{episodes.length} {episodes.length === 1 ? terms.one : terms.many}</Meta>
|
||||
<Meta icon={<FolderIcon size={15} />}><code>stories/{story.id}/</code></Meta>
|
||||
<Meta icon={<ClockIcon size={15} />}>atualizada {formatRelative(story.updated_at)}</Meta>
|
||||
</>}
|
||||
actions={<>
|
||||
{withScript && <LinkButton variant="secondary" href={`/stories/${story.id}/episodes/${withScript.number}/roteiro`}><BookIcon size={16} />Ler roteiro</LinkButton>}
|
||||
<LinkButton variant="flame" href={`/agent?story=${story.id}&kind=script`}><SparkIcon size={16} />Escrever com IA</LinkButton>
|
||||
<DeleteStoryButton storyId={story.id} title={story.title} />
|
||||
</>} />
|
||||
|
||||
<Tabs label="Seções da história" defaultTab="episodes"
|
||||
items={[
|
||||
{ id: "episodes", label: terms.Many, icon: <FilmIcon size={16} />, count: episodes.length },
|
||||
{ id: "flow", label: "Fluxo", icon: <FlowIcon size={16} /> },
|
||||
{ id: "accounts", label: "Canais de publicação", icon: <UsersIcon size={16} />, count: activeAccounts },
|
||||
]}
|
||||
panels={{
|
||||
episodes: <>
|
||||
<section aria-labelledby="episodios" className="grid gap-5">
|
||||
<SectionHeader id="episodios" eyebrow={story.kind === "documentary" ? "Produção" : "Temporada"} title={terms.Many}
|
||||
description={interactive ? `Cada episódio termina numa escolha com ${story.branch_count} opções decidida pelos comentários; o próximo continua a opção vencedora.` : undefined} />
|
||||
|
||||
{episodes.length === 0 ? (
|
||||
<EmptyState icon={<FilmIcon />} title={`Nenhum ${terms.one} ainda`}>
|
||||
Crie o {terms.code(1)} logo abaixo. Em seguida, abra o {terms.one} e peça o roteiro ao agente.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<ol className="grid gap-3">
|
||||
{episodes.map((ep) => (
|
||||
<li key={ep.id}>
|
||||
<Link href={`/stories/${story.id}/episodes/${ep.number}`}
|
||||
className="group grid items-center gap-x-6 gap-y-3 rounded-card border border-line bg-surface px-5 py-4 shadow-card transition-[border-color,background-color] hover:border-line-strong hover:bg-raised/50 md:grid-cols-[4.5rem_minmax(0,1fr)_auto_auto_1.25rem]">
|
||||
<span className="font-mono text-[1.375rem] leading-none font-semibold tracking-tight text-fg-subtle transition-colors group-hover:text-accent">
|
||||
{terms.code(ep.number)}
|
||||
</span>
|
||||
<span className="grid min-w-0 gap-1">
|
||||
<span className="truncate font-display text-[1.0625rem] font-semibold text-fg">{story.kind === "documentary" ? story.title : ep.overlay?.title || ep.title || "Sem título"}</span>
|
||||
<span className="text-xs text-fg-subtle">
|
||||
{ep.parent_choice ? `Continua a escolha ${ep.parent_choice}` : story.kind === "documentary" ? "Roteiro do vídeo" : "Abertura"} · criado {formatDate(ep.created_at)}
|
||||
</span>
|
||||
</span>
|
||||
<StagePipeline stage={ep.stage} />
|
||||
<span className="min-w-28 md:text-right">
|
||||
{ep.decision
|
||||
? <Badge tone={CHOICE_STYLE[ep.decision.winner].tone}>venceu {ep.decision.winner}</Badge>
|
||||
: <span className="text-xs text-fg-subtle">{interactive ? "votação aberta" : "—"}</span>}
|
||||
</span>
|
||||
<ArrowRightIcon size={18} className="text-fg-subtle transition-transform group-hover:translate-x-0.5 group-hover:text-fg max-md:hidden" />
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-4 rounded-card border border-dashed border-line-strong px-5 py-4">
|
||||
<span className="grid size-9 place-items-center rounded-lg bg-raised text-fg-muted"><PenIcon size={16} /></span>
|
||||
{nextBlocked ? (
|
||||
<p className="text-sm text-fg-muted">Feche a votação do {episodeCode(last!.number)} para criar o próximo episódio a partir da escolha vencedora.</p>
|
||||
) : (
|
||||
<CreateEpisodeForm storyId={story.id} parentEpisodeId={interactive && last ? last.id : undefined}
|
||||
label={last ? `Criar ${terms.code(last.number + 1)}${interactive ? ` (escolha ${last.decision?.winner})` : ""}` : `Criar ${terms.code(1)}`} />
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="assets-historia" className="grid gap-5">
|
||||
<SectionHeader id="assets-historia" eyebrow="Recursos" title="Assets disponíveis"
|
||||
description="Os da biblioteca compartilhada e os exclusivos desta história." />
|
||||
<AssetTable assets={assets} showStory />
|
||||
<Card eyebrow={<><UploadIcon size={13} />Envio</>} title="Enviar asset para esta história">
|
||||
<AssetUpload stories={listStories().map((s) => ({ id: s.id, title: s.title }))} kinds={ASSET_KINDS} defaultStoryId={story.id} />
|
||||
</Card>
|
||||
</section>
|
||||
</>,
|
||||
flow: <StoryFlowView initial={flow} />,
|
||||
accounts: <StoryAccounts storyId={story.id} accounts={accounts} />,
|
||||
}} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Aba Contas: quais contas publicam (ou já publicaram) esta história. */
|
||||
function StoryAccounts({ storyId, accounts }: { storyId: string; accounts: AccountView[] }) {
|
||||
if (accounts.length === 0) {
|
||||
return (
|
||||
<EmptyState icon={<UsersIcon />} title="Nenhuma conta publica esta história"
|
||||
action={<LinkButton variant="primary" href="/accounts">Vincular em Contas</LinkButton>}>
|
||||
Em Contas, abra uma conta e use “Vincular história”. Uma história pode sair em várias contas ao mesmo tempo.
|
||||
</EmptyState>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section aria-labelledby="contas-historia" className="grid gap-5">
|
||||
<SectionHeader id="contas-historia" eyebrow="Distribuição" title="Contas que publicam esta história"
|
||||
actions={<LinkButton size="sm" href="/accounts"><UsersIcon size={15} />Gerenciar contas</LinkButton>} />
|
||||
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
|
||||
{accounts.map((a) => {
|
||||
const link = a.stories.find((l) => l.story_id === storyId)!;
|
||||
return (
|
||||
<li key={a.id}>
|
||||
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`}
|
||||
className="grid items-center gap-x-6 gap-y-2 px-5 py-3.5 transition-colors hover:bg-raised/50 md:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto]">
|
||||
<span className="grid min-w-0 gap-0.5">
|
||||
<span className="truncate font-medium text-fg">{a.name}</span>
|
||||
<span className="truncate text-xs text-fg-subtle">{a.niche || "sem nicho"}</span>
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1 text-xs text-fg-muted">
|
||||
{a.networks.length === 0 ? <span className="text-fg-subtle">nenhuma rede vinculada</span> : a.networks.map((n) => {
|
||||
const Icon = PLATFORM_META[n.platform].icon;
|
||||
return <span key={n.platform} className="inline-flex items-center gap-1.5" title={PLATFORM_META[n.platform].label}><Icon size={14} />{n.handle}</span>;
|
||||
})}
|
||||
</span>
|
||||
<span className="flex items-center gap-3 text-xs text-fg-subtle">
|
||||
{link.status === "active"
|
||||
? <><Badge tone="success">ativa</Badge>desde {formatDate(link.linked_at)}</>
|
||||
: <><Badge tone="neutral">encerrada</Badge>em {formatDate(link.ended_at)}</>}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { MicIcon, WaveIcon } from "@/components/icons";
|
||||
import { Meta, PageHeader } from "@/components/ui";
|
||||
import { VoiceStudio } from "@/components/voice-studio";
|
||||
|
||||
export const metadata = { title: "Vozes" };
|
||||
|
||||
// O estado do serviço de voz muda a cada segundo (reinício, download de modelo): a página busca
|
||||
// /api/voice/status no navegador e consulta de novo quando precisa, em vez de renderizar no servidor.
|
||||
export default async function VoicesPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
// ?text=: a narração vinda do leitor de roteiro ("Gerar áudio em Vozes"). O campo aceita até 2.000 caracteres.
|
||||
const initialText = (await searchParams).text?.slice(0, 2000);
|
||||
return (
|
||||
<>
|
||||
<PageHeader eyebrow="Áudio" title="Vozes"
|
||||
description="Narração dos episódios, vozes de personagem e legendas com tempo. Tudo roda no seu computador, pelo serviço de voz local."
|
||||
meta={<>
|
||||
<Meta icon={<MicIcon size={15} />}>Narração: Kokoro e Piper (offline) · Edge, Google e Azure (online)</Meta>
|
||||
<Meta icon={<WaveIcon size={15} />}>Legenda: Whisper · arquivo <code>.srt</code></Meta>
|
||||
</>} />
|
||||
<VoiceStudio initialText={initialText} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user