Merge branch 'clipper/final' into clipper/integ

This commit is contained in:
Mateuus
2026-11-18 03:45:49 -03:00
16 changed files with 819 additions and 23 deletions
+10
View File
@@ -213,6 +213,16 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
<p className="text-xs text-fg-subtle">Vai com o título e a legenda do cartão. Para mudar, edite no cartão e salve antes.</p>
</div>
{clip.publishFile === null && (
// Só o vídeo final (sem as camadas de teste) vai para as redes: os envios esperam por ele (doc/clipador/REVISAO.md).
<p role="note" className="flex gap-2 rounded-control border border-info/30 bg-info-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-info">
<InfoIcon size={15} className="mt-0.5 shrink-0" />
<span>{clip.final?.status === "error"
? <>O vídeo final deu erro no Clipador. Pode agendar: nada sai até ele ficar pronto — use “Tentar de novo” no corte.</>
: <>O vídeo final (sem as camadas de teste) ainda está sendo gerado. Pode agendar: o envio espera por ele e nunca usa o vídeo de revisão.</>}</span>
</p>
)}
{loadError ? (
<Feedback ok={false}>Não deu para ler os canais de publicação ({loadError}).</Feedback>
) : !accounts ? (
+26
View File
@@ -197,8 +197,34 @@ export type Clip = {
aspect?: Aspect;
/** Idioma da sessão de origem (resolvido pelo serviço). Opcional: o serviço antigo não manda (= padrão, pt-BR). */
language?: string;
/** Vídeo de revisão (`file`): camadas de teste que entraram nele ([] = nenhuma; null = não se sabe). doc/clipador/REVISAO.md */
review?: { devLayers: string[] | null };
/** Vídeo final, gerado ao aprovar (sem as camadas de teste); null = ainda não aprovado. */
final?: ClipFinal | null;
/** O único arquivo que vai para as redes: o final pronto. null = ainda não (a publicação espera). */
publishFile?: string | null;
};
export type ClipFinal = {
status: "pending" | "rendering" | "ready" | "error";
file: string | null;
thumb: string | null;
cover: string | null;
error: string | null;
at: string | null;
/** O vídeo de revisão não tinha camada de teste: ele mesmo virou o final (sem render novo). */
reused: boolean;
};
/** Nome das camadas de teste do vídeo de revisão (grupo `dev` da configuração do corte). */
export const DEV_LAYER_LABEL: Record<string, string> = { translation: "tradução em português", dub: "dublagem em português" };
/** O vídeo de revisão (o da fila) tem camadas de teste? null = não se sabe (corte antigo). */
export function reviewHasDevLayers(clip: Pick<Clip, "review">): boolean | null {
const layers = clip.review?.devLayers;
return layers == null ? null : layers.length > 0;
}
/* ---------- Configuração do corte ---------- */
/** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */
+5 -2
View File
@@ -6,7 +6,7 @@
import { useEffect, useState } from "react";
import { CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, languageLabel, useClipperAction, type Clip, type ClipperSession } from "./clipper-client";
import {
ChatSignals, ClipActions, ClipMedia, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
ChatSignals, ClipActions, ClipMedia, ClipVideoState, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
} from "./clipper-clip-parts";
import { Dialog } from "./dialog";
import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, ClockIcon } from "./icons";
@@ -91,11 +91,14 @@ function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: ()
}
const showPublication = clip.status === "approved" || clip.status === "published";
// Player: o vídeo final quando existe (é o que vai para as redes); dá para voltar ao de revisão.
const [show, setShow] = useState<"review" | "final">("final");
return (
<div className="grid gap-6 md:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
<div className="grid content-start gap-4">
<ClipMedia clip={clip} version={videoVersion} />
<ClipMedia clip={clip} version={videoVersion} show={show} />
<ClipVideoState clip={clip} show={show} onShow={setShow} pending={pending} run={run} />
<ChatSignals clip={clip} />
<FaceSignal clip={clip} />
</div>
+105 -6
View File
@@ -5,7 +5,8 @@
// confirmação curta no lugar. Nada aqui busca dados: tudo vem por props; cada ação chama `run` (useClipperAction).
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
ACTIVE_CLIP, CLIP_STATUS, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore,
ACTIVE_CLIP, CLIP_STATUS, DEV_LAYER_LABEL, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore,
reviewHasDevLayers,
type Clip, type ClipAnalysis, type ClipTags, type Situation, type useClipperAction,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
@@ -84,14 +85,20 @@ export function DeleteControl({ clip, deleting, disabled, onDelete }: { clip: Cl
/* ---------- Cartão do corte ---------- */
export function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
/** `show = "final"` toca o vídeo final (quando pronto); o padrão é o de revisão (o da fila). */
export function ClipMedia({ clip, version, show = "review" }: { clip: Clip; version: string; show?: "review" | "final" }) {
const busy = ACTIVE_CLIP.includes(clip.status);
const poster = clip.thumb ? fileUrl(clip.thumb) : undefined;
const final = show === "final" && clip.final?.status === "ready" && clip.final.file ? clip.final : null;
const file = final ? final.file : clip.file;
const thumb = final?.thumb ?? clip.thumb;
const poster = thumb ? fileUrl(thumb) : undefined;
const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60";
if (clip.file && !busy) {
if (file && !busy) {
const v = final ? `final-${final.at ?? ""}` : version;
return (
<video key={version} controls preload="metadata" poster={poster} aria-label={`Vídeo do corte: ${clip.title || clip.id}`}
src={`${fileUrl(clip.file)}&v=${encodeURIComponent(version)}`}
<video key={`${show}-${v}`} controls preload="metadata" poster={poster}
aria-label={`${final ? "Vídeo final" : "Vídeo de revisão"} do corte: ${clip.title || clip.id}`}
src={`${fileUrl(file)}&v=${encodeURIComponent(v)}`}
className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} />
);
}
@@ -107,6 +114,98 @@ export function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
);
}
/* ---------- Vídeo de revisão × vídeo final (doc/clipador/REVISAO.md) ---------- */
function devLayersText(clip: Clip): string {
const layers = clip.review?.devLayers ?? [];
return layers.map((l) => DEV_LAYER_LABEL[l] ?? l).join(", ");
}
/** Etiqueta curta para a lista: em que pé está o vídeo do corte (revisão com teste, final gerando/pronto/erro). */
export function VideoTag({ clip }: { clip: Clip }) {
const final = clip.final;
const tag = (tone: string, text: string, title: string) => (
<span className={cx("rounded-sm border px-1 text-[0.625rem]", tone)} title={title}>{text}</span>
);
if (final?.status === "pending" || final?.status === "rendering") {
return tag("border-info/40 text-info", "gerando final", "Aprovado: o vídeo final (sem as camadas de teste) está sendo gerado. A publicação espera por ele.");
}
if (final?.status === "error") return tag("border-danger/40 text-danger", "final com erro", `O vídeo final falhou: ${final.error ?? "erro"}. Abra o corte para tentar de novo.`);
if (final?.status === "ready") return tag("border-success/40 text-success", "final", "Vídeo final pronto: é ele que vai para as redes.");
if (clip.file && reviewHasDevLayers(clip) && clip.status !== "approved" && clip.status !== "published") {
return tag("border-warning/40 text-warning", "revisão · teste", `Vídeo de revisão com camadas de teste (${devLayersText(clip)}). Ao aprovar, sai o vídeo final sem elas.`);
}
return null;
}
/**
* Bloco do modal sob o vídeo: diz se o que está tocando é o vídeo de revisão (com camadas de teste) ou o final, mostra o
* estado do final depois de aprovar (gerando… / pronto / erro com "tentar de novo") e troca o player entre os dois.
*/
export function ClipVideoState({ clip, show, onShow, pending, run }: {
clip: Clip; show: "review" | "final"; onShow: (show: "review" | "final") => void; pending: string | null; run: Run;
}) {
if (!clip.file || ACTIVE_CLIP.includes(clip.status)) return null;
const final = clip.final;
const approved = clip.status === "approved" || clip.status === "published";
const hasDev = reviewHasDevLayers(clip);
const retry = (text: string) => run("final", () => clipperCall<Clip>(`clips/${clip.id}/final`, "POST"), text);
const canToggle = final?.status === "ready" && !final.reused;
let reviewNote: ReactNode;
if (final?.status === "ready" && final.reused) {
reviewNote = <>O vídeo de revisão não tinha camada de teste: <strong className="font-medium text-success">ele já é o vídeo final</strong>.</>;
} else if (hasDev === true) {
reviewNote = <>Vídeo de <strong className="font-medium text-warning">revisão (com camadas de teste)</strong>: {devLayersText(clip)}.
{!approved && " Ao aprovar, sai o vídeo final sem elas — é só ele que vai para as redes."}</>;
} else if (hasDev === false) {
reviewNote = <>Vídeo de revisão sem camadas de teste{approved ? "" : ": ao aprovar, ele mesmo vira o final"}.</>;
} else {
reviewNote = <>Vídeo de revisão{approved ? "" : " (ao aprovar, o vídeo final é gerado de novo, sem camadas de teste)"}.</>;
}
return (
<section aria-label="Vídeo de revisão e vídeo final" className="grid gap-2 text-xs leading-relaxed">
{canToggle && (
<div role="group" aria-label="Qual vídeo tocar" className="flex gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{(["final", "review"] as const).map((v) => (
<button key={v} type="button" aria-pressed={show === v} onClick={() => onShow(v)}
className={cx("flex-1 rounded-[0.45rem] px-2 py-1 font-medium transition-colors focus-visible:outline-2 focus-visible:outline-accent",
show === v ? "bg-overlay text-fg" : "text-fg-muted hover:text-fg")}>
{v === "final" ? "Final" : "Revisão"}
</button>
))}
</div>
)}
{show === "final" && canToggle
? <p className="text-fg-muted">Tocando o <strong className="font-medium text-success">vídeo final</strong>: sem camadas de teste; é ele que vai para as redes.</p>
: <p className="text-fg-muted">{reviewNote}</p>}
{approved && (!final ? (
<div className="flex flex-wrap items-center gap-2 text-fg-subtle">
<span>Sem vídeo final ainda.</span>
<Button variant="ghost" size="sm" disabled={pending !== null} onClick={() => void retry("Vídeo final pedido.")}>
{pending === "final" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Gerar vídeo final
</Button>
</div>
) : final.status === "pending" || final.status === "rendering" ? (
<p className="flex items-center gap-2 text-info" role="status">
<Spinner className="size-3.5" />{final.status === "pending" ? "Na fila para gerar o vídeo final…" : "Gerando o vídeo final…"} A publicação espera por ele.
</p>
) : final.status === "error" ? (
<div className="grid gap-1.5 rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-danger">
<span className="flex items-start gap-1.5"><AlertIcon size={14} className="mt-px shrink-0" />
<span>O vídeo final falhou: <span className="font-mono break-words">{final.error ?? "erro"}</span>. Nada é publicado até ele sair.</span></span>
<Button variant="secondary" size="sm" className="justify-self-start" disabled={pending !== null} onClick={() => void retry("Tentando de novo: o vídeo final entrou na fila.")}>
{pending === "final" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Tentar de novo
</Button>
</div>
) : !final.reused ? (
<p className="flex items-center gap-1.5 text-success"><CheckIcon size={14} />Vídeo final pronto.</p>
) : null)}
</section>
);
}
export function JudgeVerdict({ clip }: { clip: Clip }) {
const judge = clip.judge;
if (!judge) {
+2 -1
View File
@@ -8,7 +8,7 @@ import {
type Clip, type ClipperSession,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts";
import { VideoTag, canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts";
import type { QueueFilter } from "./clipper-queue";
import { ArrowRightIcon, CheckIcon, RefreshIcon, ScissorsIcon, SparkIcon, UndoIcon, XIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
@@ -133,6 +133,7 @@ function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, o
<span className="rounded-sm border border-line-strong px-1 font-mono text-[0.625rem] text-fg-muted" title={`Idioma da live: ${language}`}>{languageShort(language)}</span>
)}
{horizontal && <span className="rounded-sm border border-line-strong px-1 text-[0.625rem] text-fg-muted">16:9</span>}
<VideoTag clip={clip} />
</p>
</div>
</Td>
+3 -1
View File
@@ -30,14 +30,16 @@ function serviceUrl(pathname: string): { url: string; key: string } {
* status · judge · emotes · games[/id[/research|refine|translate|notes/n]] (POST games = cadastrar; PUT/DELETE games/id) · channels[/id[/check|settings]]
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]]
* editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest)
* vídeo final (doc/clipador/REVISAO.md): POST clips/id/final
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
*/
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest))?))?)$/;
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final))?))?)$/;
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
const METHODS: [RegExp, string[]][] = [
[/^clips\/delete$/, ["POST"]],
[/^clips\/\d{1,9}$/, ["GET", "PATCH", "DELETE"]],
[/^clips\/\d{1,9}\/final$/, ["POST"]],
// Jogos: listar e cadastrar; gravar a edição (PUT ?lang=pt|en) e apagar (doc/clipador/JOGOS.md).
[/^games$/, ["GET", "POST"]],
[/^games\/[a-z0-9-]{1,60}$/, ["PUT", "DELETE"]],
+43
View File
@@ -234,8 +234,19 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
};
const clearQueue = () => dbm.run(`UPDATE publish_jobs SET status = 'canceled', cancel_reason = 'user'
WHERE status IN ('queued', 'scheduled', 'awaiting_approval', 'publishing')`);
// Clipador falso: cada corte responde aprovado e com o vídeo final pronto (doc/clipador/REVISAO.md); `finals`
// troca isso por corte. A listagem fica fora do ar (nada de sincronizar cortes neste bloco, como antes).
const clipperEnv = path.join(ROOT, "clipper", ".env");
const finals = new Map<string, { publishFile: string | null; final: { status: string; error: string | null } | null }>();
const clipBody = (id: string) => ({
id: Number(id), status: "approved", channelId: "twitch-xis", createdAt: "2026-11-01T00:00:00.000Z", title: "Corte", caption: "#corte",
file: MP4, thumb: null, edit: null,
...(finals.get(id) ?? { publishFile: MP4, final: { status: "ready", error: null, cover: null } }),
});
before(() => {
fs.mkdirSync(path.dirname(clipperEnv), { recursive: true });
fs.writeFileSync(clipperEnv, "CLIPPER_SERVICE_KEY=chave-de-teste\nCLIPPER_PORT=4520\n");
fs.mkdirSync(path.join(ROOT, "publisher"), { recursive: true });
fs.writeFileSync(path.join(ROOT, "publisher", ".env"), "PUBLISHER_SERVICE_KEY=chave-de-teste\nPUBLISHER_PORT=4530\n");
dbm.run("UPDATE account_networks SET status = 'connected', mode = 'official', enabled = 1 WHERE account_id = 'canal'");
@@ -247,6 +258,9 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
const body = typeof init?.body === "string" ? (JSON.parse(init.body) as Record<string, unknown>) : null;
calls.push({ method, path: url.pathname, body });
if (url.pathname === "/v1/status") return json({ browser: { found: true, kind: "chrome", path: "x" }, worker: "idle", queue: 0 });
if (url.pathname === "/v1/clips") throw new TypeError("fetch failed");
const clip = /^\/v1\/clips\/(\d+)$/.exec(url.pathname);
if (clip) return json(clipBody(clip[1]));
const prof = /^\/v1\/profiles\/([^/]+)$/.exec(url.pathname);
if (prof && method === "GET") return json(profile(decodeURIComponent(prof[1])));
if (url.pathname === "/v1/jobs" && method === "POST") return onCreate(body!);
@@ -260,6 +274,35 @@ describe("despachante: corridas, clientRef e vínculos (ALTOS)", () => {
after(() => {
globalThis.fetch = realFetch;
fs.rmSync(clipperEnv, { force: true });
});
it("corte sem vídeo final pronto espera na fila; com o final pronto sai com o arquivo FINAL, nunca o de revisão", async () => {
clearQueue();
const id = queuedClipJob();
const sourceId = dbm.get<{ source_id: string }>("SELECT source_id FROM publish_jobs WHERE id = ?", id)!.source_id;
const files: string[] = [];
onCreate = async (body) => { files.push(String(body.file)); return json(remoteJob("pj-final"), 201); };
finals.set(sourceId, { publishFile: null, final: { status: "rendering", error: null } });
await pub.dispatcherTick();
let job = pub.getJobView(id)!;
assert.equal(job.status, "queued");
assert.match(job.step, /vídeo final/);
finals.set(sourceId, { publishFile: null, final: { status: "error", error: "ffmpeg caiu" } });
await pub.dispatcherTick();
assert.equal(pub.getJobView(id)!.status, "queued");
assert.deepEqual(files, []); // nada foi ao Publicador enquanto não havia final
const finalFile = "output/clipper/3/clip-9-final.mp4";
fs.mkdirSync(path.join(ROOT, "output", "clipper", "3"), { recursive: true });
fs.writeFileSync(path.join(ROOT, finalFile), "mp4 final");
finals.set(sourceId, { publishFile: finalFile, final: { status: "ready", error: null } });
await pub.dispatcherTick();
job = pub.getJobView(id)!;
assert.equal(job.status, "publishing");
assert.equal(job.file, finalFile);
assert.deepEqual(files, [path.resolve(ROOT, finalFile)]);
finals.delete(sourceId);
});
it("cancelar enquanto o Publicador cria o envio: o job fica cancelado e o envio é cancelado lá", async () => {
+23 -1
View File
@@ -4,7 +4,7 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
DEFAULT_SLOTS, clientRefFor, isDue, localDay, mayBeLive, needsReflow, nextFreeSlot, parseVideoUrl, placeJob, planClipSync, readPublisherJob, sendBlocker,
DEFAULT_SLOTS, clientRefFor, clipPublishFile, isDue, localDay, mayBeLive, needsReflow, nextFreeSlot, parseVideoUrl, placeJob, planClipSync, readPublisherJob, sendBlocker,
tagsFromCaption, zonedTimeToUtc, type ClipInfo, type ClipTarget, type ExistingJob,
} from "./publishing-rules";
@@ -254,3 +254,25 @@ describe("envio: idempotência, reencaixe e confirmação", () => {
assert.match(sendBlocker({ status: "expired", enabled: 1 }, false)!, /venceu/);
});
});
describe("corte: só o vídeo final vai para as redes (doc/clipador/REVISAO.md)", () => {
const review = "output/clipper/3/clip-9.mp4";
it("final pronto: publica o final, não o de revisão", () => {
assert.deepEqual(clipPublishFile({ file: review, publishFile: "output/clipper/3/clip-9-final.mp4", final: { status: "ready", error: null } }),
{ file: "output/clipper/3/clip-9-final.mp4" });
});
it("sem final pronto espera, nunca devolve o vídeo de revisão", () => {
for (const final of [null, { status: "pending" as const, error: null }, { status: "rendering" as const, error: null }, { status: "error" as const, error: "ffmpeg" }]) {
const target = clipPublishFile({ file: review, publishFile: null, final });
assert.ok("wait" in target, JSON.stringify(final));
}
assert.match((clipPublishFile({ file: review, publishFile: null, final: { status: "error", error: "ffmpeg caiu" } }) as { wait: string }).wait, /ffmpeg caiu/);
});
it("Clipador antigo (sem `publishFile`) continua usando o arquivo do corte", () => {
assert.deepEqual(clipPublishFile({ file: review }), { file: review });
assert.ok("wait" in clipPublishFile({ file: null }));
});
});
+25
View File
@@ -182,6 +182,31 @@ export type ClipAction =
| { kind: "forget_auto"; clipId: number }
| { kind: "mark_clip_published"; clipId: number };
/** O que o Clipador diz do vídeo de um corte (doc/clipador/REVISAO.md). `publishFile` ausente = Clipador antigo. */
export type ClipVideo = {
file: string | null;
publishFile?: string | null;
final?: { status: "pending" | "rendering" | "ready" | "error"; error: string | null } | null;
};
/**
* Arquivo de um corte que pode ir para as redes: SÓ o vídeo final (sem as camadas de teste do vídeo de revisão).
* Sem final pronto, devolve o motivo de esperar — nunca o vídeo de revisão (`file`). Clipador antigo (sem o campo
* `publishFile`) não tem vídeo de revisão separado: vale `file`.
*/
export function clipPublishFile(clip: ClipVideo): { file: string } | { wait: string } {
if (clip.publishFile) return { file: clip.publishFile };
if (clip.publishFile === undefined) return clip.file ? { file: clip.file } : { wait: "Esperando: o corte ainda não tem vídeo pronto." };
const final = clip.final;
if (final?.status === "pending" || final?.status === "rendering") {
return { wait: "Esperando o vídeo final do Clipador (gerando, sem as camadas de teste)." };
}
if (final?.status === "error") {
return { wait: `Esperando: o vídeo final deu erro no Clipador (${final.error ?? "erro"}). Use “Tentar de novo” no corte.` };
}
return { wait: "Esperando o vídeo final: o corte precisa estar aprovado no Clipador." };
}
const PUBLISHABLE = new Set(["ready", "approved"]);
/** Estados do corte em que os jobs não enviados continuam válidos. */
const KEEPS_JOBS = new Set(["ready", "approved", "published"]);
+41 -8
View File
@@ -19,9 +19,9 @@ import { ServiceError } from "./http";
import { REPO_ROOT, SERVABLE_ROOTS, resolveInside, storyDir } from "./paths";
import { cancelJob, createJob, getJob, profileIdFor, publisherStatus, type PublisherJob } from "./publisher";
import {
OCCUPYING, UNSENT, aiGeneratedFor, clientRefFor, isDue, jobActions, mayBeLive, needsReflow, parseVideoUrl, placeJob, planClipSync, readPublisherJob,
OCCUPYING, UNSENT, aiGeneratedFor, clientRefFor, clipPublishFile, isDue, jobActions, mayBeLive, needsReflow, parseVideoUrl, placeJob, planClipSync, readPublisherJob,
sendBlocker, tagsFromCaption,
type ClipAction, type ClipInfo, type ClipTarget, type ExistingJob,
type ClipAction, type ClipInfo, type ClipTarget, type ClipVideo, type ExistingJob,
} from "./publishing-rules";
import { autoCollectMetrics } from "./metrics-sync";
import { getSettings } from "./settings";
@@ -197,8 +197,14 @@ export function placeApproved(jobId: number, opts: {
type ClipView = {
id: number; status: string; channelId: string | null; createdAt: string; title: string; caption: string;
file: string | null; thumb: string | null; edit: { cover: string | null } | null;
/** Vídeo final (sem as camadas de teste do vídeo de revisão): só ele vai para as redes. doc/clipador/REVISAO.md */
publishFile?: ClipVideo["publishFile"];
final?: (NonNullable<ClipVideo["final"]> & { cover: string | null }) | null;
};
/** Arquivo que fica no job: o final, se já existe; senão o de revisão só como referência — `sendDue` troca pelo final. */
const jobFileOf = (clip: ClipView) => clip.publishFile ?? clip.file;
async function fetchClip(clipId: number): Promise<ClipView | null> {
const response = await clipperFetch(`/v1/clips/${clipId}`, {}, 15_000);
if (response.status === 404) return null;
@@ -479,7 +485,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
if (!existing) {
const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, origin, created_at, updated_at)
VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', 'manual', ?, ?)`,
account.id, platform, String(clipId), clip.channelId ?? "", clip.file, cover, title, caption, ts, ts);
account.id, platform, String(clipId), clip.channelId ?? "", jobFileOf(clip), cover, title, caption, ts, ts);
toPlace.push(Number(info.lastInsertRowid));
} else if (existing.status === "published") {
skipped.push({ platform, reason: "já foi publicado nesta rede" });
@@ -494,7 +500,7 @@ export async function publishClip(clipId: number, input: { accountId?: unknown;
} else {
// Aguardando aprovação, cancelado, falhou (sem envio no Publicador) ou pediu login: volta com o vídeo atual.
run("UPDATE publish_jobs SET file = ?, cover = ?, title = ?, caption = ?, origin = 'manual', updated_at = ? WHERE id = ?",
clip.file, cover, title, caption, ts, existing.id);
jobFileOf(clip), cover, title, caption, ts, existing.id);
toPlace.push(existing.id);
}
}
@@ -712,11 +718,12 @@ async function listClips(query: string): Promise<FullClip[]> {
return ((await response.json()) as { clips: FullClip[] }).clips;
}
/** Capa do corte: a do editor; senão `clip-<id>-cover.jpg` ao lado do vídeo; senão a miniatura. */
/** Capa do corte: a do vídeo final; senão 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));
let found: string | null = null;
if (exists(clip.edit?.cover)) found = clip.edit!.cover;
if (clip.publishFile && exists(clip.final?.cover)) found = clip.final!.cover;
else 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)) found = cover;
@@ -840,7 +847,7 @@ async function applyClipActions(actions: ClipAction[], clips: Map<number, FullCl
const info = run(`INSERT INTO publish_jobs (account_id, platform, source_kind, source_id, source_label, file, cover, title, caption, status, created_at, updated_at)
VALUES (?, ?, 'clip', ?, ?, ?, ?, ?, ?, 'awaiting_approval', ?, ?)
ON CONFLICT (account_id, platform, source_kind, source_id) DO NOTHING`,
a.accountId, a.platform, String(clip.id), clip.channelId ?? "", clip.file, clipCover(clip),
a.accountId, a.platform, String(clip.id), clip.channelId ?? "", jobFileOf(clip), clipCover(clip),
(clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, ts);
if (approved && info.changes > 0) placeApproved(Number(info.lastInsertRowid), { from: ["awaiting_approval"] });
break;
@@ -860,7 +867,7 @@ async function applyClipActions(actions: ClipAction[], clips: Map<number, FullCl
progress = 0, attempts = attempts + 1, schedule_source = 'auto', step = 'O corte está pronto de novo.', file = ?, cover = ?,
title = ?, caption = ?, scheduled_at = NULL, updated_at = ?
WHERE id = ? AND status = 'canceled' AND cancel_reason IN ('source_changed', 'unlinked')`,
clip.file, clipCover(clip), (clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, a.jobId).changes;
jobFileOf(clip), clipCover(clip), (clip.title || `Corte ${clip.id}`).slice(0, 100), (clip.caption ?? "").slice(0, 2200), ts, a.jobId).changes;
if (revived && a.approved && !failedApprovals.has(clip.id)) placeApproved(a.jobId, { from: ["awaiting_approval"] });
break;
}
@@ -1023,6 +1030,20 @@ function episodeUsesPersonaVoice(episodeId: number): boolean {
}
}
/** Vídeo final de um job de corte, lido no Clipador agora; ou o motivo de esperar (Clipador fora, final não pronto). */
async function clipFinalForJob(job: JobRow): Promise<{ file: string; cover: string | null } | { wait: string }> {
let clip: ClipView | null;
try {
clip = await fetchClip(Number(job.source_id));
} catch (error) {
return { wait: `Esperando o Clipador para conferir o vídeo final (${errorText(error)}).` };
}
if (!clip) return { wait: "Esperando: o corte não existe mais no Clipador." };
const target = clipPublishFile(clip);
if ("wait" in target) return target;
return { file: target.file, cover: clip.publishFile ? clipCover(clip) : null };
}
/**
* Envia ao Publicador os jobs vencidos cujo perfil está pronto (um envio por perfil por vez). Seguro contra:
* - cancelamento no meio do ciclo: relê a linha antes de enviar e grava com UPDATE condicional; se o job mudou
@@ -1055,6 +1076,18 @@ async function sendDue(): Promise<void> {
}
const key = `${job.account_id}|${job.platform}`;
if (busy.has(key) || sent >= MAX_SENDS_PER_TICK) { setStep("Esperando o envio anterior terminar."); continue; }
if (job.source_kind === "clip") {
// Corte: só o vídeo FINAL vai para as redes (doc/clipador/REVISAO.md). Relê no Clipador na hora de enviar e,
// sem final pronto, espera — nunca manda o vídeo de revisão (com as camadas de teste).
const target = await clipFinalForJob(job);
if ("wait" in target) { setStep(target.wait); continue; }
if (target.file !== job.file || (target.cover && target.cover !== job.cover)) {
run("UPDATE publish_jobs SET file = ?, cover = COALESCE(?, cover), updated_at = ? WHERE id = ? AND status = 'queued'",
target.file, target.cover, now(), job.id);
job.file = target.file;
if (target.cover) job.cover = target.cover;
}
}
// O Publicador só aceita arquivos dentro de output/, stories/ ou assets/ (as mesmas pastas que o painel serve).
const file = resolveInside(job.file, SERVABLE_ROOTS);
if (!file || !fs.existsSync(file)) {