Files
o2o-castad-frontend/src/utils/p2vApi.ts
T

194 lines
7.7 KiB
TypeScript

/**
* Poster to Video (P2V) 클라이언트.
*
* castad 백엔드의 `/p2v/*` 를 다른 파이프라인(ADO2·썰박스)과 같은 방식으로 부른다 —
* `authenticatedFetch` 가 Bearer 토큰을 싣는다. 잡 소유권·크레딧은 백엔드가 맡는다.
*
* 크레딧은 생성 요청 시점에 선차감되고, 실패하면 환불된다(썰박스와 같다).
* 잔액이 모자라면 402 가 오며, 호출부가 충전 화면으로 유도할 수 있게
* `InsufficientCreditError` 로 던진다.
*/
import { ContentType, P2vContentType } from '../types/api';
import { API_URL, InsufficientCreditError, authenticatedFetch } from './api';
/**
* 404 — 서버에 그 잡이 없다(지워졌거나 내 것이 아니다). 화면은 처음으로 되돌려야 한다.
*
* 상태 코드로 판정하는 이유: 서버 detail 문구("잡 없음")를 문자열로 맞추려다
* 실제로 한 번 놓쳤다. 문구는 서버 사정으로 바뀌고 번역도 되지만 코드는 안 바뀐다.
*/
export class P2vNotFoundError extends Error {
constructor(detail: string) {
super(detail);
this.name = 'P2vNotFoundError';
}
}
export async function p2vFetch<T>(path: string, init?: RequestInit): Promise<T> {
const res = await authenticatedFetch(`${API_URL}${path}`, init);
if (res.status === 402) throw new InsufficientCreditError();
if (!res.ok) {
// FastAPI 는 {detail: ...} 로 준다. 본문이 없는 에러(502 등)도 있으므로 감싼다
let detail = res.statusText;
try {
const body = await res.json();
detail = typeof body.detail === 'string' ? body.detail : JSON.stringify(body);
} catch {
/* 본문 없음 — statusText 로 간다 */
}
if (res.status === 404) throw new P2vNotFoundError(detail);
throw new Error(detail);
}
return res.json() as Promise<T>;
}
// ── 타입 (백엔드 app/p2v/api/routers/v1/view.py 와 1:1) ───────────────
export type P2vStageStatus = 'idle' | 'running' | 'done' | 'failed';
export interface P2vStageState {
status: P2vStageStatus;
started: number | null;
ended: number | null;
}
export interface PosterMeta {
event_name: string;
date_text: string;
place: string;
category: string;
keywords: string[];
region_guess?: string;
}
export interface P2vJob {
id: number;
kind: 'f1';
name: string;
status: 'queued' | 'running' | 'awaiting_review' | 'failed' | 'done';
stage: string | null;
stages: Record<string, P2vStageState>;
narration: string[] | null;
motion_elements?: string[] | null;
metadata: PosterMeta | null;
error: { stage: string; detail: string } | null;
/** 산출물은 Azure Blob 의 절대 URL 이다 */
artifacts: Record<string, string>;
created_at: number;
}
/** 잡 id. 서버는 숫자로 주고, 화면은 localStorage 때문에 문자열로도 든다 */
export type P2vJobId = string | number;
// ── F1 (포스터 → 영상) ────────────────────────────────────────────────
/** 포스터 업로드 → 잡 생성. 반환된 id 로 폴링한다. 크레딧이 먼저 차감된다 */
export async function createPosterJob(poster: File, name: string): Promise<{ id: string }> {
const fd = new FormData();
fd.append('poster', poster);
fd.append('name', name);
const { id } = await p2vFetch<{ id: number }>('/p2v/f1/jobs', { method: 'POST', body: fd });
// 화면은 잡 id 를 localStorage 문자열로 들고 있어 경계에서 맞춘다
return { id: String(id) };
}
export const getPosterJob = (id: P2vJobId): Promise<P2vJob> =>
p2vFetch<P2vJob>(`/p2v/f1/jobs/${id}`);
export const updatePosterNarration = (id: P2vJobId, narration: string[]): Promise<unknown> =>
p2vFetch(`/p2v/f1/jobs/${id}/narration`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ narration }),
});
export const updatePosterMetadata = (
id: P2vJobId,
meta: { event_name: string; date_text: string; place: string },
): Promise<unknown> =>
p2vFetch(`/p2v/f1/jobs/${id}/metadata`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(meta),
});
/** 검수 승인 → TTS·BGM·애니메이션·렌더가 이어진다. motions 를 넘기면 모션 선정을 덮어쓴다 */
export const approvePosterJob = (id: P2vJobId, motions?: string[] | null): Promise<unknown> =>
p2vFetch(`/p2v/f1/jobs/${id}/approve`, {
method: 'POST',
...(motions
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ motions }) }
: {}),
});
export const deletePosterJob = (id: P2vJobId): Promise<unknown> =>
p2vFetch(`/p2v/f1/jobs/${id}`, { method: 'DELETE' });
// ── 통합 콘텐츠 목록 ──────────────────────────────────────────────────
export const isP2vContent = (type: ContentType | P2vContentType): type is P2vContentType =>
type === 'p2v_video' || type === 'p2v_playreel';
export interface P2vDetailItem {
type: P2vContentType;
content_id: number;
video_url: string;
poster_url: string | null;
title: string | null;
created_at: string;
like_count: number;
is_liked_by_me: boolean;
}
/** 비로그인도 보는 공개 상세. 소유자 전용 /jobs/{id} API 와 구분한다. */
export async function getP2vContentById(type: P2vContentType, id: string): Promise<P2vDetailItem> {
const kind = type === 'p2v_video' ? 'f1' : 'playreel';
const response = await authenticatedFetch(
`${API_URL}/p2v/${kind}/${encodeURIComponent(id)}`,
{ method: 'GET' },
{ redirectOnAuthFail: false },
);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
}
/**
* 내 콘텐츠에서 P2V 항목 삭제. 종류마다 테이블이 달라 경로가 갈린다.
* ⚠️ `deleteVideo`(`/archive/videos/{id}`, Video.id 기준)와 혼용하면 id 가 겹치는
* 엉뚱한 ADO2 영상이 지워진다.
*/
export const deleteP2vContent = (type: P2vContentType, id: number): Promise<unknown> =>
p2vFetch(`/p2v/${type === 'p2v_video' ? 'f1' : 'playreel'}/jobs/${id}`, { method: 'DELETE' });
// ── 진행 계산 ────────────────────────────────────────────────────────
/** 아직 도는 중인가. 이 두 상태에서만 폴링을 계속한다 */
export const isP2vActive = (job: P2vJob | null): boolean =>
job !== null && (job.status === 'queued' || job.status === 'running');
/** 스테이지 진행률(%) — 선형 진행바용. 도는 중인 스테이지는 절반으로 친다 */
export function p2vProgress(job: Pick<P2vJob, 'stages'> | null): number {
if (!job) return 0;
const states = Object.values(job.stages);
if (states.length === 0) return 0;
const done = states.filter((s) => s.status === 'done').length;
const running = states.some((s) => s.status === 'running') ? 0.5 : 0;
return Math.round(((done + running) / states.length) * 100);
}
/**
* 검수 게이트를 이미 지났는가.
*
* 스텝퍼가 "분석 → 검수 → 생성" 중 어디인지 알아야 하는데 status 만으로는
* 검수 전 running 과 승인 후 running 이 구분되지 않는다. tts 는 승인 이후에만
* 시작하므로 이게 게이트 통과의 신호다(스테이지 이름을 박는 대신 F1_STAGES 순서에
* 의존하지 않도록 tts 하나만 본다 — 게이트가 옮겨가면 이 상수만 고친다).
*/
const POST_REVIEW_STAGE = 'tts';
export const isPastReview = (job: P2vJob | null): boolean =>
!!job && job.stages[POST_REVIEW_STAGE]?.status !== undefined
&& job.stages[POST_REVIEW_STAGE].status !== 'idle';