feat(p2v): 무빙 포스터·롱컷 통합 및 상세·소셜 기능 연결

This commit is contained in:
skkim committed 2026-10-15 10:57:04 +09:00
1 parent cd71f6d9d3
commit c06018d88c
42 files changed
+3020 -1610

No files matched your search

+60 -130
View File
@@ -1,47 +1,18 @@
/**
* Poster to Video (P2V) 클라이언트.
*
* castad 백엔드가 아니라 **별도 서버(:8010)** 를 직접 호출한다. 다른 파이프라인들
* (ADO2·썰박스)이 `utils/api.ts` 로 castad 백엔드에 붙는 것과 대비된다.
* castad 백엔드의 `/p2v/*` 를 다른 파이프라인(ADO2·썰박스)과 같은 방식으로 부른다 —
* `authenticatedFetch` 가 Bearer 토큰을 싣는다. 잡 소유권·크레딧은 백엔드가 맡는다.
*
* 왜 프록시를 두지 않았나 — P2V 서버는 검증된 `scripts/*.py` 를 subprocess 로 감싼
* 단일 워커라 castad 백엔드에 흡수하려면 실행 환경(Higgsfield CLI·ffmpeg·모델 키)을
* 통째로 이식해야 한다. **내부 시연 범위**에서는 직접 호출이 맞고, 대외 공개 단계에서
* castad 백엔드에 `/p2v/*` 프록시를 세워 카카오 인증·크레딧 차감을 얹는 게 다음 수순이다.
* 그때 갈아끼울 지점은 이 파일 하나다.
*
* 인증은 단일 팀 키(`P2V_ACCESS_KEY`). 서버는 3경로로 받는다:
* - `X-P2V-Key` 헤더 → fetch 호출
* - `p2v_key` 쿠키 → **여기서는 못 쓴다.** castad 와 P2V 는 다른 오리진이라
* document.cookie 로 심어도 P2V 요청에 실리지 않는다.
* - `?key=` 쿼리 → 헤더를 못 붙이는 <img>/<video>/<a download> 용 (p2vFile)
* 크레딧은 생성 요청 시점에 선차감되고, 실패하면 환불된다(썰박스와 같다).
* 잔액이 모자라면 402 가 오며, 호출부가 충전 화면으로 유도할 수 있게
* `InsufficientCreditError` 로 던진다.
*/
/** P2V 서버 오리진. 배포 시 `.env` 의 VITE_P2V_URL 로 덮는다 */
export const P2V_URL = (import.meta.env.VITE_P2V_URL || 'http://localhost:8010').replace(/\/$/, '');
import { ContentType, P2vContentType } from '../types/api';
import { API_URL, InsufficientCreditError, authenticatedFetch } from './api';
/**
* 접근 키 저장소.
*
* storageKeys.K 에 넣지 않은 것은 의도적이다 — 그쪽 키들은 로그아웃·새 프로젝트에
* 일괄 삭제되는데, 이건 서버 자격증명이라 지워지면 시연 중에 매번 다시 물어야 한다.
*/
const KEY_STORAGE = 'castad_p2v_key';
export const getP2vKey = (): string => localStorage.getItem(KEY_STORAGE) ?? '';
export const setP2vKey = (key: string): void => localStorage.setItem(KEY_STORAGE, key.trim());
export const clearP2vKey = (): void => localStorage.removeItem(KEY_STORAGE);
/** 401 — 화면이 키 입력을 띄워야 하는 상황. 일반 실패와 구분해야 해서 타입을 나눈다 */
export class P2vAuthError extends Error {
constructor() {
super('P2V_AUTH_REQUIRED');
this.name = 'P2vAuthError';
}
}
/**
* 404 — 서버에 그 잡이 없다. 화면은 처음으로 되돌려야 한다.
* 404 — 서버에 그 잡이 없다(지워졌거나 내 것이 아니다). 화면은 처음으로 되돌려야 한다.
*
* 상태 코드로 판정하는 이유: 서버 detail 문구("잡 없음")를 문자열로 맞추려다
* 실제로 한 번 놓쳤다. 문구는 서버 사정으로 바뀌고 번역도 되지만 코드는 안 바뀐다.
@@ -54,16 +25,9 @@ export class P2vNotFoundError extends Error {
}
export async function p2vFetch<T>(path: string, init?: RequestInit): Promise<T> {
const key = getP2vKey();
const res = await fetch(`${P2V_URL}${path}`, {
...init,
headers: {
...(init?.headers ?? {}),
...(key ? { 'X-P2V-Key': key } : {}),
},
});
const res = await authenticatedFetch(`${API_URL}${path}`, init);
if (res.status === 401) throw new P2vAuthError();
if (res.status === 402) throw new InsufficientCreditError();
if (!res.ok) {
// FastAPI 는 {detail: ...} 로 준다. 본문이 없는 에러(502 등)도 있으므로 감싼다
@@ -80,20 +44,7 @@ export async function p2vFetch<T>(path: string, init?: RequestInit): Promise<T>
return res.json() as Promise<T>;
}
/**
* 정적 산출물(영상·이미지) URL.
*
* 서버가 주는 artifacts 값은 `/files/render/x.mp4` 같은 **루트 상대 경로**라
* 다른 오리진인 castad 에서는 그대로 쓸 수 없다. 오리진을 붙이고, 헤더를 실을 수 없는
* 태그(<video src> 등)를 위해 키를 쿼리로 태운다.
*/
export const p2vFile = (path: string | null | undefined): string => {
if (!path) return '';
const key = getP2vKey();
return `${P2V_URL}${path}${key ? `?key=${encodeURIComponent(key)}` : ''}`;
};
// ── 타입 (서버 jobs.py / routers 와 1:1) ──────────────────────────────
// ── 타입 (백엔드 app/p2v/api/routers/v1/view.py 와 1:1) ───────────────
export type P2vStageStatus = 'idle' | 'running' | 'done' | 'failed';
@@ -113,8 +64,8 @@ export interface PosterMeta {
}
export interface P2vJob {
id: string;
kind: 'f1' | 'f2';
id: number;
kind: 'f1';
name: string;
status: 'queued' | 'running' | 'awaiting_review' | 'failed' | 'done';
stage: string | null;
@@ -123,114 +74,93 @@ export interface P2vJob {
motion_elements?: string[] | null;
metadata: PosterMeta | null;
error: { stage: string; detail: string } | null;
/** 산출물은 Azure Blob 의 절대 URL 이다 */
artifacts: Record<string, string>;
created_at: number;
queue_size?: number;
template_id?: string | null;
}
/** 배포 등급. public-domain 만 외부 공개 가능 — 나머지는 내부 시연 한정 */
export type P2vLicense = 'public-domain' | 'internal-only' | 'user-uploaded';
export interface F2Template {
id: string;
name_ko: string;
thumb_url: string;
category: string;
license: P2vLicense;
attribution: string;
license_note: string;
/** 사용자가 올린 레퍼런스인가 (삭제 가능) */
removable: boolean;
small_ref: boolean;
}
export interface F2Category { id: string; label: string }
export interface F2Format { id: string; label: string }
export interface F2UploadHint { enabled: boolean; min_long_edge: number }
/** 잡 id. 서버는 숫자로 주고, 화면은 localStorage 때문에 문자열로도 든다 */
export type P2vJobId = string | number;
// ── F1 (포스터 → 영상) ────────────────────────────────────────────────
/** 포스터 업로드 → 잡 생성. 반환된 id 로 폴링한다 */
/** 포스터 업로드 → 잡 생성. 반환된 id 로 폴링한다. 크레딧이 먼저 차감된다 */
export async function createPosterJob(poster: File, name: string): Promise<{ id: string }> {
const fd = new FormData();
fd.append('poster', poster);
fd.append('name', name);
return p2vFetch<{ id: string }>('/api/f1/jobs', { method: 'POST', body: fd });
const { id } = await p2vFetch<{ id: number }>('/p2v/f1/jobs', { method: 'POST', body: fd });
// 화면은 잡 id 를 localStorage 문자열로 들고 있어 경계에서 맞춘다
return { id: String(id) };
}
export const getPosterJob = (id: string): Promise<P2vJob> =>
p2vFetch<P2vJob>(`/api/f1/jobs/${id}`);
export const getPosterJob = (id: P2vJobId): Promise<P2vJob> =>
p2vFetch<P2vJob>(`/p2v/f1/jobs/${id}`);
export const updatePosterNarration = (id: string, narration: string[]): Promise<unknown> =>
p2vFetch(`/api/f1/jobs/${id}/narration`, {
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: string,
id: P2vJobId,
meta: { event_name: string; date_text: string; place: string },
): Promise<unknown> =>
p2vFetch(`/api/f1/jobs/${id}/metadata`, {
p2vFetch(`/p2v/f1/jobs/${id}/metadata`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(meta),
});
/** 검수 승인 → TTS·BGM·애니메이션·렌더가 이어진다. motions 를 넘기면 모션 선정을 덮어쓴다 */
export const approvePosterJob = (id: string, motions?: string[] | null): Promise<unknown> =>
p2vFetch(`/api/f1/jobs/${id}/approve`, {
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 retryPosterJob = (id: string, motions?: string[] | null): Promise<unknown> =>
p2vFetch(`/api/f1/jobs/${id}/retry`, {
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 deletePosterJob = (id: string): Promise<unknown> =>
p2vFetch(`/api/f1/jobs/${id}`, { method: 'DELETE' });
// ── 통합 콘텐츠 목록 ──────────────────────────────────────────────────
// ── F2 (포스터 스타일링) ──────────────────────────────────────────────
export const isP2vContent = (type: ContentType | P2vContentType): type is P2vContentType =>
type === 'p2v_video' || type === 'p2v_playreel';
export const listF2Templates = (): Promise<F2Template[]> => p2vFetch<F2Template[]>('/api/f2/templates');
export const listF2Categories = (): Promise<F2Category[]> => p2vFetch<F2Category[]>('/api/f2/categories');
export const listF2Formats = (): Promise<F2Format[]> => p2vFetch<F2Format[]>('/api/f2/formats');
export const getF2UploadHint = (): Promise<F2UploadHint> => p2vFetch<F2UploadHint>('/api/f2/upload-hint');
/** 레퍼런스 업로드 — 저장 + 화풍 분석까지 서버가 동기로 끝낸다(10초 안팎) */
export async function createF2Template(reference: File, name: string): Promise<F2Template> {
const fd = new FormData();
fd.append('reference', reference);
fd.append('name', name);
return p2vFetch<F2Template>('/api/f2/templates', { method: 'POST', body: fd });
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;
}
export const deleteF2Template = (id: string): Promise<unknown> =>
p2vFetch(`/api/f2/templates/${id}`, { method: 'DELETE' });
export async function createStylingJob(
poster: File,
templateId: string,
format: string,
): Promise<{ id: string }> {
const fd = new FormData();
fd.append('poster', poster);
fd.append('template_id', templateId);
fd.append('format', format);
return p2vFetch<{ id: string }>('/api/f2/jobs', { method: 'POST', body: fd });
/** 비로그인도 보는 공개 상세. 소유자 전용 /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();
}
export const getStylingJob = (id: string): Promise<P2vJob> =>
p2vFetch<P2vJob>(`/api/f2/jobs/${id}`);
/**
* 내 콘텐츠에서 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' });
// ── 진행 계산 ────────────────────────────────────────────────────────
@@ -239,7 +169,7 @@ export const isP2vActive = (job: P2vJob | null): boolean =>
job !== null && (job.status === 'queued' || job.status === 'running');
/** 스테이지 진행률(%) — 선형 진행바용. 도는 중인 스테이지는 절반으로 친다 */
export function p2vProgress(job: P2vJob | null): number {
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;