190 lines
11 KiB
TypeScript
190 lines
11 KiB
TypeScript
"use client";
|
||
|
||
import { use, useEffect, useRef, useState } from "react";
|
||
import Link from "next/link";
|
||
import { useRouter, useSearchParams } from "next/navigation";
|
||
import StageStepper, { stageProgress } from "@/components/stage-stepper";
|
||
import { GateBody, GateShell } from "@/components/gate-card";
|
||
import { apiFetch } from "@/lib/api";
|
||
import { GATE_META, PLAYREEL_STAGE_LABELS, usePlayreelJob, type PlayreelJob } from "@/lib/playreel";
|
||
import { useAutoApprove } from "@/lib/prefs";
|
||
import { isAutoApprovable } from "@/components/auto-approve";
|
||
|
||
const RUNNING_COPY: Record<string, string> = {
|
||
fetch: "상세페이지에서 포스터와 정보를 가져오는 중", split: "상세페이지를 섹션으로 나누는 중",
|
||
upscale: "포스터 화질을 보정하는 중 (약 1분)", analyze: "포스터에서 움직일 요소를 찾는 중",
|
||
motion: "연출 프롬프트를 쓰는 중", narration: "나레이션 문장을 쓰는 중",
|
||
tts: "나레이션을 읽는 중", bgm: "배경음악을 만드는 중 (몇 분 걸릴 수 있습니다)",
|
||
i2v: "포스터를 움직이는 중 (5~8분)", hybrid: "원본 글자를 다시 덮는 중",
|
||
compose: "상세페이지 스크롤과 함께 조립하는 중", review: "자동 검사 중",
|
||
};
|
||
|
||
export default function PlayreelJobPage({ params }: { params: Promise<{ id: string }> }) {
|
||
const { id } = use(params);
|
||
const router = useRouter();
|
||
const mock = useSearchParams().get("mock");
|
||
const { job, error, refresh } = usePlayreelJob(id, mock);
|
||
const edits = useRef<unknown>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [actionError, setActionError] = useState<string | null>(null);
|
||
const prefs = useAutoApprove();
|
||
const autoFired = useRef<Set<string>>(new Set()); // 같은 게이트에 두 번 보내지 않는다
|
||
const [autoNote, setAutoNote] = useState<string | null>(null);
|
||
|
||
// 게이트 ①·③ 자동 승인 — 폴링이 awaiting_review 를 보는 순간 한 번만 approve. mock 은 화면 확인용이라 제외.
|
||
const autoGate = !mock && job?.status === "awaiting_review" && isAutoApprovable(job.gate) && prefs[job.gate] ? job.gate : null;
|
||
useEffect(() => {
|
||
if (!autoGate || autoFired.current.has(autoGate)) return;
|
||
autoFired.current.add(autoGate);
|
||
const g = GATE_META[autoGate];
|
||
apiFetch(`/api/playreel/jobs/${id}/approve`, {
|
||
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ gate: autoGate }),
|
||
}).then(() => {
|
||
setAutoNote(`${g.step}단계 ${g.name}을 자동 승인했습니다.`);
|
||
refresh();
|
||
}).catch((e) => {
|
||
autoFired.current.delete(autoGate); // 실패하면 사람이 누를 수 있게 카드가 그대로 남는다
|
||
setActionError(`자동 승인 실패 — 직접 확인해 주세요. ${(e as Error).message}`);
|
||
});
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
}, [autoGate, id]);
|
||
|
||
if (error) return <p style={{ color: "#ff7a7a" }}>{error}</p>;
|
||
if (!job) return <p style={{ color: "var(--color-text-gray-400)" }}>불러오는 중…</p>;
|
||
|
||
const post = async (path: string, body?: unknown) => {
|
||
setBusy(true);
|
||
setActionError(null);
|
||
try {
|
||
if (mock) {
|
||
// 서버 없이 화면만 볼 때 — 다음 게이트로 넘긴다
|
||
const i = job.gate ? Object.keys(GATE_META).indexOf(job.gate) : -1;
|
||
const next = Object.keys(GATE_META)[i + 1] ?? "done";
|
||
router.push(`/playreel/mock?mock=${path.endsWith("back") ? Object.keys(GATE_META)[Math.max(0, i - 1)] : next}`);
|
||
return;
|
||
}
|
||
await apiFetch(`/api/playreel/jobs/${id}/${path}`, {
|
||
method: "POST",
|
||
...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}),
|
||
});
|
||
edits.current = null;
|
||
refresh();
|
||
} catch (e) {
|
||
// 실패 화면을 띄워둔 사이에 끝났을 수 있다. 그때는 에러 대신 결과를 보여준다
|
||
const latest = await apiFetch<PlayreelJob>(`/api/playreel/jobs/${id}`).catch(() => null);
|
||
if (latest?.status === "done") {
|
||
refresh();
|
||
return;
|
||
}
|
||
setActionError((e as Error).message);
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
};
|
||
|
||
const remove = async () => {
|
||
if (!confirm(`"${job.name}" 작업과 만들어진 파일을 모두 지웁니다. 되돌릴 수 없습니다.`)) return;
|
||
await apiFetch(`/api/playreel/jobs/${id}`, { method: "DELETE" }).catch((e) => setActionError((e as Error).message));
|
||
router.push("/");
|
||
};
|
||
|
||
const pct = stageProgress(job);
|
||
const gate = job.gate ? GATE_META[job.gate] : null;
|
||
|
||
return (
|
||
<div>
|
||
<div style={{ display: "flex", alignItems: "flex-start" }}>
|
||
<Link href="/" className="btn-back">‹ 뒤로가기</Link>
|
||
{job.status !== "running" && !mock && (
|
||
<button onClick={remove} disabled={busy} className="btn-back" style={{ marginLeft: "auto", color: "#ff8c8c", borderColor: "rgba(255,140,140,0.4)" }}>작업 삭제</button>
|
||
)}
|
||
</div>
|
||
|
||
<div className="stepper-scroll"><StageStepper job={job} labels={PLAYREEL_STAGE_LABELS} /></div>
|
||
|
||
<h1 className="page-title">{job.status === "done" ? "예고편 완성" : job.name}</h1>
|
||
<p className="page-subtitle">
|
||
{job.status === "awaiting_review" && gate ? `확인 ${gate.step}/5 · ${gate.name}이 필요합니다` :
|
||
job.status === "running" ? (RUNNING_COPY[job.stage ?? ""] ?? "만드는 중") :
|
||
job.status === "queued" ? `대기 중 · 앞에 ${job.queue_size ?? 0}편` :
|
||
job.status === "failed" ? "작업이 중단되었습니다" : "아카이브에 저장되었습니다"}
|
||
{job.credits_used > 0 && <span style={{ color: "var(--color-text-gray-500)" }}> · 사용 {job.credits_used}크레딧</span>}
|
||
</p>
|
||
|
||
<div className="card" style={{ marginTop: "2rem", padding: "var(--spacing-page-md)" }}>
|
||
{(job.status === "running" || job.status === "queued") && (
|
||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "3rem 0", gap: "1.5rem" }}>
|
||
<div className="gen-spinner" />
|
||
<p style={{ margin: 0, color: "var(--color-text-gray-300)" }}>{RUNNING_COPY[job.stage ?? ""] ?? "준비 중"}</p>
|
||
<div style={{ width: 320 }}>
|
||
<div className="progress-bar-container"><div className="progress-bar-fill" style={{ width: `${pct}%` }} /></div>
|
||
<p style={{ textAlign: "center", margin: "0.5rem 0 0", fontSize: "var(--text-sm)", color: "var(--color-text-gray-400)" }}>{pct}%</p>
|
||
</div>
|
||
<p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-text-gray-500)" }}>
|
||
다음 확인 요청이 오면 이 화면에 나타납니다. 창을 닫아도 작업은 계속됩니다.
|
||
</p>
|
||
{autoNote && <p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-mint)" }}>{autoNote} <Link href="/playreel" style={{ color: "inherit" }}>설정 바꾸기 ›</Link></p>}
|
||
</div>
|
||
)}
|
||
|
||
{autoGate && !actionError && (
|
||
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "3rem 0", gap: "1rem" }}>
|
||
<div className="gen-spinner" />
|
||
<p style={{ margin: 0, color: "var(--color-text-gray-300)" }}>{GATE_META[autoGate].step}단계 {GATE_META[autoGate].name}을 자동 승인하는 중</p>
|
||
<p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-text-gray-500)" }}>시작 화면에서 끌 수 있습니다.</p>
|
||
</div>
|
||
)}
|
||
|
||
{job.status === "awaiting_review" && job.gate && job.review && !(autoGate && !actionError) && (
|
||
<GateShell gate={job.gate} busy={busy} error={actionError}
|
||
onApprove={() => post("approve", { gate: job.gate, edits: edits.current })}
|
||
onBack={gate?.canBack ? () => post("back") : undefined}
|
||
approveLabel={job.gate === "final_confirm" ? "승인하고 저장" : job.gate === "clip_confirm" ? "이 클립으로 계속" : undefined}>
|
||
<GateBody review={job.review} onEdits={(e) => { edits.current = e; }} />
|
||
{job.gate === "clip_confirm" && (
|
||
<button className="btn-outline btn-lg" style={{ marginTop: "0.75rem" }} disabled={busy} onClick={() => post("retry")}>
|
||
다시 만들기 (재과금)
|
||
</button>
|
||
)}
|
||
</GateShell>
|
||
)}
|
||
|
||
{job.status === "failed" && job.error && (
|
||
<div style={{ maxWidth: 640, margin: "0 auto" }}>
|
||
<p className="eyebrow" style={{ color: "#ff8c8c", margin: "0 0 1rem" }}>실패 · {PLAYREEL_STAGE_LABELS[job.error.stage] ?? job.error.stage}</p>
|
||
<pre className="card-inner" style={{ fontSize: "var(--text-sm)", whiteSpace: "pre-wrap", wordBreak: "break-all", maxHeight: 280, overflow: "auto", color: "var(--color-text-gray-400)", margin: 0 }}>{job.error.detail}</pre>
|
||
<div className="fail-actions">
|
||
<button className="btn-outline" disabled={busy} onClick={() => post("retry")}>다시 시도</button>
|
||
{job.error.stage === "i2v" && (
|
||
<button className="btn-tonal-mint" disabled={busy} onClick={() => post("force")}>클립은 쓸 만함 — 이대로 진행</button>
|
||
)}
|
||
</div>
|
||
{actionError && <p style={{ color: "#ff7a7a", fontSize: "var(--text-sm)", marginTop: "0.75rem", textAlign: "center" }}>{actionError}</p>}
|
||
</div>
|
||
)}
|
||
|
||
{job.status === "done" && (
|
||
<div className="result-grid">
|
||
<div className="card-inner result-video">
|
||
{job.artifacts.video
|
||
? <video src={job.artifacts.video} controls style={{ width: "100%", maxHeight: 560, borderRadius: "var(--radius-md)", display: "block" }} />
|
||
: <p style={{ color: "var(--color-text-gray-500)", fontSize: "var(--text-sm)" }}>영상</p>}
|
||
</div>
|
||
<div className="result-meta">
|
||
<p className="field-label" style={{ margin: 0 }}>파일명</p>
|
||
<p style={{ margin: "0.25rem 0 1rem", fontSize: "var(--text-xl)", fontWeight: 700 }}>{job.source.slug}_30_v{job.version}.mp4</p>
|
||
<p style={{ margin: 0, fontSize: "var(--text-sm)", color: "var(--color-text-gray-400)" }}>출처 · <a href={job.source.url} target="_blank" rel="noreferrer" style={{ color: "var(--color-mint)" }}>공연 상품페이지 열기 →</a></p>
|
||
<div className="result-actions">
|
||
<Link href="/" className="btn-tonal-mint" style={{ textDecoration: "none", textAlign: "center" }}>새 버전 만들기</Link>
|
||
{/* blob에 Content-Disposition이 박혀 있어 주소만 열면 내려받기가 된다.
|
||
<a download>은 다른 출처에 안 먹으므로 이 속성에 기대지 않는다 */}
|
||
<a href={job.artifacts.video} className="btn-cta" style={{ padding: "0.75rem 1rem", fontSize: "var(--text-base)", borderRadius: "var(--radius-xl)", textDecoration: "none" }}>MP4 다운로드</a>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|