Painel: ordenar fila de cortes, horário específico ao publicar e capas preservadas
Clipador (fila de cortes) - Seletor "Ordenar": mais novos, mais antigos, maior/menor nota da IA, sinal mais forte e mais longos; a escolha fica lembrada no navegador. - A fila abre filtrada pela sessão que está gravando. - Gancho automático logo abaixo da câmera e legenda desviada enquanto o gancho a cobriria; posição do gancho editável no painel. Publicação - "Publicar este corte" ganha "Horário específico": um dia e hora para todas as redes ou um diferente por rede (timing "at" + scheduledAt por rede na rota POST /api/publishing/clips/[id]), com validação e testes. - Capa do vídeo publicado copiada para output/publishing/covers/: apagar a sessão no Clipador não quebra mais a miniatura do dashboard; jobs antigos migram no ciclo de sincronização. - Dashboard só usa capa que existe no disco; corrige a regex do número do episódio (link do episódio). - Canais de publicação: seletor compacto de canais e detalhe reorganizado. - Publicador: confirmação pela página pública quando o YouTube Studio fica com a caixa de envio aberta; estatísticas por rede. Skill cenaforge 1.44.0 com as regras e a armadilha das capas. Testes: painel 68/68, Clipador 279, Publicador 84. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,23 +1,27 @@
|
||||
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 { AccountCreateForm, AccountDetail } from "@/components/account-manager";
|
||||
import { PlusIcon, PublishIcon, SettingsIcon, UsersIcon } from "@/components/icons";
|
||||
import { EmptyState, LinkButton, Meta, PageHeader, cx } from "@/components/ui";
|
||||
import { listAccounts } from "@/lib/accounts";
|
||||
import { listAccounts, type AccountView } from "@/lib/accounts";
|
||||
import { listStories } from "@/lib/stories";
|
||||
|
||||
export const metadata = { title: "Canais de publicação" };
|
||||
|
||||
/** Estados de rede que pedem uma ação do dono (entrar de novo, conexão vencida, erro). */
|
||||
const ATTENTION = new Set(["needs_login", "expired", "error"]);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Canais de publicação (no código: accounts): seletor compacto de canais no topo e o detalhe em largura total.
|
||||
* `?account=<id>` abre o detalhe; `?new=1` abre o formulário de novo canal. Com um canal só, ele abre direto.
|
||||
*/
|
||||
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 selected = sp.account ? accounts.find((a) => a.id === sp.account)
|
||||
: !creating && accounts.length === 1 ? accounts[0] : undefined;
|
||||
const stories = listStories().map((s) => ({ id: s.id, title: s.title, kind: s.kind }));
|
||||
|
||||
return (
|
||||
@@ -27,64 +31,57 @@ export default async function AccountsPage({ searchParams }: { searchParams: Pro
|
||||
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>
|
||||
<div className="grid gap-6">
|
||||
{accounts.length > 0 && <AccountPicker accounts={accounts} selectedId={selected?.id} creating={creating} />}
|
||||
|
||||
{/* 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>
|
||||
{creating ? (
|
||||
<div className="max-w-2xl"><AccountCreateForm /></div>
|
||||
) : selected ? (
|
||||
<AccountDetail key={selected.id} account={selected} stories={stories} />
|
||||
) : sp.account ? (
|
||||
<EmptyState icon={<UsersIcon />} title="Canal não encontrado"
|
||||
action={<LinkButton href="/accounts">Ver todos</LinkButton>}>
|
||||
Ele pode ter sido apagado.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<EmptyState icon={<UsersIcon />} title="Escolha um canal">
|
||||
Abra um canal acima para conectar as redes, ajustar como publicar e ligar histórias e fontes de corte.
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Um chip por canal (com ponto de alerta se alguma rede pede atenção) e o botão "Novo canal". */
|
||||
function AccountPicker({ accounts, selectedId, creating }: { accounts: AccountView[]; selectedId?: string; creating: boolean }) {
|
||||
return (
|
||||
<nav aria-label="Canais de publicação" className="flex flex-wrap items-center gap-x-3 gap-y-3 border-b border-line pb-5">
|
||||
<ul className="flex min-w-0 flex-wrap gap-2">
|
||||
{accounts.map((a) => {
|
||||
const current = a.id === selectedId;
|
||||
const attention = a.networks.filter((n) => ATTENTION.has(n.status)).length;
|
||||
return (
|
||||
<li key={a.id}>
|
||||
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} aria-current={current ? "page" : undefined}
|
||||
title={attention > 0 ? `${a.name}: ${attention === 1 ? "uma rede precisa" : `${attention} redes precisam`} de atenção` : a.name}
|
||||
className={cx("inline-flex h-10 max-w-[20rem] items-center gap-2 rounded-full border px-4 text-sm font-medium transition-colors",
|
||||
current ? "border-accent/60 bg-accent-soft text-fg" : "border-line-strong bg-surface text-fg-muted hover:bg-raised hover:text-fg")}>
|
||||
<span className="truncate">{a.name}</span>
|
||||
{attention > 0 && <>
|
||||
<span aria-hidden="true" className="size-2 shrink-0 rounded-full bg-warning" />
|
||||
<span className="sr-only">({attention === 1 ? "uma rede precisa" : `${attention} redes precisam`} de atenção)</span>
|
||||
</>}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<LinkButton href="/accounts?new=1" variant={creating ? "secondary" : "ghost"} size="sm" aria-current={creating ? "page" : undefined}>
|
||||
<PlusIcon size={16} />Novo canal
|
||||
</LinkButton>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,13 +5,14 @@ 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"}.
|
||||
* Corpo (JSON): {accountId, platforms: ["youtube"|"tiktok"|"instagram"], timing?: "now"|"best_slot"|"at",
|
||||
* scheduledAt?: {youtube?: ISO, tiktok?: ISO, instagram?: ISO}} — com "at", um horário para cada rede escolhida.
|
||||
* → {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);
|
||||
const body = await readJson<{ accountId: string; platforms: string[]; timing: string; scheduledAt?: Record<string, string> }>(request);
|
||||
return Response.json(await publishClip(parseId(id), body));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
|
||||
@@ -2,24 +2,30 @@
|
||||
// Canais de publicação (a entidade `accounts`): criar, editar dados, conectar as redes (account-networks.tsx),
|
||||
// regras de publicação e ligar/encerrar histórias e fontes do Clipador. Fala com /api/accounts/*; depois de cada
|
||||
// mudança, router.refresh() atualiza a lista do servidor.
|
||||
//
|
||||
// Ordem do detalhe: cabeçalho (nome, atalhos, estado das 3 redes) → Redes → O que este canal publica → Como publicar
|
||||
// → dados e zona de perigo. Em tela larga (xl), Redes e Como publicar ficam à esquerda e "O que publica" à direita.
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState, useTransition, type FormEvent, type ReactNode } from "react";
|
||||
import { useEffect, useId, useState, useTransition, type FormEvent, type ReactNode } from "react";
|
||||
import type { AccountView } from "@/lib/accounts";
|
||||
import { PLATFORMS, type StoryKind } from "@/lib/types";
|
||||
import { apiCall } from "./api-client";
|
||||
import { PLATFORM_LABEL, clipperCall, isOfflineError, type ClipperChannel } from "./clipper-client";
|
||||
import { PlatformIcon } from "./clipper-sessions";
|
||||
import { PublishingNetworksCard, PublishingRulesCard } from "./account-networks";
|
||||
import { AlertIcon, FilmIcon, LinkIcon, PlusIcon, ScissorsIcon, TrashIcon, XIcon } from "./icons";
|
||||
import { PublishingNetworksCard, PublishingRulesCard, networkAnchor } from "./account-networks";
|
||||
import { Dialog } from "./dialog";
|
||||
import { AlertIcon, ChartIcon, FilmIcon, LinkIcon, PenIcon, PlusIcon, PublishIcon, ScissorsIcon, TrashIcon, XIcon } from "./icons";
|
||||
import { PLATFORM_META } from "./platforms";
|
||||
import { networkName, readNetwork } from "./publishing-client";
|
||||
import { readNetwork } from "./publishing-client";
|
||||
import { NETWORK_STATUS, networkStatusText } from "./publishing-ui";
|
||||
import { storyFormatLabel } from "./story-formats";
|
||||
import { Badge, Button, Card, Feedback, Field, Input, Select, Spinner, Textarea, formatDate } from "./ui";
|
||||
import { Badge, Button, Card, Eyebrow, Feedback, Field, Input, LinkButton, Select, Spinner, Textarea, cx, formatDate, type Tone } from "./ui";
|
||||
import { askConfirm } from "./confirm-dialog";
|
||||
|
||||
type StoryOption = { id: string; title: string; kind: StoryKind };
|
||||
type Message = { ok: boolean; text: string } | null;
|
||||
/** `key` diz qual ação gerou o retorno, para mostrá-lo perto de onde o clique aconteceu. */
|
||||
type Message = { ok: boolean; text: string; key: string } | null;
|
||||
|
||||
/** Executa uma chamada, mostra o retorno e atualiza a página do servidor. */
|
||||
function useMutation() {
|
||||
@@ -33,10 +39,10 @@ function useMutation() {
|
||||
const result = await call();
|
||||
setPending(null);
|
||||
if (!result.ok) {
|
||||
setMessage({ ok: false, text: result.error });
|
||||
setMessage({ ok: false, text: result.error, key });
|
||||
return false;
|
||||
}
|
||||
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success });
|
||||
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success, key });
|
||||
after?.(result.data);
|
||||
startTransition(() => router.refresh());
|
||||
return true;
|
||||
@@ -44,6 +50,15 @@ function useMutation() {
|
||||
return { pending, message, setMessage, run, router };
|
||||
}
|
||||
|
||||
/** Retorno de uma ação, só se veio de uma das chaves pedidas (prefixos). */
|
||||
function messageFor(message: Message, ...prefixes: string[]): Message {
|
||||
return message && prefixes.some((p) => message.key.startsWith(p)) ? message : null;
|
||||
}
|
||||
|
||||
function plural(n: number, one: string, many: string): string {
|
||||
return `${n} ${n === 1 ? one : many}`;
|
||||
}
|
||||
|
||||
/* ---------- Novo canal de publicação ---------- */
|
||||
|
||||
export function AccountCreateForm() {
|
||||
@@ -60,7 +75,7 @@ export function AccountCreateForm() {
|
||||
}
|
||||
return (
|
||||
<Card eyebrow={<><PlusIcon size={13} />Novo canal</>} title="Criar canal de publicação"
|
||||
description="Reúne seus perfis no YouTube, TikTok e Instagram."
|
||||
description="Reúne seus perfis no YouTube, TikTok e Instagram. Depois de criar, conecte as redes e escolha o que ele publica."
|
||||
actions={<Link href="/accounts" aria-label="Cancelar" className="grid size-8 place-items-center rounded-control text-fg-subtle hover:bg-raised hover:text-fg"><XIcon size={16} /></Link>}>
|
||||
<form onSubmit={submit} className="grid gap-4">
|
||||
<Field label="Nome" hint="Entre 2 e 60 caracteres. Vira o identificador do canal.">
|
||||
@@ -85,19 +100,205 @@ export function AccountCreateForm() {
|
||||
|
||||
export function AccountDetail({ account, stories }: { account: AccountView; stories: StoryOption[] }) {
|
||||
const { pending, message, run, router } = useMutation();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const base = `/api/accounts/${encodeURIComponent(account.id)}`;
|
||||
const active = account.stories.filter((s) => s.status === "active");
|
||||
const ended = account.stories.filter((s) => s.status === "ended");
|
||||
const linkable = stories.filter((s) => !active.some((a) => a.story_id === s.id));
|
||||
const activeStories = account.stories.filter((s) => s.status === "active").length;
|
||||
const activeChannels = account.channels.filter((c) => c.status === "active").length;
|
||||
// Quem já publica algo vem primeiro: canal só de histórias mostra Histórias no topo; o resto, as fontes de corte.
|
||||
const storiesFirst = activeStories > 0 && activeChannels === 0;
|
||||
|
||||
async function save(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const form = new FormData(e.currentTarget);
|
||||
await run("save", () => apiCall<AccountView>(base, "PATCH", {
|
||||
const ok = await run("save", () => apiCall<AccountView>(base, "PATCH", {
|
||||
name: String(form.get("name") ?? ""), niche: String(form.get("niche") ?? ""), notes: String(form.get("notes") ?? ""),
|
||||
}), "Dados do canal salvos.");
|
||||
if (ok) setEditing(false);
|
||||
}
|
||||
|
||||
const saveMessage = messageFor(message, "save");
|
||||
const publishesMessage = messageFor(message, "link-story", "end-", "link-channel");
|
||||
const deleteMessage = messageFor(message, "delete");
|
||||
const formId = useId();
|
||||
const channelsSection = <LiveChannelsSection key="channels" account={account} base={base} pending={pending} run={run} />;
|
||||
const storiesSection = <StoriesSection key="stories" account={account} stories={stories} base={base} pending={pending} run={run} />;
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<AccountHeader account={account} activeStories={activeStories} activeChannels={activeChannels} onEdit={() => setEditing(true)} />
|
||||
<div aria-live="polite" className="empty:hidden">{saveMessage && !editing && <Feedback ok={saveMessage.ok}>{saveMessage.text}</Feedback>}</div>
|
||||
|
||||
{/* Tela larga: Redes e Como publicar à esquerda, "O que publica" à direita ocupando as duas linhas.
|
||||
Tela estreita: a ordem do DOM vale (Redes → O que publica → Como publicar). */}
|
||||
<div className="grid items-start gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)] xl:grid-rows-[auto_1fr]">
|
||||
<PublishingNetworksCard account={account} className="xl:col-start-1 xl:row-start-1" />
|
||||
|
||||
<Card title="O que este canal publica" className="xl:col-start-2 xl:row-span-2 xl:row-start-1"
|
||||
description="O que você aprovar destas fontes e histórias sai nas redes deste canal.">
|
||||
<div className="grid gap-6">
|
||||
<div aria-live="polite" className="empty:hidden">{publishesMessage && <Feedback ok={publishesMessage.ok}>{publishesMessage.text}</Feedback>}</div>
|
||||
{/* Ordem no DOM = ordem visual (o foco do teclado segue a mesma sequência). */}
|
||||
<div className="grid gap-7">
|
||||
{storiesFirst ? storiesSection : channelsSection}
|
||||
<div aria-hidden="true" className="h-px bg-line" />
|
||||
{storiesFirst ? channelsSection : storiesSection}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<PublishingRulesCard account={account} className="xl:col-start-1 xl:row-start-2" />
|
||||
</div>
|
||||
|
||||
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]">
|
||||
<AccountDataCard account={account} onEdit={() => setEditing(true)} />
|
||||
|
||||
<section aria-labelledby={`${formId}-apagar`} className="grid gap-3 rounded-card border border-danger/20 px-6 py-5">
|
||||
<h2 id={`${formId}-apagar`} className="text-[0.9375rem] font-semibold text-fg">Apagar canal</h2>
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-muted">Apagar o canal remove as conexões com as redes, os vínculos e o histórico de publicações dele. As histórias continuam, e os vídeos já publicados ficam nas redes.</p>
|
||||
<div>
|
||||
<Button variant="danger" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Apagar o canal “${account.name}”?`,
|
||||
message: "Conexões com as redes, vínculos e histórico de publicações saem junto. Não dá para desfazer.",
|
||||
confirmLabel: "Apagar canal", tone: "danger" }))) return;
|
||||
void run("delete", () => apiCall<{ ok: true }>(base, "DELETE"), "Canal apagado.", () => router.push("/accounts"));
|
||||
}}>
|
||||
{pending === "delete" ? <Spinner /> : <TrashIcon size={15} />}Apagar canal
|
||||
</Button>
|
||||
</div>
|
||||
<div aria-live="polite" className="empty:hidden">{deleteMessage && <Feedback ok={deleteMessage.ok}>{deleteMessage.text}</Feedback>}</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<Dialog open={editing} onClose={() => setEditing(false)} size="sm" eyebrow="Canal de publicação" title="Editar dados do canal"
|
||||
description="Nome, nicho e notas. Não mexe nas redes nem no que o canal publica."
|
||||
footer={<>
|
||||
<Button type="button" variant="ghost" onClick={() => setEditing(false)}>Cancelar</Button>
|
||||
<Button type="submit" form={formId} disabled={pending !== null}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar dados"}</Button>
|
||||
</>}>
|
||||
<form id={formId} key={account.updated_at} onSubmit={save} className="grid gap-4">
|
||||
<Field label="Nome"><Input name="name" required minLength={2} maxLength={60} defaultValue={account.name} autoFocus /></Field>
|
||||
<Field label="Nicho"><Input name="niche" maxLength={60} defaultValue={account.niche} placeholder="Ex.: suspense leve" /></Field>
|
||||
<Field label="Notas"><Textarea name="notes" rows={4} maxLength={500} defaultValue={account.notes} /></Field>
|
||||
<div aria-live="polite" className="empty:hidden">{saveMessage && !saveMessage.ok && <Feedback ok={false}>{saveMessage.text}</Feedback>}</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Cabeçalho do canal ---------- */
|
||||
|
||||
const CHIP_TONE: Partial<Record<Tone, string>> = {
|
||||
neutral: "border-line-strong text-fg-muted", info: "border-info/30 text-info", success: "border-success/30 text-success",
|
||||
warning: "border-warning/35 text-warning", danger: "border-danger/35 text-danger",
|
||||
};
|
||||
|
||||
/** Nome, nicho, atalhos e o estado das três redes em chips legíveis ("TikTok · Conectado"). */
|
||||
function AccountHeader({ account, activeStories, activeChannels, onEdit }: {
|
||||
account: AccountView; activeStories: number; activeChannels: number; onEdit: () => void;
|
||||
}) {
|
||||
const titleId = useId();
|
||||
const publishes = activeStories + activeChannels === 0
|
||||
// Sem nada ligado o canal ainda publica o que você mandar à mão ("Publicar" no corte do Clipador).
|
||||
? "Sem fonte nem história ligada: só sai o que você mandar publicar"
|
||||
: `Publica ${[activeChannels > 0 && plural(activeChannels, "fonte de corte", "fontes de corte"),
|
||||
activeStories > 0 && plural(activeStories, "história", "histórias")].filter(Boolean).join(" e ")}`;
|
||||
|
||||
return (
|
||||
<section aria-labelledby={titleId} className="grid gap-5 rounded-card border border-line bg-surface px-6 py-5 shadow-card">
|
||||
<div className="flex flex-wrap items-start justify-between gap-x-8 gap-y-4">
|
||||
<div className="min-w-0">
|
||||
<Eyebrow className="mb-2">Canal de publicação</Eyebrow>
|
||||
<h2 id={titleId} className="font-display text-[1.75rem] leading-tight font-semibold tracking-[-0.02em] break-words text-fg">{account.name}</h2>
|
||||
<p className="mt-1.5 text-sm text-fg-muted">
|
||||
{account.niche || <span className="text-fg-subtle">Sem nicho definido</span>}
|
||||
<span aria-hidden="true" className="px-2 text-fg-subtle">·</span>{publishes}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="secondary" size="sm" onClick={onEdit}><PenIcon size={15} />Editar dados</Button>
|
||||
<LinkButton variant="ghost" size="sm" href="/publishing"><PublishIcon size={15} />Publicações</LinkButton>
|
||||
<LinkButton variant="ghost" size="sm" href={`/dashboard?account=${encodeURIComponent(account.id)}`}><ChartIcon size={15} />Dashboard do canal</LinkButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul aria-label="Estado das redes" className="flex flex-wrap gap-2">
|
||||
{PLATFORMS.map((p) => {
|
||||
const raw = account.networks.find((n) => n.platform === p);
|
||||
const n = readNetwork(raw, p);
|
||||
const s = NETWORK_STATUS[n.status];
|
||||
const Icon = PLATFORM_META[p].icon;
|
||||
const paused = raw !== undefined && !n.enabled && n.status !== "disconnected";
|
||||
return (
|
||||
<li key={p}>
|
||||
<a href={`#${networkAnchor(p)}`} title={`${PLATFORM_META[p].label}: ${networkStatusText(n)}${paused ? " (pausado neste canal)" : ""}`}
|
||||
className={cx("inline-flex h-9 items-center gap-2 rounded-full border bg-raised px-3.5 text-[0.8125rem] font-medium transition-colors hover:bg-overlay",
|
||||
CHIP_TONE[s.tone] ?? CHIP_TONE.neutral)}>
|
||||
<Icon size={15} className="text-fg" />
|
||||
<span className="text-fg">{PLATFORM_META[p].label}</span>
|
||||
<span aria-hidden="true" className="text-fg-subtle">·</span>
|
||||
{s.icon}<span>{s.label}</span>
|
||||
{paused && <span className="text-warning">· pausado</span>}
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Dados do canal (fim da página) ---------- */
|
||||
|
||||
function AccountDataCard({ account, onEdit }: { account: AccountView; onEdit: () => void }) {
|
||||
return (
|
||||
<Card title="Dados do canal" actions={<Button variant="ghost" size="sm" onClick={onEdit}><PenIcon size={15} />Editar dados</Button>}>
|
||||
<dl className="grid gap-x-6 gap-y-4 text-sm sm:grid-cols-2">
|
||||
<div className="grid gap-1">
|
||||
<dt className="text-[0.8125rem] text-fg-subtle">Nicho</dt>
|
||||
<dd className="text-fg">{account.niche || <span className="text-fg-subtle">—</span>}</dd>
|
||||
</div>
|
||||
<div className="grid gap-1">
|
||||
<dt className="text-[0.8125rem] text-fg-subtle">Criado em</dt>
|
||||
<dd className="text-fg">{formatDate(account.created_at)}</dd>
|
||||
</div>
|
||||
<div className="grid gap-1 sm:col-span-2">
|
||||
<dt className="text-[0.8125rem] text-fg-subtle">Notas</dt>
|
||||
<dd className="leading-relaxed whitespace-pre-line text-fg-muted">{account.notes || <span className="text-fg-subtle">Sem notas.</span>}</dd>
|
||||
</div>
|
||||
<div className="grid gap-1 sm:col-span-2">
|
||||
<dt className="text-[0.8125rem] text-fg-subtle">Identificador</dt>
|
||||
<dd><code className="text-[0.8125rem] text-fg-muted">{account.id}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- O que este canal publica: subseções ---------- */
|
||||
|
||||
type Run = ReturnType<typeof useMutation>["run"];
|
||||
|
||||
/** Cabeçalho de subseção dentro do cartão "O que este canal publica". */
|
||||
function SubsectionHeader({ id, icon, title, count, children }: { id: string; icon: ReactNode; title: string; count: number; children: ReactNode }) {
|
||||
return (
|
||||
<header className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
|
||||
<div className="grid min-w-0 flex-1 basis-60 gap-1">
|
||||
<h3 id={id} className="flex items-center gap-2 text-[0.9375rem] font-semibold text-fg"><span className="text-accent">{icon}</span>{title}</h3>
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle">{children}</p>
|
||||
</div>
|
||||
<Badge tone={count > 0 ? "success" : "neutral"}>{count === 1 ? "1 ativa" : `${count} ativas`}</Badge>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function StoriesSection({ account, stories, base, pending, run }: { account: AccountView; stories: StoryOption[]; base: string; pending: string | null; run: Run }) {
|
||||
const headingId = useId();
|
||||
const active = account.stories.filter((s) => s.status === "active");
|
||||
const ended = account.stories.filter((s) => s.status === "ended");
|
||||
const linkable = stories.filter((s) => !active.some((a) => a.story_id === s.id));
|
||||
|
||||
async function linkStory(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const storyId = String(new FormData(e.currentTarget).get("storyId") ?? "");
|
||||
@@ -107,104 +308,79 @@ export function AccountDetail({ account, stories }: { account: AccountView; stor
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
|
||||
<section aria-labelledby={headingId} className="grid gap-4">
|
||||
<SubsectionHeader id={headingId} icon={<FilmIcon size={16} />} title="Histórias" count={active.length}>
|
||||
Várias podem estar ativas ao mesmo tempo. Encerrar tira das ativas, mas a história fica no histórico e nas métricas.
|
||||
</SubsectionHeader>
|
||||
|
||||
<Card eyebrow="Canal de publicação" title={account.name}
|
||||
description={<>Criada em {formatDate(account.created_at)} · identificador <code>{account.id}</code></>}>
|
||||
<form key={account.updated_at} onSubmit={save} className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Nome"><Input name="name" required minLength={2} maxLength={60} defaultValue={account.name} /></Field>
|
||||
<Field label="Nicho"><Input name="niche" maxLength={60} defaultValue={account.niche} placeholder="Ex.: suspense leve" /></Field>
|
||||
</div>
|
||||
<Field label="Notas"><Textarea name="notes" rows={2} maxLength={500} defaultValue={account.notes} /></Field>
|
||||
<div><Button variant="secondary" size="sm" disabled={pending !== null}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar dados"}</Button></div>
|
||||
</form>
|
||||
</Card>
|
||||
{active.length === 0 ? (
|
||||
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma história ativa neste canal.</p>
|
||||
) : (
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line">
|
||||
{active.map((s) => (
|
||||
<li key={s.story_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-3">
|
||||
<FilmIcon size={16} className="text-fg-subtle" />
|
||||
<span className="grid min-w-40 flex-1 gap-0.5">
|
||||
<Link href={`/stories/${s.story_id}`} className="truncate text-sm font-medium text-fg hover:text-accent hover:underline">{s.title}</Link>
|
||||
<span className="text-[0.8125rem] text-fg-subtle">{storyFormatLabel(s.kind)} · desde {formatDate(s.linked_at)}</span>
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Encerrar “${s.title}” neste canal?`,
|
||||
message: "Ela sai das ativas, mas fica no histórico e nas métricas.", confirmLabel: "Encerrar" }))) return;
|
||||
void run(`end-${s.story_id}`, () => apiCall<AccountView>(`${base}/stories/${encodeURIComponent(s.story_id)}`, "DELETE"), `“${s.title}” encerrada neste canal.`);
|
||||
}}>
|
||||
{pending === `end-${s.story_id}` ? <Spinner /> : null}Encerrar
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<PublishingNetworksCard account={account} />
|
||||
<PublishingRulesCard account={account} />
|
||||
|
||||
<Card title="Histórias" description="Várias podem estar ativas ao mesmo tempo. Encerrar tira das ativas, mas a história fica no histórico e nas métricas.">
|
||||
<div className="grid gap-5">
|
||||
{active.length === 0 ? (
|
||||
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma história ativa neste canal.</p>
|
||||
) : (
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line">
|
||||
{active.map((s) => (
|
||||
<li key={s.story_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-2.5">
|
||||
<FilmIcon size={16} className="text-fg-subtle" />
|
||||
<span className="grid min-w-40 flex-1 gap-0.5">
|
||||
<Link href={`/stories/${s.story_id}`} className="truncate text-sm font-medium text-fg hover:text-accent hover:underline">{s.title}</Link>
|
||||
<span className="text-xs text-fg-subtle">{storyFormatLabel(s.kind)} · desde {formatDate(s.linked_at)}</span>
|
||||
</span>
|
||||
<Badge tone="success">ativa</Badge>
|
||||
<Button variant="ghost" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Encerrar “${s.title}” neste canal?`,
|
||||
message: "Ela sai das ativas, mas fica no histórico e nas métricas.", confirmLabel: "Encerrar" }))) return;
|
||||
void run(`end-${s.story_id}`, () => apiCall<AccountView>(`${base}/stories/${encodeURIComponent(s.story_id)}`, "DELETE"), `“${s.title}” encerrada neste canal.`);
|
||||
}}>
|
||||
{pending === `end-${s.story_id}` ? <Spinner /> : null}Encerrar
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<form onSubmit={linkStory} className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Vincular história" className="min-w-0 flex-1 basis-56">
|
||||
<Select name="storyId" defaultValue="" required disabled={linkable.length === 0}>
|
||||
<option value="" disabled>{linkable.length === 0 ? "Todas as histórias já estão ativas" : "Escolha uma história…"}</option>
|
||||
{linkable.map((s) => <option key={s.id} value={s.id}>{s.title}{ended.some((e) => e.story_id === s.id) ? " (reativar)" : ""}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
<Button disabled={pending !== null || linkable.length === 0}>
|
||||
{pending === "link-story" ? <Spinner /> : <LinkIcon size={16} />}Vincular
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{ended.length > 0 && (
|
||||
<div className="grid gap-2">
|
||||
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Histórico · encerradas</h3>
|
||||
<ul className="grid gap-1 text-sm">
|
||||
{ended.map((s) => (
|
||||
<li key={s.story_id} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-1.5 text-fg-muted hover:bg-raised/40">
|
||||
<Link href={`/stories/${s.story_id}`} className="min-w-0 truncate hover:text-fg hover:underline">{s.title}</Link>
|
||||
<span className="text-xs text-fg-subtle">{formatDate(s.linked_at)} → {formatDate(s.ended_at)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<LiveChannelsCard account={account} base={base} pending={pending} run={run} />
|
||||
|
||||
<section aria-label="Apagar canal" className="flex flex-wrap items-center justify-between gap-4 rounded-card border border-danger/25 bg-danger-soft/40 px-6 py-4">
|
||||
<p className="text-sm text-fg-muted">Apagar o canal remove as conexões com as redes, os vínculos e o histórico de publicações dele. As histórias continuam, e os vídeos já publicados ficam nas redes.</p>
|
||||
<Button variant="danger" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Apagar o canal “${account.name}”?`,
|
||||
message: "Conexões com as redes, vínculos e histórico de publicações saem junto. Não dá para desfazer.",
|
||||
confirmLabel: "Apagar canal", tone: "danger" }))) return;
|
||||
void run("delete", () => apiCall<{ ok: true }>(base, "DELETE"), "Canal apagado.", () => router.push("/accounts"));
|
||||
}}>
|
||||
{pending === "delete" ? <Spinner /> : <TrashIcon size={15} />}Apagar canal
|
||||
<form onSubmit={linkStory} className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Vincular história" className="min-w-0 flex-1 basis-56">
|
||||
<Select name="storyId" defaultValue="" required disabled={linkable.length === 0}>
|
||||
<option value="" disabled>{linkable.length === 0 ? "Todas as histórias já estão ativas" : "Escolha uma história…"}</option>
|
||||
{linkable.map((s) => <option key={s.id} value={s.id}>{s.title}{ended.some((e) => e.story_id === s.id) ? " (reativar)" : ""}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
<Button variant="secondary" disabled={pending !== null || linkable.length === 0}>
|
||||
{pending === "link-story" ? <Spinner /> : <LinkIcon size={16} />}Vincular
|
||||
</Button>
|
||||
</section>
|
||||
</form>
|
||||
|
||||
{ended.length > 0 && <EndedList items={ended.map((s) => ({
|
||||
key: s.story_id, linkedAt: s.linked_at, endedAt: s.ended_at,
|
||||
label: <Link href={`/stories/${s.story_id}`} className="min-w-0 truncate hover:text-fg hover:underline">{s.title}</Link>,
|
||||
}))} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Histórico de vínculos encerrados (histórias ou fontes). */
|
||||
function EndedList({ items }: { items: { key: string; label: ReactNode; linkedAt: string; endedAt: string | null }[] }) {
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Histórico · encerradas</h4>
|
||||
<ul className="grid gap-1 text-sm">
|
||||
{items.map((i) => (
|
||||
<li key={i.key} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-1.5 text-fg-muted hover:bg-raised/40">
|
||||
{i.label}
|
||||
<span className="text-[0.8125rem] text-fg-subtle">{formatDate(i.linkedAt)} → {formatDate(i.endedAt)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Fontes do Clipador (no código: channels) ---------- */
|
||||
|
||||
type Run = ReturnType<typeof useMutation>["run"];
|
||||
type Catalog = { ok: true; channels: ClipperChannel[] } | { ok: false; offline: boolean; error: string } | null;
|
||||
|
||||
/** Fontes (lives) do Clipador ligadas ao canal: os cortes aprovados delas saem nas redes deste canal. */
|
||||
function LiveChannelsCard({ account, base, pending, run }: { account: AccountView; base: string; pending: string | null; run: Run }) {
|
||||
function LiveChannelsSection({ account, base, pending, run }: { account: AccountView; base: string; pending: string | null; run: Run }) {
|
||||
const headingId = useId();
|
||||
const [catalog, setCatalog] = useState<Catalog>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -233,103 +409,70 @@ function LiveChannelsCard({ account, base, pending, run }: { account: AccountVie
|
||||
}
|
||||
|
||||
return (
|
||||
<Card eyebrow={<><ScissorsIcon size={13} />Clipador</>} title="Fontes de corte"
|
||||
description={<>Lives de onde saem os cortes publicados por este canal. As fontes são cadastradas no <Link href="/clipper?tab=canais" className="text-fg-muted underline underline-offset-2 hover:text-fg">Clipador</Link>.</>}>
|
||||
<div className="grid gap-5">
|
||||
{catalog && !catalog.ok && (
|
||||
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
|
||||
<AlertIcon size={14} className="mt-px" />
|
||||
{catalog.offline ? "O Clipador está fora do ar: as fontes aparecem pelo identificador e não dá para ligar novas agora." : catalog.error}
|
||||
</p>
|
||||
)}
|
||||
<section aria-labelledby={headingId} className="grid gap-4">
|
||||
<SubsectionHeader id={headingId} icon={<ScissorsIcon size={16} />} title="Fontes de corte do Clipador" count={active.length}>
|
||||
Lives de onde saem os cortes publicados por este canal. As fontes são cadastradas no <Link href="/clipper?tab=canais" className="font-medium text-fg-muted underline underline-offset-2 hover:text-fg">Clipador</Link>.
|
||||
</SubsectionHeader>
|
||||
|
||||
{active.length === 0 ? (
|
||||
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma fonte ligada a este canal.</p>
|
||||
) : (
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line">
|
||||
{active.map((l) => {
|
||||
const c = find(l.channel_id);
|
||||
return (
|
||||
<li key={l.channel_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-2.5">
|
||||
{c ? <PlatformIcon platform={c.platform} size={16} className="text-fg-subtle" /> : <ScissorsIcon size={16} className="text-fg-subtle" />}
|
||||
<span className="grid min-w-40 flex-1 gap-0.5">
|
||||
<span className="truncate text-sm font-medium text-fg">{c ? c.displayName || c.channel : <code>{l.channel_id}</code>}</span>
|
||||
<span className="text-xs text-fg-subtle">{c ? `${PLATFORM_LABEL[c.platform]} · ` : ""}desde {formatDate(l.linked_at)}</span>
|
||||
</span>
|
||||
{c && !c.authorized && <Badge tone="warning" dot={false}>sem autorização</Badge>}
|
||||
<Badge tone="success">ativa</Badge>
|
||||
<Button variant="ghost" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Encerrar ${label(l.channel_id)} neste canal?`,
|
||||
message: "O vínculo fica no histórico.", confirmLabel: "Encerrar" }))) return;
|
||||
void run(`end-ch-${l.channel_id}`, () => apiCall<AccountView>(`${base}/channels/${encodeURIComponent(l.channel_id)}`, "DELETE"),
|
||||
`${label(l.channel_id)} encerrada neste canal.`);
|
||||
}}>
|
||||
{pending === `end-ch-${l.channel_id}` ? <Spinner /> : null}Encerrar
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{catalog && !catalog.ok && (
|
||||
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-[0.8125rem] text-warning">
|
||||
<AlertIcon size={15} className="mt-0.5 shrink-0" />
|
||||
{catalog.offline ? "O Clipador está fora do ar: as fontes aparecem pelo identificador e não dá para ligar novas agora." : catalog.error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={link} className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Ligar fonte" className="min-w-0 flex-1 basis-56">
|
||||
<Select name="channelId" defaultValue="" required disabled={!catalog?.ok || linkable.length === 0}>
|
||||
<option value="" disabled>
|
||||
{catalog === null ? "Carregando fontes…" : !catalog.ok ? "Clipador indisponível"
|
||||
: channels.length === 0 ? "Nenhuma fonte cadastrada no Clipador" : linkable.length === 0 ? "Todas as fontes já estão ligadas" : "Escolha uma fonte…"}
|
||||
{active.length === 0 ? (
|
||||
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma fonte ligada a este canal.</p>
|
||||
) : (
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line">
|
||||
{active.map((l) => {
|
||||
const c = find(l.channel_id);
|
||||
return (
|
||||
<li key={l.channel_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-3">
|
||||
{c ? <PlatformIcon platform={c.platform} size={16} className="text-fg-subtle" /> : <ScissorsIcon size={16} className="text-fg-subtle" />}
|
||||
<span className="grid min-w-40 flex-1 gap-0.5">
|
||||
<span className="truncate text-sm font-medium text-fg">{c ? c.displayName || c.channel : <code>{l.channel_id}</code>}</span>
|
||||
<span className="text-[0.8125rem] text-fg-subtle">{c ? `${PLATFORM_LABEL[c.platform]} · ` : ""}desde {formatDate(l.linked_at)}</span>
|
||||
</span>
|
||||
{c && !c.authorized && <Badge tone="warning" dot={false}>sem autorização</Badge>}
|
||||
<Button variant="ghost" size="sm" disabled={pending !== null}
|
||||
onClick={async () => {
|
||||
if (!(await askConfirm({ title: `Encerrar ${label(l.channel_id)} neste canal?`,
|
||||
message: "O vínculo fica no histórico.", confirmLabel: "Encerrar" }))) return;
|
||||
void run(`end-ch-${l.channel_id}`, () => apiCall<AccountView>(`${base}/channels/${encodeURIComponent(l.channel_id)}`, "DELETE"),
|
||||
`${label(l.channel_id)} encerrada neste canal.`);
|
||||
}}>
|
||||
{pending === `end-ch-${l.channel_id}` ? <Spinner /> : null}Encerrar
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<form onSubmit={link} className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Ligar fonte" className="min-w-0 flex-1 basis-56">
|
||||
<Select name="channelId" defaultValue="" required disabled={!catalog?.ok || linkable.length === 0}>
|
||||
<option value="" disabled>
|
||||
{catalog === null ? "Carregando fontes…" : !catalog.ok ? "Clipador indisponível"
|
||||
: channels.length === 0 ? "Nenhuma fonte cadastrada no Clipador" : linkable.length === 0 ? "Todas as fontes já estão ligadas" : "Escolha uma fonte…"}
|
||||
</option>
|
||||
{linkable.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.displayName || c.channel} · {PLATFORM_LABEL[c.platform]}{ended.some((e) => e.channel_id === c.id) ? " (religar)" : ""}
|
||||
</option>
|
||||
{linkable.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.displayName || c.channel} · {PLATFORM_LABEL[c.platform]}{ended.some((e) => e.channel_id === c.id) ? " (religar)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
<Button disabled={pending !== null || !catalog?.ok || linkable.length === 0}>
|
||||
{pending === "link-channel" ? <Spinner /> : <LinkIcon size={16} />}Ligar
|
||||
</Button>
|
||||
</form>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
<Button variant="secondary" disabled={pending !== null || !catalog?.ok || linkable.length === 0}>
|
||||
{pending === "link-channel" ? <Spinner /> : <LinkIcon size={16} />}Ligar
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{ended.length > 0 && (
|
||||
<div className="grid gap-2">
|
||||
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Histórico · encerradas</h3>
|
||||
<ul className="grid gap-1 text-sm">
|
||||
{ended.map((l) => (
|
||||
<li key={l.channel_id} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-1.5 text-fg-muted hover:bg-raised/40">
|
||||
<span className="min-w-0 truncate">{label(l.channel_id)}</span>
|
||||
<span className="text-xs text-fg-subtle">{formatDate(l.linked_at)} → {formatDate(l.ended_at)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/** Ícone de cada rede com o @ (conectada) ou o estado em palavras, para listas densas. */
|
||||
export function NetworkHandles({ networks, compact = false }: { networks: AccountView["networks"]; compact?: boolean }): ReactNode {
|
||||
const shown = PLATFORMS.map((p) => readNetwork(networks.find((n) => n.platform === p), p)).filter((n) => n.status !== "disconnected");
|
||||
if (shown.length === 0) return <span className="text-xs text-fg-subtle">nenhuma rede conectada</span>;
|
||||
return (
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-x-3.5 gap-y-1 text-xs text-fg-muted">
|
||||
{shown.map((n) => {
|
||||
const Icon = PLATFORM_META[n.platform].icon;
|
||||
const text = n.status === "connected" ? networkName(n) ?? "conectado"
|
||||
: n.status === "needs_login" || n.status === "expired" ? "entrar de novo" : n.status === "error" ? "erro" : "conectando";
|
||||
const attention = n.status !== "connected";
|
||||
return (
|
||||
<span key={n.platform} className="inline-flex min-w-0 items-center gap-1.5" title={`${PLATFORM_META[n.platform].label}: ${text}`}>
|
||||
<Icon size={14} className="text-fg-subtle" />
|
||||
{attention && <AlertIcon size={12} className="text-warning" />}
|
||||
{compact ? <span className="sr-only">{PLATFORM_META[n.platform].label}: {text}</span>
|
||||
: <span className={attention ? "truncate text-warning" : "truncate"}>{text}</span>}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
{ended.length > 0 && <EndedList items={ended.map((l) => ({
|
||||
key: l.channel_id, linkedAt: l.linked_at, endedAt: l.ended_at,
|
||||
label: <span className="min-w-0 truncate">{label(l.channel_id)}</span>,
|
||||
}))} />}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,14 +8,14 @@ import type { AccountView } from "@/lib/accounts";
|
||||
import { PLATFORMS, type Platform } from "@/lib/types";
|
||||
import { askConfirm } from "./confirm-dialog";
|
||||
import { ConnectWizard } from "./connect-wizard";
|
||||
import { CheckIcon, ChevronDownIcon, LinkIcon, RefreshIcon, SettingsIcon, UnlinkIcon } from "./icons";
|
||||
import { CheckIcon, ChevronDownIcon, LinkIcon, PauseIcon, RefreshIcon, SettingsIcon, UnlinkIcon } from "./icons";
|
||||
import { PLATFORM_META } from "./platforms";
|
||||
import {
|
||||
DAILY_LIMIT_MAX, MODE_LABEL, checkNetwork, disconnectNetwork, readNetwork, readRules, updateNetwork, updateRules,
|
||||
DAILY_LIMIT_MAX, MODE_LABEL, PRIVACY_LABEL, checkNetwork, disconnectNetwork, readNetwork, readRules, updateNetwork, updateRules,
|
||||
type AiLabel, type Privacy, type PublishingNetwork, type PublishingRules, type TiktokMode, type PublishTiming,
|
||||
} from "./publishing-client";
|
||||
import { NetworkStatusBadge, TextLink } from "./publishing-ui";
|
||||
import { Button, Card, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Switch, cx, formatRelative } from "./ui";
|
||||
import { Badge, Button, Card, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Switch, cx, formatRelative } from "./ui";
|
||||
|
||||
type Message = { ok: boolean; text: string } | null;
|
||||
|
||||
@@ -25,9 +25,22 @@ function useRefresh() {
|
||||
return () => startTransition(() => router.refresh());
|
||||
}
|
||||
|
||||
/** Âncora da linha de cada rede (os chips do cabeçalho do canal levam até ela). */
|
||||
export function networkAnchor(platform: Platform): string {
|
||||
return `rede-${platform}`;
|
||||
}
|
||||
|
||||
/** Resumo dos ajustes numa linha: "Até 3 por dia · Público · publica direto". */
|
||||
function settingsSummary(network: PublishingNetwork): string {
|
||||
const parts = [`Até ${network.daily_limit} por dia`];
|
||||
parts.push(network.platform === "instagram" ? "sempre público" : PRIVACY_LABEL[network.privacy]);
|
||||
if (network.platform === "tiktok") parts.push(network.tiktok_mode === "draft" ? "manda como rascunho" : "publica direto");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
/* ---------- Redes do canal ---------- */
|
||||
|
||||
export function PublishingNetworksCard({ account }: { account: AccountView }) {
|
||||
export function PublishingNetworksCard({ account, className }: { account: AccountView; className?: string }) {
|
||||
const refresh = useRefresh();
|
||||
const [wizard, setWizard] = useState<{ platform: Platform; reconnect: boolean } | null>(null);
|
||||
const networks = PLATFORMS.map((p) => {
|
||||
@@ -37,7 +50,7 @@ export function PublishingNetworksCard({ account }: { account: AccountView }) {
|
||||
const target = wizard ? networks.find((n) => n.platform === wizard.platform) : undefined;
|
||||
|
||||
return (
|
||||
<Card title="Redes"
|
||||
<Card title="Redes" className={className}
|
||||
description="Onde os vídeos deste canal são publicados. Conecte cada rede uma vez; o CenaForge envia sozinho depois que você aprova.">
|
||||
<ul className="grid divide-y divide-line rounded-control border border-line">
|
||||
{networks.map((n) => (
|
||||
@@ -46,7 +59,7 @@ export function PublishingNetworksCard({ account }: { account: AccountView }) {
|
||||
onConnect={(reconnect) => setWizard({ platform: n.platform, reconnect })} />
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 text-xs leading-relaxed text-fg-subtle">
|
||||
<p className="mt-4 text-[0.8125rem] leading-relaxed text-fg-subtle">
|
||||
O painel precisa estar aberto para publicar e agendar. Contas e chaves ficam só neste computador.
|
||||
</p>
|
||||
{wizard && target && (
|
||||
@@ -98,22 +111,23 @@ function NetworkRow({ accountId, platform, exists, network, onChanged, onConnect
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="grid gap-3 px-4 py-3.5">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2.5">
|
||||
<span className={cx("grid size-9 shrink-0 place-items-center rounded-lg border",
|
||||
<li id={networkAnchor(platform)} className="grid scroll-mt-6 gap-3 px-4 py-4 sm:px-5">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
|
||||
<span className={cx("grid size-11 shrink-0 place-items-center rounded-xl border",
|
||||
status === "connected" ? "border-line-strong bg-raised text-fg" : "border-line bg-sunken/40 text-fg-subtle")}>
|
||||
<Icon size={18} />
|
||||
<Icon size={22} />
|
||||
</span>
|
||||
<span className="grid min-w-40 flex-1 gap-1">
|
||||
<span className="grid min-w-48 flex-1 gap-1">
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-semibold text-fg">{meta.label}</span>
|
||||
<span className="text-[0.9375rem] font-semibold text-fg">{meta.label}</span>
|
||||
<NetworkStatusBadge network={network} />
|
||||
{exists && !network.enabled && <Badge tone="warning" dot={false}><PauseIcon size={13} />Pausado neste canal</Badge>}
|
||||
</span>
|
||||
<span className="text-xs text-fg-subtle">
|
||||
{network.mode ? MODE_LABEL[network.mode] : "Escolha como conectar"}
|
||||
<span className="text-[0.8125rem] text-fg-muted">
|
||||
{network.mode ? MODE_LABEL[network.mode] : "Ainda não conectado: escolha como conectar"}
|
||||
{network.checked_at && <> · conferido {formatRelative(network.checked_at)}</>}
|
||||
{exists && !network.enabled && <> · <span className="font-medium text-warning">pausado neste canal</span></>}
|
||||
</span>
|
||||
{linked && <span className="text-[0.8125rem] text-fg-subtle">{settingsSummary(network)}</span>}
|
||||
</span>
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
{status === "disconnected" && (
|
||||
@@ -145,11 +159,11 @@ function NetworkRow({ accountId, platform, exists, network, onChanged, onConnect
|
||||
</span>
|
||||
</div>
|
||||
{status === "error" && network.last_error && (
|
||||
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-xs break-words text-danger sm:ml-12">{network.last_error}</p>
|
||||
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-[0.8125rem] break-words text-danger sm:ml-15">{network.last_error}</p>
|
||||
)}
|
||||
<div aria-live="polite" className="empty:hidden sm:ml-12">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||||
<div aria-live="polite" className="empty:hidden sm:ml-15">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||||
{exists && (
|
||||
<div id={`ajustes-${platform}`} hidden={!open} className="sm:ml-12">
|
||||
<div id={`ajustes-${platform}`} hidden={!open} className="sm:ml-15">
|
||||
<NetworkSettings accountId={accountId} network={network} onChanged={onChanged} />
|
||||
</div>
|
||||
)}
|
||||
@@ -227,7 +241,7 @@ function NetworkSettings({ accountId, network, onChanged }: { accountId: string;
|
||||
</Select>
|
||||
</Field>
|
||||
) : (
|
||||
<p className="text-xs leading-relaxed text-fg-subtle sm:pt-7">No Instagram, os Reels saem sempre públicos.</p>
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle sm:pt-7">No Instagram, os Reels saem sempre públicos.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -245,7 +259,7 @@ function NetworkSettings({ accountId, network, onChanged }: { accountId: string;
|
||||
{ value: "direct", label: "Publicar direto", hint: "Sai na hora no perfil" },
|
||||
{ value: "draft", label: "Mandar como rascunho", hint: "Você termina no app" },
|
||||
]} />
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">Rascunho chega na caixa de entrada do app do TikTok; você revisa e publica de lá.</p>
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle">Rascunho chega na caixa de entrada do app do TikTok; você revisa e publica de lá.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -256,7 +270,7 @@ function NetworkSettings({ accountId, network, onChanged }: { accountId: string;
|
||||
|
||||
/* ---------- Regras do canal ---------- */
|
||||
|
||||
export function PublishingRulesCard({ account }: { account: AccountView }) {
|
||||
export function PublishingRulesCard({ account, className }: { account: AccountView; className?: string }) {
|
||||
const refresh = useRefresh();
|
||||
const [rules, setRules] = useState<PublishingRules>(() => readRules(account));
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
@@ -277,7 +291,7 @@ export function PublishingRulesCard({ account }: { account: AccountView }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Card title="Como publicar" description="Valem para todas as redes deste canal.">
|
||||
<Card title="Como publicar" description="Valem para todas as redes deste canal." className={className}>
|
||||
<div className="grid gap-6">
|
||||
<Switch label="Aprovar sozinho os vídeos novos?" checked={rules.approval_mode === "auto"} busy={busy === "approval_mode"} disabled={busy !== null}
|
||||
hint={rules.approval_mode === "auto"
|
||||
@@ -293,7 +307,7 @@ export function PublishingRulesCard({ account }: { account: AccountView }) {
|
||||
{ value: "now", label: "Na hora", hint: "Assim que aprovar" },
|
||||
{ value: "best_slot", label: "No próximo horário bom", hint: "Mais gente vendo" },
|
||||
]} />
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle">
|
||||
Os horários bons de cada rede ficam em <TextLink href="/settings">Configurações</TextLink>. Entre dois vídeos na mesma rede fica pelo menos 1 hora.
|
||||
</p>
|
||||
</div>
|
||||
@@ -306,7 +320,7 @@ export function PublishingRulesCard({ account }: { account: AccountView }) {
|
||||
{ value: "always", label: "Sempre" },
|
||||
{ value: "never", label: "Nunca" },
|
||||
]} />
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-subtle">
|
||||
As redes pedem um aviso quando o vídeo tem voz ou imagem realista feita por IA. Automático marca só quando o episódio usa voz clonada.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
// "Publicar" no cartão de um corte aprovado do Clipador: abre um diálogo para escolher o canal de publicação, as
|
||||
// redes (só as conectadas) e quando sai (agora ou no próximo horário bom). Não precisa ligar a fonte inteira ao
|
||||
// redes (só as conectadas) e quando sai (agora, no próximo horário bom ou num horário específico — o mesmo para
|
||||
// todas as redes ou um diferente por rede). Não precisa ligar a fonte inteira ao
|
||||
// canal: POST /api/publishing/clips/[id] cria os jobs já aprovados (o clique é a aprovação), com origem "manual".
|
||||
// Título e legenda são os do cartão (salvos). Cada rede mostra por que não pode ser escolhida, quando for o caso.
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -9,14 +10,29 @@ import type { Platform } from "@/lib/types";
|
||||
import { apiCall } from "./api-client";
|
||||
import type { Clip } from "./clipper-client";
|
||||
import { Dialog } from "./dialog";
|
||||
import { AlertIcon, CheckIcon, PublishIcon } from "./icons";
|
||||
import { AlertIcon, CheckIcon, ClockIcon, PublishIcon } from "./icons";
|
||||
import { PLATFORM_META } from "./platforms";
|
||||
import { publishClip, type PublishJob, type PublishTiming } from "./publishing-client";
|
||||
import { formatTime, publishClip, toLocalInput, type ClipTiming, type PublishJob } from "./publishing-client";
|
||||
import { TextLink } from "./publishing-ui";
|
||||
import { Button, ChoiceGroup, Feedback, Field, Select, Spinner, cx } from "./ui";
|
||||
import { Button, ChoiceGroup, Feedback, Field, Input, Select, Spinner, cx } from "./ui";
|
||||
|
||||
const PLATFORM_ORDER: Platform[] = ["youtube", "tiktok", "instagram"];
|
||||
|
||||
/** Sugestão inicial do horário específico: a próxima hora cheia que esteja a pelo menos 30 min. */
|
||||
function suggestedTime(): string {
|
||||
const d = new Date(Date.now() + 30 * 60_000);
|
||||
d.setMinutes(60, 0, 0);
|
||||
return toLocalInput(d.toISOString());
|
||||
}
|
||||
|
||||
/** Valor do datetime-local → Date, ou o motivo de não servir. */
|
||||
function readLocalTime(value: string): Date | string {
|
||||
const date = new Date(value);
|
||||
if (!value || Number.isNaN(date.getTime())) return "Escolha o dia e a hora";
|
||||
if (date.getTime() < Date.now() - 60_000) return "Esse horário já passou";
|
||||
return date;
|
||||
}
|
||||
|
||||
const NETWORK_NOTE: Record<string, string> = {
|
||||
connected: "conectada",
|
||||
connecting: "ainda conectando (sai quando terminar)",
|
||||
@@ -63,7 +79,11 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [accountId, setAccountId] = useState("");
|
||||
const [chosen, setChosen] = useState<ReadonlySet<Platform>>(() => new Set());
|
||||
const [timing, setTiming] = useState<PublishTiming>("best_slot");
|
||||
const [timing, setTiming] = useState<ClipTiming>("best_slot");
|
||||
// Horário específico: um para todas as redes, ou (perNetwork) um por rede, que começa igual ao comum.
|
||||
const [sharedAt, setSharedAt] = useState(suggestedTime);
|
||||
const [perNetwork, setPerNetwork] = useState(false);
|
||||
const [atByPlatform, setAtByPlatform] = useState<Partial<Record<Platform, string>>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -104,21 +124,39 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
|
||||
if (on) next.add(platform); else next.delete(platform);
|
||||
return next;
|
||||
});
|
||||
const splitTimes = selected.length > 1;
|
||||
/** Horário (datetime-local) que a rede vai usar no modo "Horário específico". */
|
||||
const timeOf = (platform: Platform) => (perNetwork && splitTimes ? atByPlatform[platform] ?? sharedAt : sharedAt);
|
||||
|
||||
async function submit() {
|
||||
if (!account) { setError("Escolha um canal de publicação."); return; }
|
||||
if (selected.length === 0) { setError("Marque pelo menos uma rede."); return; }
|
||||
let scheduledAt: Partial<Record<Platform, string>> | undefined;
|
||||
if (timing === "at") {
|
||||
scheduledAt = {};
|
||||
for (const platform of selected) {
|
||||
const at = readLocalTime(timeOf(platform));
|
||||
if (typeof at === "string") {
|
||||
setError(perNetwork && splitTimes ? `${PLATFORM_META[platform].label}: ${at.toLowerCase()}.` : `${at}.`);
|
||||
return;
|
||||
}
|
||||
scheduledAt[platform] = at.toISOString();
|
||||
}
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const r = await publishClip(clip.id, { accountId: account.id, platforms: selected, timing });
|
||||
const r = await publishClip(clip.id, { accountId: account.id, platforms: selected, timing, scheduledAt });
|
||||
setBusy(false);
|
||||
if (!r.ok) { setError(r.error); return; }
|
||||
const label = (p: Platform) => PLATFORM_META[p].label;
|
||||
const skipped = r.data.skipped.map((s) => `${label(s.platform)}: ${s.reason}`).join("; ");
|
||||
const placed = r.data.placed;
|
||||
const scheduled = placed === 1 ? "1 rede agendada" : `${placed} redes agendadas`;
|
||||
const times = [...new Set(Object.values(scheduledAt ?? {}))];
|
||||
const head = placed === 0 ? "Nenhuma rede entrou na fila."
|
||||
: timing === "now" ? `${placed === 1 ? "1 rede" : `${placed} redes`} na fila para sair agora.`
|
||||
: `${placed === 1 ? "1 rede agendada" : `${placed} redes agendadas`} no próximo horário bom.`;
|
||||
: timing === "at" ? (times.length === 1 ? `${scheduled} para ${formatTime(times[0])}.` : `${scheduled} nos horários que você escolheu.`)
|
||||
: `${scheduled} no próximo horário bom.`;
|
||||
onDone({ ok: placed > 0, text: skipped ? `${head} Ficou de fora — ${skipped}.` : head });
|
||||
}
|
||||
|
||||
@@ -189,10 +227,23 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<ChoiceGroup name={`quando-${clip.id}`} legend="Quando sai" value={timing} onChange={setTiming} options={[
|
||||
{ value: "now", label: "Agora", hint: "no próximo ciclo (até 20 s)" },
|
||||
{ value: "best_slot", label: "No próximo horário bom", hint: "respeita o limite por dia" },
|
||||
]} />
|
||||
<div className="grid gap-3">
|
||||
<ChoiceGroup name={`quando-${clip.id}`} legend="Quando sai" value={timing} onChange={setTiming} options={[
|
||||
{ value: "now", label: "Agora", hint: "no próximo ciclo (até 20 s)" },
|
||||
{ value: "best_slot", label: "No próximo horário bom", hint: "respeita o limite por dia" },
|
||||
{ value: "at", label: "Horário específico", hint: "você escolhe dia e hora" },
|
||||
]} />
|
||||
{timing === "at" && (
|
||||
<SpecificTime clipId={clip.id} platforms={selected} perNetwork={perNetwork && splitTimes} canSplit={splitTimes}
|
||||
sharedAt={sharedAt} onShared={setSharedAt} timeOf={timeOf}
|
||||
onPerNetwork={(on) => {
|
||||
// Ao separar, cada rede começa no horário comum; ao juntar, volta a valer só o comum.
|
||||
if (on) setAtByPlatform(Object.fromEntries(selected.map((p) => [p, sharedAt])));
|
||||
setPerNetwork(on);
|
||||
}}
|
||||
onPlatformTime={(p, v) => setAtByPlatform((prev) => ({ ...prev, [p]: v }))} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -201,3 +252,48 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** Campos do "Horário específico": um dia e hora para todas as redes, ou um por rede (quando há mais de uma). */
|
||||
function SpecificTime({ clipId, platforms, perNetwork, canSplit, sharedAt, onShared, timeOf, onPerNetwork, onPlatformTime }: {
|
||||
clipId: number; platforms: Platform[]; perNetwork: boolean; canSplit: boolean;
|
||||
sharedAt: string; onShared: (value: string) => void; timeOf: (platform: Platform) => string;
|
||||
onPerNetwork: (on: boolean) => void; onPlatformTime: (platform: Platform, value: string) => void;
|
||||
}) {
|
||||
const min = toLocalInput(new Date().toISOString());
|
||||
return (
|
||||
<div className="grid gap-3 rounded-control border border-line bg-sunken/40 px-3.5 py-3">
|
||||
{perNetwork ? (
|
||||
<ul className="grid gap-2">
|
||||
{platforms.map((platform) => {
|
||||
const Icon = PLATFORM_META[platform].icon;
|
||||
const id = `horario-${clipId}-${platform}`;
|
||||
return (
|
||||
<li key={platform} className="grid grid-cols-[minmax(0,7rem)_minmax(0,1fr)] items-center gap-3">
|
||||
<label htmlFor={id} className="flex items-center gap-2 text-sm font-medium text-fg">
|
||||
<Icon size={15} />{PLATFORM_META[platform].label}
|
||||
</label>
|
||||
<Input id={id} type="datetime-local" min={min} value={timeOf(platform)}
|
||||
onChange={(e) => onPlatformTime(platform, e.target.value)} required />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<Field label={platforms.length > 1 ? "Dia e hora (todas as redes)" : "Dia e hora"}>
|
||||
<Input type="datetime-local" min={min} value={sharedAt} onChange={(e) => onShared(e.target.value)} required />
|
||||
</Field>
|
||||
)}
|
||||
{canSplit && (
|
||||
<label className="flex cursor-pointer items-center gap-2 text-[0.8125rem] text-fg-muted hover:text-fg">
|
||||
<input type="checkbox" className="size-4 shrink-0 accent-accent" checked={perNetwork}
|
||||
onChange={(e) => onPerNetwork(e.target.checked)} />
|
||||
Horário diferente para cada rede
|
||||
</label>
|
||||
)}
|
||||
<p className="flex items-start gap-1.5 text-xs leading-relaxed text-fg-subtle">
|
||||
<ClockIcon size={13} className="mt-0.5 shrink-0" />
|
||||
<span>Horário deste computador. Sai nesse horário, sem passar pelo horário bom nem pelo limite por dia. Dá para mudar depois em Publicações.</span>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -441,12 +441,13 @@ export function sourceName(channelId: string | null, url: string, channels: Clip
|
||||
export type HookStyle = "plain" | "banner";
|
||||
/** `slide`: a tarja atravessa a tela e o texto entra deslizando, borrado, e assenta nítido. */
|
||||
export type HookAnim = "pop" | "fade" | "none" | "slide";
|
||||
export type HookSettings = { style: HookStyle; bg: string; color: string; font: string; anim: HookAnim; seconds: number };
|
||||
/** `y` = centro do gancho em fração da altura (0,04–0,96); null = automático (logo abaixo da câmera). */
|
||||
export type HookSettings = { style: HookStyle; bg: string; color: string; font: string; anim: HookAnim; seconds: number; y: number | null };
|
||||
/** Tamanho do vídeo de saída e quadro lógico do ASS (no horizontal os textos são contados em 2560×1440). */
|
||||
export type FrameSize = { width: number; height: number; canvasWidth: number; canvasHeight: number };
|
||||
|
||||
/** Espelho de `layout.DEFAULTS["hook"]` do serviço, só para quando ele não manda o grupo (serviço antigo). */
|
||||
export const HOOK_FALLBACK: HookSettings = { style: "banner", bg: "#00FF00", color: "#FFFFFF", font: "Luckiest Guy", anim: "slide", seconds: 3 };
|
||||
export const HOOK_FALLBACK: HookSettings = { style: "banner", bg: "#00FF00", color: "#FFFFFF", font: "Luckiest Guy", anim: "slide", seconds: 3, y: null };
|
||||
|
||||
/** Grupo `hook` efetivo (o serviço antigo não manda: usa o espelho do padrão). */
|
||||
export function hookOf(settings: Pick<CutSettings, "hook"> | null | undefined): HookSettings {
|
||||
|
||||
@@ -534,8 +534,32 @@ function CutSettingsEditor({ scope, onDirty, onClose, onSaved }: {
|
||||
)}
|
||||
<div className="grid gap-x-8 gap-y-6 xl:grid-cols-2">
|
||||
<div className="grid content-start gap-4">
|
||||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Estilo</h4>
|
||||
<HookSample hook={hook} aspect={aspect} />
|
||||
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Posição e estilo</h4>
|
||||
<HookSample hook={hook} aspect={aspect} layout={draft.layout} caption={draft.caption} onMove={(y) => setHook({ y })} />
|
||||
{(() => {
|
||||
const place = hookPlacement(hook, aspect, draft.layout, draft.caption);
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
<ChoiceGroup<"auto" | "chosen"> name="cut-hook-place" legend="Onde o gancho aparece" value={hook.y === null ? "auto" : "chosen"}
|
||||
onChange={(v) => setHook({ y: v === "auto" ? null : place.y })}
|
||||
options={[
|
||||
{ value: "auto", label: "Automático", hint: place.camTop ? "logo abaixo da câmera" : "longe da legenda" },
|
||||
{ value: "chosen", label: "Escolhido por mim", hint: "arraste no quadro" },
|
||||
]} />
|
||||
{hook.y !== null && (
|
||||
<RangeField label="Altura do gancho na tela" min={0.04} max={0.96} step={0.002} value={hook.y}
|
||||
onChange={(y) => setHook({ y })} format={hookPct}
|
||||
hint={`Automático daria ${hookPct(place.auto)}. 0 % é o topo do vídeo.`} />
|
||||
)}
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
{hook.y === null
|
||||
? <>Agora em {hookPct(place.y)} da altura{place.camTop ? ", logo abaixo da câmera" : ""}. Arraste o gancho no quadro para escolher outro lugar.</>
|
||||
: <>Centro do gancho em {hookPct(hook.y)} da altura (o mesmo número do editor do corte).</>}
|
||||
{" "}Enquanto o gancho aparece, a legenda que ficaria embaixo dele desce para logo abaixo da tarja.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<ChoiceGroup<HookStyle> name="cut-hook-style" legend="Estilo" value={hook.style} onChange={(style) => setHook({ style })}
|
||||
options={(["banner", "plain"] as const).map((v) => ({ value: v, label: HOOK_STYLE_LABEL[v].label, hint: HOOK_STYLE_LABEL[v].hint }))} />
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
@@ -1027,17 +1051,55 @@ function RectCanvas({ imageUrl, loading, cam, game, target, onTarget, onChange }
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Amostra do gancho ---------- */
|
||||
/* ---------- Amostra e posição do gancho ---------- */
|
||||
|
||||
// Espelho de `layout.hook_y` do Clipador (app/layout.py): com a câmera em cima, logo abaixo dela; senão 20 % da altura,
|
||||
// trocando de lado se cair na legenda automática. Escolhido (`hook.y`) vale como está.
|
||||
const HOOK_BELOW_CAM = 0.044;
|
||||
const clampHookY = (y: number) => Math.min(0.96, Math.max(0.04, y));
|
||||
const hookPct = (y: number) => `${(Math.round(y * 1000) / 10).toLocaleString("pt-BR")} %`;
|
||||
|
||||
function hookPlacement(hook: HookSettings, aspect: Aspect, layout: CutSettings["layout"], caption: CutSettings["caption"]) {
|
||||
const vertical = aspect === "vertical";
|
||||
const hasCam = Boolean(layout.cam);
|
||||
const camTop = vertical && hasCam && (layout.mode === "cam_top" || layout.mode === "auto");
|
||||
const camH = camTop ? layout.camHeight : 0;
|
||||
// Legenda automática: na emenda câmera/jogo (câmera em cima), 74 % no vertical, 85 % no horizontal.
|
||||
const capAuto = caption.y ?? (camTop ? camH + 0.02 : vertical ? 0.74 : 0.85);
|
||||
let auto = 0.2;
|
||||
if (camTop) auto = Math.min(0.96, Math.round((camH + HOOK_BELOW_CAM) * 1000) / 1000);
|
||||
else if (Math.abs(capAuto - 0.2) < 0.2) auto = capAuto > 0.3 ? capAuto - 0.22 : Math.min(0.85, capAuto + 0.22);
|
||||
return { y: hook.y ?? auto, auto, camTop, camH, captionY: caption.enabled ? capAuto : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Amostra do gancho num quadro no formato do corte: tarja (faixa na largura toda) ou texto simples com caixa, na fonte
|
||||
* e nas cores escolhidas. "Ver a entrada" toca a animação (Web Animations; nada com movimento reduzido).
|
||||
*/
|
||||
function HookSample({ hook, aspect }: { hook: HookSettings; aspect: Aspect }) {
|
||||
function HookSample({ hook, aspect, layout, caption, onMove }: {
|
||||
hook: HookSettings; aspect: Aspect; layout: CutSettings["layout"]; caption: CutSettings["caption"];
|
||||
/** Nova posição (fração da altura) ao arrastar ou usar o teclado. */
|
||||
onMove: (y: number) => void;
|
||||
}) {
|
||||
const band = useRef<HTMLSpanElement>(null);
|
||||
const text = useRef<HTMLSpanElement>(null);
|
||||
const frame = useRef<HTMLDivElement>(null);
|
||||
const [run, setRun] = useState(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const banner = hook.style === "banner";
|
||||
const place = hookPlacement(hook, aspect, layout, caption);
|
||||
const fromPointer = (clientY: number) => {
|
||||
const r = frame.current?.getBoundingClientRect();
|
||||
if (!r) return;
|
||||
onMove(clampHookY(Math.round(((clientY - r.top) / r.height) * 1000) / 1000));
|
||||
};
|
||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const step = e.key === "PageUp" || e.key === "PageDown" ? 0.05 : 0.01;
|
||||
if (e.key === "ArrowUp" || e.key === "PageUp") onMove(clampHookY(place.y - step));
|
||||
else if (e.key === "ArrowDown" || e.key === "PageDown") onMove(clampHookY(place.y + step));
|
||||
else return;
|
||||
e.preventDefault();
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!run || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
const t = text.current, b = band.current;
|
||||
@@ -1053,17 +1115,38 @@ function HookSample({ hook, aspect }: { hook: HookSettings; aspect: Aspect }) {
|
||||
const words = "Assim fica o gancho";
|
||||
const size = aspect === "vertical" ? "text-base" : "text-lg";
|
||||
const textStyle = { fontFamily: fontStack(hook.font), fontWeight: 700, color: hook.color } as const;
|
||||
const at = { top: `${place.y * 100}%`, transform: "translateY(-50%)" } as const;
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<div aria-hidden="true" className={cx("relative overflow-hidden rounded-control border border-line bg-[repeating-linear-gradient(45deg,#26262d_0_12px,#1d1d23_12px_24px)]",
|
||||
aspect === "vertical" ? "mx-auto aspect-9/16 h-64" : "aspect-video w-full max-w-md")}>
|
||||
{/* Quadro do corte: câmera (laranja) e jogo (ciano) como na aba Câmera, a legenda tracejada e o gancho, que se
|
||||
arrasta para cima e para baixo (ou setas do teclado com o quadro em foco). */}
|
||||
<div ref={frame} role="slider" tabIndex={0} aria-label="Posição do gancho na tela" aria-orientation="vertical"
|
||||
aria-valuemin={4} aria-valuemax={96} aria-valuenow={Math.round(place.y * 100)}
|
||||
aria-valuetext={`${hookPct(place.y)} da altura${hook.y === null ? " (automática)" : ""}`}
|
||||
onKeyDown={onKey}
|
||||
onPointerDown={(e: PointerEvent<HTMLDivElement>) => { e.currentTarget.setPointerCapture(e.pointerId); setDragging(true); fromPointer(e.clientY); }}
|
||||
onPointerMove={(e: PointerEvent<HTMLDivElement>) => { if (dragging) fromPointer(e.clientY); }}
|
||||
onPointerUp={() => setDragging(false)} onPointerCancel={() => setDragging(false)}
|
||||
className={cx("relative touch-none overflow-hidden rounded-control border border-line bg-sunken select-none focus-visible:outline-2 focus-visible:outline-accent",
|
||||
dragging ? "cursor-grabbing" : "cursor-grab",
|
||||
aspect === "vertical" ? "mx-auto aspect-9/16 h-80" : "aspect-video w-full max-w-md")}>
|
||||
{place.camTop && (
|
||||
<span aria-hidden="true" className="absolute inset-x-0 top-0 grid place-items-center border-b border-accent/70 bg-accent/25 text-[0.6875rem] font-semibold tracking-wide text-accent uppercase"
|
||||
style={{ height: `${place.camH * 100}%` }}>Câmera</span>
|
||||
)}
|
||||
<span aria-hidden="true" className="absolute inset-x-0 bottom-0 grid place-items-end justify-center bg-option-b/15 pb-2 text-[0.6875rem] font-semibold tracking-wide text-option-b uppercase"
|
||||
style={{ top: `${place.camH * 100}%` }}>Jogo</span>
|
||||
{place.captionY !== null && (
|
||||
<span aria-hidden="true" className="absolute left-1/2 grid h-[5%] w-3/4 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-[3px] border border-dashed border-fg/60 text-[0.625rem] text-fg-muted"
|
||||
style={{ top: `${place.captionY * 100}%` }}>legenda</span>
|
||||
)}
|
||||
{banner ? (
|
||||
<span ref={band} className="absolute inset-x-0 top-[14%] grid place-items-center px-2 py-2" style={{ background: hook.bg }}>
|
||||
<span ref={band} aria-hidden="true" className="absolute inset-x-0 grid place-items-center px-2 py-1.5 shadow-[0_0_0_2px_rgba(0,0,0,.35)]" style={{ ...at, background: hook.bg }}>
|
||||
<span ref={text} className={cx("block text-center leading-tight uppercase", size)}
|
||||
style={{ ...textStyle, WebkitTextStroke: "3px #000", paintOrder: "stroke fill", textShadow: "2px 2px 0 #000" }}>{words}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="absolute inset-x-0 top-[14%] grid place-items-center px-2">
|
||||
<span aria-hidden="true" className="absolute inset-x-0 grid place-items-center px-2" style={at}>
|
||||
<span ref={text} className={cx("block bg-[#E11D48] px-2 py-1 text-center leading-tight", size)} style={textStyle}>{words}</span>
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
// Fila de cortes do Clipador: filtros por etapa (para aprovar, na fila, aprovados…) e um cartão por
|
||||
// corte com o vídeo (9:16, ou 16:9 se o corte for horizontal; sem `aspect` = vertical), título e legenda editáveis, o veredito da IA, os sinais do chat, ajuste fino
|
||||
// de início/fim e as ações da etapa. Os dados vêm de cima (ClipperStudio); cada ação recarrega tudo.
|
||||
// de início/fim e as ações da etapa. "Ordenar" (mais novos, maior nota da IA, sinal mais forte…) só reordena
|
||||
// o que a aba mostra, no navegador; a escolha fica lembrada no localStorage. Os dados vêm de cima (ClipperStudio); cada ação recarrega tudo.
|
||||
// Apagar: "Apagar" em cada cartão (confirmação curta no próprio cartão). Seleção discreta (pedido do dono: "bem
|
||||
// sutil, no cantinho"): "Selecionar" e o menu "⋯" (com "Apagar todos desta aba", modal que respeita o filtro de
|
||||
// sessão) no canto da linha das abas; a caixa de cada cartão só aparece no hover/foco ou no modo de seleção; com algo
|
||||
@@ -30,6 +31,53 @@ export const QUEUE_FILTERS: { id: QueueFilter; label: string; statuses: ClipStat
|
||||
{ id: "error", label: "Com erro", statuses: ["error"], empty: "Nenhum corte com erro." },
|
||||
];
|
||||
|
||||
export type QueueSort = "newest" | "oldest" | "bestScore" | "worstScore" | "strongestSignal" | "longest";
|
||||
|
||||
/** Nota da IA (0–10) do corte; `null` quando a IA ainda não julgou ou deu erro. */
|
||||
function judgeScore(clip: Clip): number | null {
|
||||
return clip.judge && "score" in clip.judge ? clip.judge.score : null;
|
||||
}
|
||||
|
||||
/** O id cresce com a criação: serve de "mais novo" e de desempate estável. */
|
||||
const byNewest = (a: Clip, b: Clip) => b.id - a.id;
|
||||
|
||||
/** Compara por nota; sem nota vai sempre para o fim, qualquer que seja a direção. */
|
||||
function byJudge(direction: 1 | -1) {
|
||||
return (a: Clip, b: Clip) => {
|
||||
const x = judgeScore(a);
|
||||
const y = judgeScore(b);
|
||||
if (x === null || y === null) return x === y ? byNewest(a, b) : x === null ? 1 : -1;
|
||||
return (x - y) * direction || byNewest(a, b);
|
||||
};
|
||||
}
|
||||
|
||||
export const QUEUE_SORTS: { id: QueueSort; label: string; compare: (a: Clip, b: Clip) => number }[] = [
|
||||
{ id: "newest", label: "Mais novos", compare: byNewest },
|
||||
{ id: "oldest", label: "Mais antigos", compare: (a, b) => a.id - b.id },
|
||||
{ id: "bestScore", label: "Maior nota da IA", compare: byJudge(-1) },
|
||||
{ id: "worstScore", label: "Menor nota da IA", compare: byJudge(1) },
|
||||
{ id: "strongestSignal", label: "Sinal mais forte (chat/áudio)", compare: (a, b) => b.score - a.score || byNewest(a, b) },
|
||||
{ id: "longest", label: "Mais longos", compare: (a, b) => b.durationS - a.durationS || byNewest(a, b) },
|
||||
];
|
||||
|
||||
/** A ordem escolhida fica lembrada neste navegador (conveniência; sem ela, volta para "Mais novos"). */
|
||||
const SORT_STORAGE_KEY = "cenaforge.clipper.queueSort";
|
||||
|
||||
function useQueueSort() {
|
||||
const [sort, setSort] = useState<QueueSort>("newest");
|
||||
useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem(SORT_STORAGE_KEY);
|
||||
if (QUEUE_SORTS.some((s) => s.id === saved)) setSort(saved as QueueSort);
|
||||
} catch { /* armazenamento bloqueado: fica o padrão */ }
|
||||
}, []);
|
||||
const change = useCallback((next: QueueSort) => {
|
||||
setSort(next);
|
||||
try { localStorage.setItem(SORT_STORAGE_KEY, next); } catch { /* idem */ }
|
||||
}, []);
|
||||
return [sort, change] as const;
|
||||
}
|
||||
|
||||
/** Duração mínima e máxima de um corte (limites do serviço; Shorts aceita até 180 s). */
|
||||
const MIN_CLIP_S = 5;
|
||||
const MAX_CLIP_S = 180;
|
||||
@@ -81,7 +129,9 @@ export function ClipQueue({ clips, sessions, sessionFilter, onSessionFilter, nam
|
||||
const [filter, setFilter] = useState<QueueFilter>("ready");
|
||||
const scoped = sessionFilter === null ? clips : clips.filter((c) => c.sessionId === sessionFilter);
|
||||
const current = QUEUE_FILTERS.find((f) => f.id === filter)!;
|
||||
const shown = scoped.filter((c) => current.statuses.includes(c.status));
|
||||
const [sort, setSort] = useQueueSort();
|
||||
const compare = (QUEUE_SORTS.find((s) => s.id === sort) ?? QUEUE_SORTS[0]).compare;
|
||||
const shown = scoped.filter((c) => current.statuses.includes(c.status)).sort(compare);
|
||||
const sessionIds = [...new Set(clips.map((c) => c.sessionId))];
|
||||
const publishing = useClipPublishing(filter === "approved");
|
||||
|
||||
@@ -205,6 +255,12 @@ export function ClipQueue({ clips, sessions, sessionFilter, onSessionFilter, nam
|
||||
</Select>
|
||||
</label>
|
||||
) : null}
|
||||
<label className="flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">
|
||||
Ordenar
|
||||
<Select value={sort} onChange={(e) => setSort(e.target.value as QueueSort)} className="h-9 w-auto min-w-44">
|
||||
{QUEUE_SORTS.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
{/* Sempre no lugar (mesmo vazio, desabilitado): ligar/desligar a seleção não mexe no layout. */}
|
||||
<div className="flex items-center gap-0.5">
|
||||
<Button variant="ghost" size="sm" aria-pressed={selecting} disabled={selectable.length === 0 || working}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// Consulta de novo a cada 5 s enquanto houver sessão gravando/processando ou corte na fila (e a cada
|
||||
// 10 s com o serviço fora do ar, para perceber quando ele volta); para quando a aba fica oculta.
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { ChannelAddForm, ChannelList, type ChannelAccounts } from "./clipper-channels";
|
||||
import {
|
||||
ACTIVE_CLIP, ACTIVE_SESSION, PROVIDER_LABEL, clipperCall, formatClock, formatScore, isOfflineError, sourceName, useClipperAction,
|
||||
@@ -103,6 +103,16 @@ export function ClipperStudio({ channelAccounts }: { channelAccounts: ChannelAcc
|
||||
|
||||
const reload = useCallback(() => void refresh(), [refresh]);
|
||||
|
||||
// Ao abrir a página, a fila já vem filtrada pela primeira sessão aberta (gravando agora), não por "Todas as
|
||||
// sessões" (pedido do dono, 17/11/2026). Só na primeira carga: depois vale o que você escolher no filtro.
|
||||
const autoPicked = useRef(false);
|
||||
useEffect(() => {
|
||||
if (autoPicked.current || !data) return;
|
||||
autoPicked.current = true;
|
||||
const open = data.sessions.find((s) => s.status === "recording" || s.status === "starting");
|
||||
if (open) setSessionFilter((current) => current ?? open.id);
|
||||
}, [data]);
|
||||
|
||||
if (!loadedOnce) {
|
||||
return <div role="status" className="flex items-center gap-3 text-sm text-fg-muted"><Spinner />Consultando o Clipador…</div>;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ type CollectResult = { groups: { accountId: string; platform: Platform; read: nu
|
||||
/** "Há 5 min", "há 2 h", "há 3 dias". */
|
||||
function ago(iso: string): string {
|
||||
const min = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60_000));
|
||||
if (min < 1) return "agora há pouco";
|
||||
if (min < 1) return "agora";
|
||||
if (min < 60) return `há ${min} min`;
|
||||
const h = Math.round(min / 60);
|
||||
return h < 48 ? `há ${h} h` : `há ${Math.round(h / 24)} dias`;
|
||||
@@ -118,7 +118,9 @@ export function MetricsSyncControls({ syncs, accountId, everyHours, showAccount
|
||||
if (g.error) return `${label}: não deu (${g.error})`;
|
||||
return `${label}: ${g.read} vídeo${g.read === 1 ? "" : "s"}${g.missing ? ` (${g.missing} não ${g.missing === 1 ? "achado" : "achados"})` : ""}`;
|
||||
});
|
||||
setMessage({ ok: r.data.groups.every((g) => !g.error), text: `Números lidos. ${parts.join(" · ")}.` });
|
||||
const failed = r.data.groups.filter((g) => g.error).length;
|
||||
const head = failed === 0 ? "Números lidos." : failed === r.data.groups.length ? "Não deu para ler os números." : "Parte dos números foi lida.";
|
||||
setMessage({ ok: failed === 0, text: `${head} ${parts.join(" · ")}.` });
|
||||
}
|
||||
startTransition(() => router.refresh());
|
||||
}
|
||||
@@ -147,7 +149,7 @@ export function MetricsSyncControls({ syncs, accountId, everyHours, showAccount
|
||||
<Icon size={13} className="shrink-0 text-fg-subtle" />
|
||||
<span className="font-medium text-fg">{PLATFORM_META[s.platform].label}{showAccount && <span className="font-normal text-fg-subtle"> · {s.accountName}</span>}</span>
|
||||
{s.lastError
|
||||
? <span className="truncate text-danger" title={s.lastError}>falhou {s.lastRunAt ? ago(s.lastRunAt) : ""}: {s.lastError}</span>
|
||||
? <span className="truncate text-danger" title={s.lastError}>falhou {s.lastRunAt ? ago(s.lastRunAt) : ""} — {s.lastError}</span>
|
||||
: <span className="text-fg-muted">{s.lastOkAt ? `lido ${ago(s.lastOkAt)}` : "ainda não lido"}</span>}
|
||||
</li>
|
||||
);
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "./icons";
|
||||
import { PLATFORM_META } from "./platforms";
|
||||
import {
|
||||
formatTime, getPublisherStatus, getSettings, getSummary, listJobs, markJobPublished, markJobRemoved, patchJob, publishClip, putSettings, readNetwork, runJobAction,
|
||||
formatTime, getPublisherStatus, getSettings, getSummary, listJobs, markJobPublished, markJobRemoved, patchJob, publishClip, putSettings, readNetwork, runJobAction, toLocalInput,
|
||||
type JobAction, type PublisherStatus, type PublishJob, type PublishJobAction, type PublishJobStatus, type PublishingNetwork, type PublishingSummary,
|
||||
} from "./publishing-client";
|
||||
import { JobStatusBadge, NoticeBar, PlatformName, TextLink } from "./publishing-ui";
|
||||
@@ -87,7 +87,7 @@ export function PublishingBoard() {
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [resumeBusy, setResumeBusy] = useState(false);
|
||||
const [notice, setNotice] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [reschedule, setReschedule] = useState<PublishJob | null>(null);
|
||||
const [reschedule, setReschedule] = useState<PublishJob[] | null>(null);
|
||||
const [reconnect, setReconnect] = useState<{ job: PublishJob; network: PublishingNetwork; accountName: string } | null>(null);
|
||||
const [markJob, setMarkJob] = useState<PublishJob | null>(null);
|
||||
const [accounts, setAccounts] = useState<AccountView[] | null>(null);
|
||||
@@ -284,7 +284,7 @@ export function PublishingBoard() {
|
||||
</p>
|
||||
|
||||
{reschedule && (
|
||||
<RescheduleDialog job={reschedule} timezone={timezone} onClose={() => setReschedule(null)}
|
||||
<RescheduleDialog jobs={reschedule} timezone={timezone} onClose={() => setReschedule(null)}
|
||||
onSaved={(text) => { setReschedule(null); setNotice({ ok: true, text }); void load(); }} />
|
||||
)}
|
||||
{markJob && (
|
||||
@@ -304,7 +304,8 @@ export function PublishingBoard() {
|
||||
|
||||
type Handlers = {
|
||||
onAction: (job: PublishJob, action: JobAction) => Promise<boolean>;
|
||||
onReschedule: (job: PublishJob) => void;
|
||||
/** Uma rede ou várias do mesmo vídeo ("Mudar horário de todas"). */
|
||||
onReschedule: (jobs: PublishJob[]) => void;
|
||||
onReconnect: (job: PublishJob) => void;
|
||||
onMarkPublished: (job: PublishJob) => void;
|
||||
onMarkRemoved: (job: PublishJob) => void;
|
||||
@@ -337,6 +338,8 @@ function JobGroup({ tab, group, onAction, onReschedule, onReconnect, onMarkPubli
|
||||
const [approving, setApproving] = useState(false);
|
||||
const [sending, setSending] = useState<Platform | null>(null);
|
||||
const missing = missingFor(head);
|
||||
// Redes deste vídeo cujo horário dá para mudar (agendadas): um botão muda todas de uma vez.
|
||||
const reschedulable = jobs.filter((j) => j.actions.includes("reschedule"));
|
||||
// Aprovar um job aprova o vídeo inteiro (todas as redes aguardando): um botão por vídeo, não por rede.
|
||||
const approvable = jobs.find((j) => j.status === "awaiting_approval" && j.actions.includes("approve"));
|
||||
const awaitingCount = jobs.filter((j) => j.status === "awaiting_approval").length;
|
||||
@@ -364,6 +367,11 @@ function JobGroup({ tab, group, onAction, onReschedule, onReconnect, onMarkPubli
|
||||
<span>Canal <TextLink href={`/accounts?account=${encodeURIComponent(head.accountId)}`}>{head.accountName || head.accountId}</TextLink></span>
|
||||
</p>
|
||||
</div>
|
||||
{reschedulable.length > 1 && (
|
||||
<Button variant="secondary" onClick={() => onReschedule(reschedulable)}>
|
||||
<ClockIcon size={16} />Mudar horário de todas ({reschedulable.length})
|
||||
</Button>
|
||||
)}
|
||||
{tab === "aprovar" && approvable && (
|
||||
<Button onClick={() => void approve()} disabled={approving}>
|
||||
{approving ? <Spinner /> : <CheckIcon size={16} />}
|
||||
@@ -435,13 +443,13 @@ function JobRow({ job, onAction, onReschedule, onReconnect, onMarkPublished, onM
|
||||
switch (job.status) {
|
||||
case "awaiting_approval":
|
||||
return <>
|
||||
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule(job)}><ClockIcon size={15} />Mudar horário</Button>}
|
||||
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule([job])}><ClockIcon size={15} />Mudar horário</Button>}
|
||||
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Tirar esta rede</Button>}
|
||||
</>;
|
||||
case "scheduled":
|
||||
return <>
|
||||
{can("publish-now") && <Button size="sm" disabled={disabled} onClick={() => void run("publish-now")}>{icon("publish-now", <PublishIcon size={15} />)}Publicar agora</Button>}
|
||||
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule(job)}><ClockIcon size={15} />Mudar horário</Button>}
|
||||
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule([job])}><ClockIcon size={15} />Mudar horário</Button>}
|
||||
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Cancelar</Button>}
|
||||
</>;
|
||||
case "queued":
|
||||
@@ -560,20 +568,16 @@ function MarkPublishedDialog({ job, onClose, onSaved }: { job: PublishJob; onClo
|
||||
|
||||
/* ---------- Mudar horário ---------- */
|
||||
|
||||
/** Valor de <input type="datetime-local"> no horário local do navegador. */
|
||||
function toLocalInput(iso: string | null): string {
|
||||
const d = iso ? new Date(iso) : new Date(Date.now() + 3_600_000);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function RescheduleDialog({ job, timezone, onClose, onSaved }: {
|
||||
job: PublishJob; timezone: string; onClose: () => void; onSaved: (text: string) => void;
|
||||
function RescheduleDialog({ jobs, timezone, onClose, onSaved }: {
|
||||
jobs: PublishJob[]; timezone: string; onClose: () => void; onSaved: (text: string) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState(() => toLocalInput(job.scheduledAt));
|
||||
// Começa no horário mais cedo entre as redes escolhidas.
|
||||
const first = jobs.map((j) => j.scheduledAt).filter((t): t is string => !!t).sort()[0] ?? null;
|
||||
const [value, setValue] = useState(() => toLocalInput(first));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const label = PLATFORM_META[job.platform].label;
|
||||
const names = jobs.map((j) => PLATFORM_META[j.platform].label);
|
||||
const label = names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} e ${names.at(-1)}`;
|
||||
|
||||
async function save() {
|
||||
const date = new Date(value);
|
||||
@@ -581,15 +585,21 @@ function RescheduleDialog({ job, timezone, onClose, onSaved }: {
|
||||
if (date.getTime() < Date.now() - 60_000) { setError("Escolha um horário daqui para a frente."); return; }
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const r = await patchJob(job.id, { scheduledAt: date.toISOString() });
|
||||
// Uma rede por vez: se uma recusar (limite por dia, intervalo mínimo), as outras continuam e o erro aparece.
|
||||
const failed: string[] = [];
|
||||
for (const job of jobs) {
|
||||
const r = await patchJob(job.id, { scheduledAt: date.toISOString() });
|
||||
if (!r.ok) failed.push(`${PLATFORM_META[job.platform].label}: ${r.error}`);
|
||||
}
|
||||
setBusy(false);
|
||||
if (!r.ok) { setError(r.error); return; }
|
||||
onSaved(`${label}: sai ${formatTime(date.toISOString())}.`);
|
||||
if (failed.length === jobs.length) { setError(failed.join(" · ")); return; }
|
||||
onSaved(`${label}: ${jobs.length > 1 ? "saem" : "sai"} ${formatTime(date.toISOString())}.${failed.length ? ` Não mudou — ${failed.join(" · ")}.` : ""}`);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onClose={onClose} size="sm" title={`Mudar horário no ${label}`}
|
||||
description="O vídeo sai nesse horário, se o limite por dia da rede deixar."
|
||||
<Dialog open onClose={onClose} size="sm" title={jobs.length === 1 ? `Mudar horário no ${label}` : "Mudar horário de todas as redes"}
|
||||
description={jobs.length === 1 ? "O vídeo sai nesse horário, se o limite por dia da rede deixar."
|
||||
: `O vídeo sai no ${label} nesse mesmo horário, se o limite por dia de cada rede deixar.`}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>Voltar</Button>
|
||||
<Button onClick={() => void save()} disabled={busy}>{busy ? <Spinner /> : <CheckIcon size={16} />}Salvar horário</Button>
|
||||
|
||||
@@ -144,7 +144,11 @@ export function deleteApp(platform: Platform) {
|
||||
}
|
||||
/** "Publicar" um corte aprovado num canal, nas redes escolhidas (não precisa ligar a fonte ao canal). */
|
||||
export type ClipPublishResult = { jobs: PublishJob[]; skipped: { platform: Platform; reason: string }[]; placed: number };
|
||||
export function publishClip(clipId: number, body: { accountId: string; platforms: Platform[]; timing: PublishTiming }) {
|
||||
/** "Quando sai" no diálogo do corte: os do canal mais "at" (horário escolhido, um por rede em `scheduledAt`). */
|
||||
export type ClipTiming = PublishTiming | "at";
|
||||
export function publishClip(clipId: number, body: {
|
||||
accountId: string; platforms: Platform[]; timing: ClipTiming; scheduledAt?: Partial<Record<Platform, string>>;
|
||||
}) {
|
||||
return apiCall<ClipPublishResult>(`/api/publishing/clips/${clipId}`, "POST", body);
|
||||
}
|
||||
export function approveEpisode(episodeId: number, body: { renderId: number; title: string; caption: string }) {
|
||||
@@ -165,6 +169,13 @@ export function networkName(n: { handle: string | null; display_name?: string |
|
||||
export const MODE_LABEL: Record<ConnectionMode, string> = { official: "Conta oficial (API)", session: "Sessão logada" };
|
||||
export const PRIVACY_LABEL: Record<Privacy, string> = { public: "Público", unlisted: "Não listado", private: "Privado" };
|
||||
|
||||
/** Valor de <input type="datetime-local"> no horário local do navegador (sem horário = daqui a 1 h). */
|
||||
export function toLocalInput(iso: string | null): string {
|
||||
const d = iso ? new Date(iso) : new Date(Date.now() + 3_600_000);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** Horário curto e humano: "hoje, 19:00", "amanhã, 08:00" ou "qua., 19/11, 12:00". */
|
||||
export function formatTime(iso: string | null): string {
|
||||
if (!iso) return "—";
|
||||
|
||||
@@ -20,7 +20,7 @@ export function PlatformName({ platform, size = 16, className }: { platform: Pla
|
||||
);
|
||||
}
|
||||
|
||||
const NETWORK_STATUS: Record<NetworkStatus, { tone: Tone; icon: ReactNode; label: string }> = {
|
||||
export const NETWORK_STATUS: Record<NetworkStatus, { tone: Tone; icon: ReactNode; label: string }> = {
|
||||
disconnected: { tone: "neutral", icon: <UnlinkIcon size={13} />, label: "Não conectado" },
|
||||
connecting: { tone: "info", icon: <Spinner className="size-3" />, label: "Conectando…" },
|
||||
connected: { tone: "success", icon: <CheckIcon size={13} />, label: "Conectado" },
|
||||
|
||||
@@ -161,7 +161,7 @@ export function ChoiceGroup<T extends string>({ name, legend, options, defaultVa
|
||||
: { defaultChecked: defaultValue === o.value })} />
|
||||
<span className="grid">
|
||||
<span>{o.label}</span>
|
||||
{o.hint && <span className="text-[0.6875rem] font-normal text-fg-subtle">{o.hint}</span>}
|
||||
{o.hint && <span className="text-xs font-normal text-fg-subtle">{o.hint}</span>}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
|
||||
@@ -110,10 +110,14 @@ async function collect({ accountId, force = false }: { accountId?: string; force
|
||||
saveSync(account, platform, startedAt, null, stats.items.length, stats.missing.length);
|
||||
result.groups.push({ accountId: account, platform, read: stats.items.length, missing: stats.missing.length, error: null });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
// 404 = o Publicador rodando é anterior à rota /stats (o pnpm dev não foi reiniciado depois da atualização).
|
||||
const message = error instanceof ServiceError && error.status === 404
|
||||
? "o Publicador está com a versão antiga, sem a leitura de números. Reinicie o pnpm dev."
|
||||
: error instanceof Error ? error.message : String(error);
|
||||
saveSync(account, platform, startedAt, message, 0, byRemote.size);
|
||||
result.groups.push({ accountId: account, platform, read: 0, missing: byRemote.size, error: message });
|
||||
if (error instanceof ServiceError && error.status === 503) break; // Publicador fora: as outras redes também falhariam
|
||||
// Publicador fora ou desatualizado: as outras redes falhariam do mesmo jeito.
|
||||
if (error instanceof ServiceError && (error.status === 503 || error.status === 404)) break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
// `simulateMetrics()` ainda gera dados de EXEMPLO (simulated = 1) para ver o dashboard sem nada publicado; tudo
|
||||
// que é simulado é marcado e sai de uma vez com `clearSimulated()`.
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { all, get, run } from "./db";
|
||||
import { REPO_ROOT } from "./paths";
|
||||
import { listMetricSyncs, type MetricSync } from "./metrics-sync";
|
||||
import type { MetricTotals, Platform } from "./types";
|
||||
|
||||
@@ -83,12 +86,13 @@ function videos(where: string, params: string[], base: string): VideoMetrics[] {
|
||||
return [...map.entries()].map(([key, list]) => {
|
||||
const first = list[0];
|
||||
const sum = (k: "views" | "likes" | "comments" | "shares" | "saves") => list.reduce((n, r) => n + (r[k] ?? 0), 0);
|
||||
const n = first.file_key ? /^ep(d+)/i.exec(first.file_key)?.[1] : undefined;
|
||||
const n = first.file_key ? /^ep(\d+)/i.exec(first.file_key)?.[1] : undefined;
|
||||
const captured = list.map((r) => r.captured_at).filter((c): c is string => !!c).sort();
|
||||
return {
|
||||
key, kind: first.clip_id !== null ? "clip" as const : "episode" as const,
|
||||
title: list.find((r) => r.title)?.title || (first.clip_id !== null ? `Corte ${first.clip_id}` : "Episódio"),
|
||||
cover: list.find((r) => r.cover)?.cover ?? null,
|
||||
// Só capa que ainda existe no disco (a de um corte cuja sessão foi apagada some): sem ela, o marcador vazio.
|
||||
cover: list.map((r) => r.cover).find((c): c is string => !!c && fs.existsSync(path.resolve(REPO_ROOT, c))) ?? null,
|
||||
href: first.story_id ? (n ? `/stories/${first.story_id}/episodes/${Number(n)}` : `/stories/${first.story_id}`) : null,
|
||||
publishedAt: first.published_at, capturedAt: captured.at(-1) ?? null,
|
||||
totals: totals({ views: sum("views"), likes: sum("likes"), comments: sum("comments"), shares: sum("shares"), saves: sum("saves"),
|
||||
|
||||
@@ -413,6 +413,24 @@ describe("\"Publicar\" no cartão do corte (origem manual)", () => {
|
||||
assert.deepEqual([after.status, after.attempts], ["queued", attempts + 1]);
|
||||
});
|
||||
|
||||
it("horário específico: agenda no horário escolhido para a rede (manual), mesmo se já estava na fila", async () => {
|
||||
const at = new Date(Date.now() + 3 * 86_400_000);
|
||||
at.setUTCMinutes(17, 0, 0);
|
||||
// O job do corte 500 está na fila (teste anterior): o horário escolhido o reagenda.
|
||||
const r = await pub.publishClip(500, { accountId: "canal", platforms: ["youtube"], timing: "at", scheduledAt: { youtube: at.toISOString() } });
|
||||
assert.equal(r.placed, 1);
|
||||
const row = dbm.get<import("./publishing").JobRow>("SELECT * FROM publish_jobs WHERE source_kind = 'clip' AND source_id = '500'")!;
|
||||
assert.deepEqual([row.status, row.schedule_source, row.scheduled_at], ["scheduled", "manual", at.toISOString()]);
|
||||
});
|
||||
|
||||
it("horário específico: recusa rede sem horário, horário passado e além de um ano", async () => {
|
||||
const base = { accountId: "canal", platforms: ["youtube"], timing: "at" };
|
||||
await assert.rejects(pub.publishClip(500, { ...base, scheduledAt: {} }), /dia e a hora do YouTube/);
|
||||
await assert.rejects(pub.publishClip(500, { ...base, scheduledAt: { youtube: "2020-01-01T10:00:00Z" } }), /já passou/);
|
||||
await assert.rejects(pub.publishClip(500, { ...base, scheduledAt: { youtube: new Date(Date.now() + 400 * 86_400_000).toISOString() } }), /um ano/);
|
||||
await assert.rejects(pub.publishClip(500, { ...base, timing: "ontem" }), /now, best_slot ou at/);
|
||||
});
|
||||
|
||||
it("recusa corte que não está aprovado, canal inexistente e lista vazia de redes", async () => {
|
||||
await assert.rejects(pub.publishClip(501, { accountId: "canal", platforms: ["youtube"] }), /aprovado/);
|
||||
await assert.rejects(pub.publishClip(500, { accountId: "nao-existe", platforms: ["youtube"] }), /canal de publicação/);
|
||||
|
||||
+78
-10
@@ -409,6 +409,24 @@ function cleanCaption(raw: unknown): string {
|
||||
}
|
||||
|
||||
// ---------- "Publicar" no cartão do corte ----------
|
||||
/** "Quando sai" do diálogo do corte: os do canal mais "at" (horário escolhido por você, por rede). */
|
||||
export type ClipTiming = PublishTiming | "at";
|
||||
|
||||
/** Mesmos limites da troca de horário de um job (updateJob): futuro (1 min de folga) e até um ano. */
|
||||
function readChosenTimes(raw: unknown, platforms: Platform[]): Map<Platform, Date> {
|
||||
const map = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
|
||||
const times = new Map<Platform, Date>();
|
||||
for (const platform of platforms) {
|
||||
const at = new Date(String(map[platform] ?? ""));
|
||||
const name = platform === "youtube" ? "YouTube" : platform === "tiktok" ? "TikTok" : "Instagram";
|
||||
if (map[platform] === undefined || Number.isNaN(at.getTime())) throw new UserError(`Escolha o dia e a hora do ${name}.`);
|
||||
if (at.getTime() < Date.now() - 60_000) throw new UserError(`O horário do ${name} já passou. Escolha um horário no futuro.`);
|
||||
if (at.getTime() > Date.now() + 365 * 86_400_000) throw new UserError(`O horário do ${name} passa de um ano. Escolha uma data mais perto.`);
|
||||
times.set(platform, at);
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
export type ClipPublishResult = {
|
||||
/** Jobs deste corte depois da ação (todos os canais e redes). */
|
||||
jobs: PublishJob[];
|
||||
@@ -422,17 +440,22 @@ export type ClipPublishResult = {
|
||||
* Publica um corte APROVADO num canal de publicação, nas redes escolhidas — sem precisar ligar a fonte inteira ao
|
||||
* canal. O clique é a aprovação humana. Os jobs ficam com `origin = 'manual'` (o despachante não os cancela por
|
||||
* "fonte desligada"). `timing`: "now" sai no próximo ciclo (ignora horário bom e limite do dia, decisão sua);
|
||||
* "best_slot" entra no próximo horário bom livre; ausente = o que o canal usa.
|
||||
* "best_slot" entra no próximo horário bom livre; "at" sai no horário que você escolheu para cada rede
|
||||
* (`scheduledAt`: { rede: ISO }, pode ser um igual para todas ou um diferente por rede; como "now", é decisão sua
|
||||
* e não passa pelo horário bom nem pelo limite do dia); ausente = o que o canal usa.
|
||||
* Rede que já tem esse corte publicado, em envio ou que pode já ter saído fica de fora (com o motivo).
|
||||
*/
|
||||
export async function publishClip(clipId: number, input: { accountId?: unknown; platforms?: unknown; timing?: unknown }): Promise<ClipPublishResult> {
|
||||
export async function publishClip(clipId: number, input: { accountId?: unknown; platforms?: unknown; timing?: unknown; scheduledAt?: unknown }): Promise<ClipPublishResult> {
|
||||
if (!Number.isInteger(clipId) || clipId <= 0) throw new UserError("Corte inválido.");
|
||||
const account = get<Account>("SELECT * FROM accounts WHERE id = ?", String(input.accountId ?? ""));
|
||||
if (!account) throw new UserError("Escolha um canal de publicação.");
|
||||
const platforms = Array.isArray(input.platforms) ? [...new Set(input.platforms.map((p) => mustPlatform(String(p))))] : [];
|
||||
if (platforms.length === 0) throw new UserError("Escolha pelo menos uma rede.");
|
||||
if (input.timing !== undefined && input.timing !== "now" && input.timing !== "best_slot") throw new UserError("Quando sai: use now ou best_slot.");
|
||||
const timing: PublishTiming = (input.timing as PublishTiming | undefined) ?? account.timing;
|
||||
if (input.timing !== undefined && input.timing !== "now" && input.timing !== "best_slot" && input.timing !== "at") {
|
||||
throw new UserError("Quando sai: use now, best_slot ou at.");
|
||||
}
|
||||
const timing: ClipTiming = (input.timing as ClipTiming | undefined) ?? account.timing;
|
||||
const chosenAt = timing === "at" ? readChosenTimes(input.scheduledAt, platforms) : null;
|
||||
|
||||
const clip = await fetchClip(clipId);
|
||||
if (!clip) throw new UserError("O corte não existe mais no Clipador.");
|
||||
@@ -445,6 +468,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
|
||||
const skipped: ClipPublishResult["skipped"] = [];
|
||||
const toPlace: number[] = [];
|
||||
const toNow: number[] = [];
|
||||
const toReschedule: { id: number; at: Date }[] = [];
|
||||
const ts = now();
|
||||
for (const platform of platforms) {
|
||||
const network = getNetwork(account.id, platform);
|
||||
@@ -465,6 +489,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
|
||||
skipped.push({ platform, reason: "já está sendo enviado" });
|
||||
} else if (existing.status === "scheduled" || existing.status === "queued") {
|
||||
if (timing === "now") toNow.push(existing.id);
|
||||
else if (chosenAt) toReschedule.push({ id: existing.id, at: chosenAt.get(platform)! });
|
||||
else skipped.push({ platform, reason: existing.status === "queued" ? "já está na fila" : "já está agendado" });
|
||||
} else {
|
||||
// Aguardando aprovação, cancelado, falhou (sem envio no Publicador) ou pediu login: volta com o vídeo atual.
|
||||
@@ -475,16 +500,24 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
|
||||
}
|
||||
|
||||
for (const id of toPlace) {
|
||||
placeApproved(id, { from: ["awaiting_approval", "canceled", "failed", "needs_login"], timing });
|
||||
const platform = get<{ platform: Platform }>("SELECT platform FROM publish_jobs WHERE id = ?", id)!.platform;
|
||||
// Horário escolhido: no mínimo daqui a 5 s, senão placeApproved o trataria como passado e cairia no horário bom.
|
||||
const preferredAt = chosenAt ? new Date(Math.max(chosenAt.get(platform)!.getTime(), Date.now() + 5_000)) : null;
|
||||
placeApproved(id, { from: ["awaiting_approval", "canceled", "failed", "needs_login"], timing: timing === "now" ? "now" : "best_slot", preferredAt });
|
||||
if (timing === "now") toNow.push(id);
|
||||
}
|
||||
for (const { id, at } of toReschedule) {
|
||||
run(`UPDATE publish_jobs SET status = 'scheduled', scheduled_at = ?, schedule_source = 'manual', step = 'Agendado por você.',
|
||||
error = NULL, updated_at = ? WHERE id = ? AND status IN ('scheduled', 'queued') AND publisher_job_id IS NULL`,
|
||||
new Date(Math.max(at.getTime(), Date.now() + 5_000)).toISOString(), now(), id);
|
||||
}
|
||||
for (const id of new Set(toNow)) {
|
||||
// "Agora" escolhido por você: sai no próximo ciclo, mesmo se o limite do dia já foi atingido.
|
||||
run(`UPDATE publish_jobs SET status = 'queued', scheduled_at = ?, schedule_source = 'now', step = 'Na fila para enviar agora.',
|
||||
error = NULL, updated_at = ? WHERE id = ? AND status IN ('scheduled', 'queued', 'failed') AND publisher_job_id IS NULL`, now(), now(), id);
|
||||
}
|
||||
// Sem horário livre, placeApproved marca "falhou" (com o motivo): só conta o que ficou na fila ou agendado.
|
||||
const placed = [...new Set([...toPlace, ...toNow])]
|
||||
const placed = [...new Set([...toPlace, ...toNow, ...toReschedule.map((r) => r.id)])]
|
||||
.filter((id) => ["scheduled", "queued"].includes(get<{ status: string }>("SELECT status FROM publish_jobs WHERE id = ?", id)?.status ?? "")).length;
|
||||
kickDispatcher();
|
||||
return { jobs: listJobs({ sourceKind: "clip", sourceId: String(clipId) }), skipped, placed };
|
||||
@@ -682,16 +715,51 @@ async function listClips(query: string): Promise<FullClip[]> {
|
||||
/** Capa do corte: a do editor; senão `clip-<id>-cover.jpg` ao lado do vídeo; senão a miniatura. */
|
||||
function clipCover(clip: FullClip): string | null {
|
||||
const exists = (rel: string | null | undefined) => !!rel && fs.existsSync(path.resolve(REPO_ROOT, rel));
|
||||
if (exists(clip.edit?.cover)) return clip.edit!.cover;
|
||||
if (clip.file) {
|
||||
let found: string | null = null;
|
||||
if (exists(clip.edit?.cover)) found = clip.edit!.cover;
|
||||
else if (clip.file) {
|
||||
const cover = path.posix.join(path.posix.dirname(clip.file.replace(/\\/g, "/")), `clip-${clip.id}-cover.jpg`);
|
||||
if (exists(cover)) return cover;
|
||||
if (exists(cover)) found = cover;
|
||||
}
|
||||
if (!found && exists(clip.thumb) && /\.(jpe?g|png)$/i.test(clip.thumb!)) found = clip.thumb;
|
||||
return found ? keepCover(clip.id, found) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pasta de capas do painel: o Clipador apaga `output/clipper/<sessão>/` inteira quando você apaga a sessão, e a
|
||||
* capa de um vídeo já publicado sumiria do dashboard. Aqui fica uma cópia que só o painel mexe.
|
||||
*/
|
||||
const KEPT_COVERS = "output/publishing/covers";
|
||||
|
||||
/** Copia a capa do corte para a pasta do painel e devolve o caminho da cópia (ou o original, se a cópia falhar). */
|
||||
function keepCover(clipId: number, rel: string): string {
|
||||
const normalized = rel.replace(/\\/g, "/");
|
||||
if (normalized.startsWith(`${KEPT_COVERS}/`)) return normalized;
|
||||
const kept = `${KEPT_COVERS}/clip-${clipId}${path.extname(normalized).toLowerCase() || ".jpg"}`;
|
||||
try {
|
||||
fs.mkdirSync(path.resolve(REPO_ROOT, KEPT_COVERS), { recursive: true });
|
||||
fs.copyFileSync(path.resolve(REPO_ROOT, normalized), path.resolve(REPO_ROOT, kept));
|
||||
return kept;
|
||||
} catch {
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
|
||||
/** Jobs de corte cuja capa ainda está na pasta do Clipador: passa para a cópia do painel enquanto o arquivo existe. */
|
||||
function keepClipCovers(): void {
|
||||
const rows = all<{ id: number; source_id: string; cover: string }>(
|
||||
`SELECT id, source_id, cover FROM publish_jobs WHERE source_kind = 'clip' AND cover IS NOT NULL AND cover NOT LIKE ?`,
|
||||
`${KEPT_COVERS}/%`);
|
||||
for (const r of rows) {
|
||||
if (!fs.existsSync(path.resolve(REPO_ROOT, r.cover))) continue;
|
||||
const kept = keepCover(Number(r.source_id), r.cover);
|
||||
if (kept !== r.cover) run("UPDATE publish_jobs SET cover = ? WHERE id = ?", kept, r.id);
|
||||
}
|
||||
return exists(clip.thumb) && /\.(jpe?g|png)$/i.test(clip.thumb!) ? clip.thumb : null;
|
||||
}
|
||||
|
||||
/** Sincroniza a fila com o Clipador. false = Clipador fora (ou não instalado) — nada muda neste ciclo. */
|
||||
async function syncClips(): Promise<boolean> {
|
||||
keepClipCovers();
|
||||
const targets: ClipTarget[] = all<Pick<Account, "id" | "approval_mode" | "auto_since">>(
|
||||
`SELECT a.id, a.approval_mode, a.auto_since FROM accounts a
|
||||
WHERE EXISTS (SELECT 1 FROM account_channels l WHERE l.account_id = a.id AND l.status = 'active')`)
|
||||
|
||||
Reference in New Issue
Block a user