feat(p2v): 무빙 포스터·롱컷 통합 및 상세·소셜 기능 연결
This commit is contained in:
1 parent
cd71f6d9d3
commit
c06018d88c
42 files changed
+3020
-1610
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import type { ContentType } from '../types/api';
|
||||
|
||||
/**
|
||||
* 기기의 네이티브 공유 시트를 열고 요청을 처리했는지 반환합니다.
|
||||
*
|
||||
@@ -32,9 +34,13 @@ export function buildVideoShareUrl(apiBaseUrl: string, videoId: number | string)
|
||||
export function buildContentShareUrl(
|
||||
apiBaseUrl: string,
|
||||
contentId: number | string,
|
||||
contentType: 'video' | 'ssul' = 'video',
|
||||
contentType: ContentType = 'video',
|
||||
): string {
|
||||
const base = apiBaseUrl.replace(/\/$/, '');
|
||||
if (contentType === 'p2v_video' || contentType === 'p2v_playreel') {
|
||||
const kind = contentType === 'p2v_video' ? 'f1' : 'playreel';
|
||||
return `${base}/p2v/${kind}/share/${encodeURIComponent(String(contentId))}`;
|
||||
}
|
||||
if (contentType === 'ssul') {
|
||||
return `${base}/ssul/share/${encodeURIComponent(String(contentId))}`;
|
||||
}
|
||||
|
||||
+60
-130
@@ -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;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Playreel(롱컷) 클라이언트 — 공연 상품페이지 URL → 30초 세로 예고편.
|
||||
*
|
||||
* castad 백엔드의 `/p2v/playreel/*` 를 부른다(p2vApi.ts 의 `p2vFetch` 를 공유).
|
||||
* 이 파이프라인은 사람이 확인하는 **게이트 5개**에서 멈춘다. 게이트마다 검수 페이로드
|
||||
* (`review`)가 오고, 승인할 때 고친 값(`edits`)을 함께 보낸다.
|
||||
*
|
||||
* 크레딧은 생성 요청 시점에 선차감되고, 실패하면 환불된다. 실패한 잡은 다시 돌릴 수
|
||||
* 없다(새로 만든다). 다시 돌릴 수 있는 것은 클립 검수 게이트의 "다시 만들기" 뿐이다.
|
||||
*/
|
||||
import { P2vJobId, P2vStageState, p2vFetch } from './p2vApi';
|
||||
|
||||
export type GateKey =
|
||||
| 'fetch_confirm'
|
||||
| 'analysis_confirm'
|
||||
| 'narration_confirm'
|
||||
| 'clip_confirm'
|
||||
| 'final_confirm';
|
||||
|
||||
export const GATE_ORDER: readonly GateKey[] = [
|
||||
'fetch_confirm', 'analysis_confirm', 'narration_confirm', 'clip_confirm', 'final_confirm',
|
||||
];
|
||||
|
||||
/**
|
||||
* 게이트 진행 상태. 문구는 locales 의 `playreel.gates.<key>` 에 있다.
|
||||
* 되돌리기는 크레딧을 이미 쓴 지점 뒤로는 서버가 거절한다(`REVERSIBLE_GATES`).
|
||||
*/
|
||||
export const GATE_CAN_BACK: Record<GateKey, boolean> = {
|
||||
fetch_confirm: false,
|
||||
analysis_confirm: true,
|
||||
narration_confirm: true,
|
||||
clip_confirm: false,
|
||||
final_confirm: false,
|
||||
};
|
||||
|
||||
// ── 게이트별 검수 페이로드 (백엔드 app/p2v/worker/gate.py 와 1:1) ──────────
|
||||
|
||||
export interface DetailSection {
|
||||
id: string;
|
||||
tag: string;
|
||||
label: string;
|
||||
thumb_url: string;
|
||||
height: number;
|
||||
/** 캐스팅 스케줄은 항상 포함 */
|
||||
required?: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
export interface FetchReview {
|
||||
poster_url: string;
|
||||
/** 800px 이하면 저해상 경고 */
|
||||
poster_width: number;
|
||||
meta: { title: string; date_text: string; place: string; cast: string[]; genre: string };
|
||||
sections: DetailSection[];
|
||||
}
|
||||
|
||||
export interface AnalysisReview {
|
||||
grid_url: string;
|
||||
movable: { key: string; label: string; on: boolean }[];
|
||||
fixed: { key: string; label: string; on: boolean }[];
|
||||
model: string;
|
||||
ip_risk: boolean;
|
||||
has_qr: boolean;
|
||||
}
|
||||
|
||||
export interface NarrationReview {
|
||||
lines: { slot: string; text: string }[];
|
||||
voice: { id: string; name: string; sample_url: string };
|
||||
est_seconds: number;
|
||||
}
|
||||
|
||||
export interface ClipReview {
|
||||
clip_url: string;
|
||||
frames_url: string;
|
||||
title_mae: number;
|
||||
gate_passed: boolean;
|
||||
gate_reason: string | null;
|
||||
}
|
||||
|
||||
export interface FinalReview {
|
||||
video_url: string;
|
||||
proof_url: string;
|
||||
duration: number;
|
||||
checks: { key: string; label: string; ok: boolean }[];
|
||||
version: number;
|
||||
}
|
||||
|
||||
export type GateReview =
|
||||
| { gate: 'fetch_confirm'; data: FetchReview }
|
||||
| { gate: 'analysis_confirm'; data: AnalysisReview }
|
||||
| { gate: 'narration_confirm'; data: NarrationReview }
|
||||
| { gate: 'clip_confirm'; data: ClipReview }
|
||||
| { gate: 'final_confirm'; data: FinalReview };
|
||||
|
||||
/** 승인할 때 함께 보내는 고친 값. 게이트마다 모양이 다르다 */
|
||||
export type GateEdits =
|
||||
| { sections: string[]; meta: FetchReview['meta'] }
|
||||
| { movable: string[]; fixed: string[]; model: string }
|
||||
| { lines: string[]; voice_id: string };
|
||||
|
||||
export interface PlayreelJob {
|
||||
id: number;
|
||||
kind: 'playreel';
|
||||
name: string;
|
||||
status: 'queued' | 'running' | 'awaiting_review' | 'failed' | 'done';
|
||||
stage: string | null;
|
||||
stages: Record<string, P2vStageState>;
|
||||
error: { stage: string; detail: string } | null;
|
||||
/** 산출물은 Azure Blob 의 절대 URL 이다 */
|
||||
artifacts: Record<string, string>;
|
||||
created_at: number;
|
||||
source: { url: string; goods_id: string; slug: string };
|
||||
gate: GateKey | null;
|
||||
review: GateReview | null;
|
||||
version: number;
|
||||
}
|
||||
|
||||
// ── URL 인식 ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* NOL티켓/인터파크 상품 URL 에서 goodsId 를 뽑는다. 못 뽑으면 null.
|
||||
* 입력 도중의 안내용이고, 판정은 서버가 같은 규칙으로 다시 한다.
|
||||
*/
|
||||
export function parseGoodsId(url: string): string | null {
|
||||
const s = url.trim();
|
||||
if (!s) return null;
|
||||
const m =
|
||||
// 인터파크 주소는 야놀자로 리다이렉트된다. 상품 번호는 양쪽이 같다
|
||||
s.match(/nol\.yanolja\.com\/ticket\/products\/(\d{5,})/i) ??
|
||||
s.match(/tickets\.interpark\.com\/goods\/(\d{5,})/i) ??
|
||||
s.match(/nol\.interpark\.com\/[^?]*?(\d{8,})/i) ??
|
||||
s.match(/[?&]goodsCode=(\d{5,})/i) ??
|
||||
s.match(/^(\d{8,})$/);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
// ── API ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const jsonBody = (body: unknown): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
/** 상품페이지 주소 → 잡 생성. 크레딧이 먼저 차감된다 */
|
||||
export async function createPlayreelJob(url: string): Promise<{ id: string }> {
|
||||
const { id } = await p2vFetch<{ id: number }>('/p2v/playreel/jobs', jsonBody({ url: url.trim() }));
|
||||
// 화면은 잡 id 를 localStorage 문자열로 들고 있어 경계에서 맞춘다
|
||||
return { id: String(id) };
|
||||
}
|
||||
|
||||
export const getPlayreelJob = (id: P2vJobId): Promise<PlayreelJob> =>
|
||||
p2vFetch<PlayreelJob>(`/p2v/playreel/jobs/${id}`);
|
||||
|
||||
/** 게이트 승인. gate 를 함께 보내 화면과 서버의 게이트가 어긋나면 서버가 409 로 막는다 */
|
||||
export const approvePlayreelGate = (
|
||||
id: P2vJobId, gate: GateKey, edits: GateEdits | null,
|
||||
): Promise<PlayreelJob> =>
|
||||
p2vFetch<PlayreelJob>(`/p2v/playreel/jobs/${id}/approve`, jsonBody({ gate, edits }));
|
||||
|
||||
/** 직전 게이트로 되돌린다 */
|
||||
export const backPlayreelGate = (id: P2vJobId): Promise<PlayreelJob> =>
|
||||
p2vFetch<PlayreelJob>(`/p2v/playreel/jobs/${id}/back`, { method: 'POST' });
|
||||
|
||||
/** 클립 검수 게이트에서 영상을 다시 만든다. 추가 크레딧은 차감되지 않는다 */
|
||||
export const retryPlayreelClip = (id: P2vJobId): Promise<PlayreelJob> =>
|
||||
p2vFetch<PlayreelJob>(`/p2v/playreel/jobs/${id}/retry`, { method: 'POST' });
|
||||
|
||||
export const deletePlayreelJob = (id: P2vJobId): Promise<unknown> =>
|
||||
p2vFetch(`/p2v/playreel/jobs/${id}`, { method: 'DELETE' });
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { GateKey } from './playreelApi';
|
||||
|
||||
/**
|
||||
* 롱컷 게이트 자동 승인 설정 — playreel 원본(`lib/prefs.ts`)과 같은 방식이다.
|
||||
*
|
||||
* 대상은 되돌릴 수 있는 게이트(① 수집 확인, ③ 나레이션 확인)뿐이다.
|
||||
* ②·④·⑤ 는 크레딧을 쓰거나 결과를 고정하는 비가역 단계라 항상 사람이 확인한다.
|
||||
*
|
||||
* 브라우저 localStorage 에만 저장하고 서버에는 보내지 않는다. `storageKeys.K` 에 넣지 않은 것도
|
||||
* 의도적이다 — 그쪽 키는 새 프로젝트·로그아웃 때 지워지는데, 이건 사용자의 취향이라
|
||||
* 생성할 때마다 다시 켜게 만들면 안 된다.
|
||||
*/
|
||||
export const AUTO_APPROVABLE = ['fetch_confirm', 'narration_confirm'] as const satisfies readonly GateKey[];
|
||||
export type AutoApprovable = (typeof AUTO_APPROVABLE)[number];
|
||||
export type AutoApprovePrefs = Partial<Record<AutoApprovable, boolean>>;
|
||||
|
||||
export const isAutoApprovable = (gate: GateKey | null | undefined): gate is AutoApprovable =>
|
||||
!!gate && (AUTO_APPROVABLE as readonly string[]).includes(gate);
|
||||
|
||||
const STORAGE_KEY = 'castad_playreel_auto_approve';
|
||||
const CHANGE_EVENT = 'castad:playreel-prefs';
|
||||
const EMPTY: AutoApprovePrefs = {};
|
||||
|
||||
// useSyncExternalStore 는 같은 값이면 같은 참조를 돌려줘야 한다
|
||||
let cache: { raw: string | null; value: AutoApprovePrefs } = { raw: null, value: EMPTY };
|
||||
|
||||
export function readAutoApprove(): AutoApprovePrefs {
|
||||
let raw: string | null = null;
|
||||
try {
|
||||
raw = localStorage.getItem(STORAGE_KEY);
|
||||
} catch {
|
||||
return EMPTY; // 저장소를 못 쓰면 항상 사람이 확인한다
|
||||
}
|
||||
if (raw === cache.raw) return cache.value;
|
||||
let value: AutoApprovePrefs = EMPTY;
|
||||
try {
|
||||
const parsed = raw ? JSON.parse(raw) : {};
|
||||
value = Object.fromEntries(
|
||||
AUTO_APPROVABLE.filter((gate) => parsed?.[gate] === true).map((gate) => [gate, true]),
|
||||
);
|
||||
} catch {
|
||||
/* 깨진 값은 꺼진 것으로 본다 */
|
||||
}
|
||||
cache = { raw, value };
|
||||
return value;
|
||||
}
|
||||
|
||||
export function setAutoApprove(gate: AutoApprovable, on: boolean): void {
|
||||
const next = { ...readAutoApprove() };
|
||||
if (on) next[gate] = true;
|
||||
else delete next[gate];
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* 프라이빗 모드 등 — 이 세션에서만 유지되지 않는다 */
|
||||
}
|
||||
window.dispatchEvent(new Event(CHANGE_EVENT));
|
||||
}
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
window.addEventListener(CHANGE_EVENT, onChange);
|
||||
window.addEventListener('storage', onChange); // 다른 탭에서 바꾼 경우
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE_EVENT, onChange);
|
||||
window.removeEventListener('storage', onChange);
|
||||
};
|
||||
}
|
||||
|
||||
export function useAutoApprove(): AutoApprovePrefs {
|
||||
return useSyncExternalStore(subscribe, readAutoApprove, () => EMPTY);
|
||||
}
|
||||
@@ -50,6 +50,11 @@ export const K = {
|
||||
* 로그아웃으로 지워지면 시연 중 매번 다시 물어야 한다 (utils/p2vApi.ts 참조).
|
||||
*/
|
||||
POSTER_JOB_ID: 'castad_poster_job_id',
|
||||
/**
|
||||
* 롱컷(Playreel) 진행 중 잡 id. 포스터 영상과 같은 이유로 새로고침 복구의 근거다.
|
||||
* 잡이 사라졌으면 조회가 404 로 떨어지고 GenerationFlow 가 이 키를 정리한다.
|
||||
*/
|
||||
PLAYREEL_JOB_ID: 'castad_playreel_job_id',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -67,6 +72,7 @@ export const PROJECT_KEYS: readonly string[] = [
|
||||
K.PIPELINE,
|
||||
K.SSUL_TASK_ID,
|
||||
K.POSTER_JOB_ID,
|
||||
K.PLAYREEL_JOB_ID,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user