feat(ssulbox): 썰박스 진입 탭·생성 플로우와 통합 콘텐츠 목록 분기

This commit is contained in:
skkim committed 2026-08-11 14:57:33 +09:00
1 parent c4c46db0d9
commit bb0ab91bcc
26 files changed
+2793 -119

No files matched your search

+160 -14
View File
@@ -1,3 +1,4 @@
import { clearSessionStorage } from './storageKeys';
import {
CrawlingResponse,
LyricGenerateRequest,
@@ -776,11 +777,8 @@ let refreshPromise: Promise<TokenRefreshResponse> | null = null;
function redirectToLogin() {
// 토큰 삭제
clearTokens();
// localStorage 정리
localStorage.removeItem('castad_view_mode');
localStorage.removeItem('castad_analysis_data');
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
// localStorage 정리 (생성 중이던 상태까지 전부 — 재로그인 시 잔류 방지)
clearSessionStorage();
// 홈으로 리다이렉트
window.location.href = '/';
}
@@ -928,15 +926,7 @@ export async function refreshAccessToken(): Promise<TokenRefreshResponse> {
// 로컬 스토리지 전체 정리
function clearAllLocalData() {
clearTokens();
localStorage.removeItem('castad_view_mode');
localStorage.removeItem('castad_analysis_data');
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
localStorage.removeItem('castad_song_task_id');
localStorage.removeItem('castad_image_task_id');
localStorage.removeItem('castad_song_generation');
localStorage.removeItem('castad_video_generation');
localStorage.removeItem('castad_video_ratio');
clearSessionStorage();
}
// 로그아웃
@@ -1336,3 +1326,159 @@ export async function retryUpload(uploadId: number): Promise<{ success: boolean;
if (!response.ok) throw new Error('재시도 실패');
return response.json();
}
// ============================================================================
// 썰박스 (Ssulbox)
// ============================================================================
/**
* 썰박스 장소 검색 결과.
*
* castad `/search/accommodation`(네이버 검색 API)과 달리 **`place_url` 을 준다.**
* generator 가 네이버 지도 place 페이지를 크롤링하므로 이 URL 이 반드시 필요해서
* 별도 엔드포인트를 쓴다.
*/
export interface SsulPlaceItem {
title: string;
category: string;
address: string;
roadAddress: string;
place_url: string;
}
export interface SsulCreateRequest {
scenario: string;
/** 네이버 지도 place URL 또는 업장명 */
input: string;
scenes?: number;
seconds?: number;
/**
* 검색으로 업장을 고른 경우에만 함께 보낸다.
*
* 통합 콘텐츠 목록의 업장명 표시와 `store_name`/`region` 필터가 이 값에 의존한다.
* 링크를 직접 붙여넣은 경우에는 보낼 값이 없고, 그때 업장명은 백엔드가 생성
* 로그에서 뒤늦게 채운다(주소가 없어 지역은 채우지 못한다).
*/
store_name?: string;
/** 지역 추출용(도로명). 백엔드는 이 값을 저장하지 않는다 */
road_address?: string;
/** 지역 추출용(지번). 도로명에서 시/군 추출이 실패할 때의 폴백 */
address?: string;
}
export interface SsulCreateResponse {
id: number;
status: string;
}
/**
* 업장 검색. 실패해도 빈 배열을 돌려준다 —
* 사용자는 네이버 링크를 직접 붙여넣는 우회 경로가 있으므로 흐름을 막지 않는다.
*/
export async function searchSsulPlace(query: string): Promise<SsulPlaceItem[]> {
try {
const response = await authenticatedFetch(
`${API_URL}/ssul/search/place?query=${encodeURIComponent(query)}`
);
if (!response.ok) return [];
const data = await response.json();
return data.items ?? [];
} catch {
return [];
}
}
/**
* 썰박스 생성 요청. **요청 시점에 크레딧이 선차감된다.**
* 잔액이 부족하면 402 를 던지므로 호출부가 충전 화면으로 유도해야 한다.
*/
export async function createSsulJob(
request: SsulCreateRequest
): Promise<SsulCreateResponse> {
const response = await authenticatedFetch(`${API_URL}/ssul/create`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
if (response.status === 402) {
throw new InsufficientCreditError();
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/** 크레딧 부족(402). 호출부가 충전 화면으로 유도할 수 있게 별도 타입으로 던진다 */
export class InsufficientCreditError extends Error {
constructor(message = '크레딧이 부족합니다.') {
super(message);
this.name = 'InsufficientCreditError';
}
}
export interface SsulTaskStatus {
id: number;
scenario: string;
status: 'queued' | 'running' | 'done' | 'error';
/** 0~4. 0=준비, 4=영상 합성 완료 */
step: number;
error: string | null;
video_url: string | null;
}
/** 폴링 간격. castad 의 waitForVideoComplete 와 동일하게 맞춘다 */
const SSUL_POLL_INTERVAL = 3000;
/** 생성이 수 분~십수 분 걸리므로 넉넉히 */
const SSUL_POLL_TIMEOUT = 30 * 60 * 1000;
/** 생성 잡 단건 조회 */
export async function getSsulTask(taskId: number): Promise<SsulTaskStatus> {
const response = await authenticatedFetch(`${API_URL}/ssul/tasks/${taskId}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
}
/**
* 진행 중인 내 잡 조회 (새로고침·새 탭 복구용).
* 진행 중인 것이 없으면 null.
*/
export async function getActiveSsulTask(): Promise<SsulTaskStatus | null> {
try {
const response = await authenticatedFetch(`${API_URL}/ssul/tasks/active`);
if (!response.ok) return null;
const data = await response.json();
return data.items?.[0] ?? null;
} catch {
return null;
}
}
/**
* 생성 완료까지 폴링한다. castad 의 waitForVideoComplete 와 같은 재귀 패턴.
*
* SSE 대신 폴링을 쓰는 이유는 계획서 참조 — 요약하면 EventSource 가
* `authenticatedFetch` 의 401 자동 갱신을 못 타고, 스트림이 DB 커넥션을
* 점유하며, 리버스 프록시 버퍼링에 취약하기 때문이다.
*
* @param shouldStop 매 틱마다 확인. true 면 조용히 중단한다(언마운트·로그아웃).
*/
export async function waitForSsulComplete(
taskId: number,
onProgress?: (task: SsulTaskStatus) => void,
shouldStop?: () => boolean,
startedAt: number = Date.now()
): Promise<SsulTaskStatus> {
if (shouldStop?.()) throw new Error('CANCELLED');
if (Date.now() - startedAt > SSUL_POLL_TIMEOUT) throw new Error('TIMEOUT');
const task = await getSsulTask(taskId);
onProgress?.(task);
if (task.status === 'done') return task;
if (task.status === 'error') throw new Error(task.error ?? 'SSUL_FAILED');
await new Promise((resolve) => setTimeout(resolve, SSUL_POLL_INTERVAL));
return waitForSsulComplete(taskId, onProgress, shouldStop, startedAt);
}