Merge branch 'clipper/final' into clipper/integ
This commit is contained in:
@@ -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"]],
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
Reference in New Issue
Block a user