feat(ssulbox): 썰박스 진입 탭·생성 플로우와 통합 콘텐츠 목록 분기
This commit is contained in:
1 parent
c4c46db0d9
commit
bb0ab91bcc
26 files changed
+2793
-119
No files matched your search
+160
-14
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* localStorage 키 정의와 정리 함수.
|
||||
*
|
||||
* 이 앱에는 라우터도 전역 스토어도 없어서 localStorage 가 사실상의 상태 저장소다.
|
||||
* 그래서 "언제 무엇을 지우는가"가 흩어지면 조용히 어긋난다 — 이 모듈을 만들기 전에는
|
||||
* 정리 코드가 5곳에 있었고 지우는 키 목록이 전부 달랐다:
|
||||
*
|
||||
* App.tsx initializeOnNewSession video_complete 누락
|
||||
* GenerationFlow clearAllProjectStorage (프로젝트 키만, 의도된 범위)
|
||||
* GenerationFlow handleLogout song/video 생성 상태 누락 ← 계정 전환 시 잔류
|
||||
* api.ts redirectToLogin 위와 동일
|
||||
* api.ts clearAllLocalData video_complete 누락
|
||||
*
|
||||
* 키를 추가할 때는 아래 배열에만 넣으면 5곳에 자동 반영된다.
|
||||
*/
|
||||
|
||||
export const K = {
|
||||
// 화면 상태
|
||||
VIEW_MODE: 'castad_view_mode',
|
||||
ACTIVE_ITEM: 'castad_active_item',
|
||||
WIZARD_STEP: 'castad_wizard_step',
|
||||
|
||||
// 분석 결과
|
||||
ANALYSIS_DATA: 'castad_analysis_data',
|
||||
|
||||
// 생성 진행 상태
|
||||
SONG_TASK_ID: 'castad_song_task_id',
|
||||
IMAGE_TASK_ID: 'castad_image_task_id',
|
||||
SONG_GENERATION: 'castad_song_generation',
|
||||
VIDEO_GENERATION: 'castad_video_generation',
|
||||
VIDEO_COMPLETE: 'castad_video_complete',
|
||||
VIDEO_RATIO: 'castad_video_ratio',
|
||||
|
||||
// 썰박스 통합
|
||||
/** 현재 선택된 파이프라인 ('ado2' | 'ssul') */
|
||||
PIPELINE: 'castad_pipeline',
|
||||
/** 진행 중인 썰박스 생성 잡 ID. 권위는 서버(`/ssul/tasks/active`)이고 이건 복구 힌트다 */
|
||||
SSUL_TASK_ID: 'castad_ssul_task_id',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 하나의 프로젝트(생성 1건)에 딸린 키.
|
||||
* '새 프로젝트 만들기'로 초기화할 때 지운다. 로그인 상태와 분석 데이터는 남긴다.
|
||||
*/
|
||||
export const PROJECT_KEYS: readonly string[] = [
|
||||
K.WIZARD_STEP,
|
||||
K.SONG_TASK_ID,
|
||||
K.IMAGE_TASK_ID,
|
||||
K.SONG_GENERATION,
|
||||
K.VIDEO_GENERATION,
|
||||
K.VIDEO_COMPLETE,
|
||||
K.VIDEO_RATIO,
|
||||
K.PIPELINE,
|
||||
K.SSUL_TASK_ID,
|
||||
];
|
||||
|
||||
/**
|
||||
* 세션 전체에 걸친 키. 로그아웃·토큰 만료·새 탭 진입 시 전부 지운다.
|
||||
* PROJECT_KEYS 를 포함한다.
|
||||
*/
|
||||
export const SESSION_KEYS: readonly string[] = [
|
||||
...PROJECT_KEYS,
|
||||
K.VIEW_MODE,
|
||||
K.ACTIVE_ITEM,
|
||||
K.ANALYSIS_DATA,
|
||||
];
|
||||
|
||||
/** 진행 중인 프로젝트 상태만 정리 (로그인·분석 데이터 유지) */
|
||||
export const clearProjectStorage = (): void => {
|
||||
PROJECT_KEYS.forEach((key) => localStorage.removeItem(key));
|
||||
};
|
||||
|
||||
/** 세션 상태 전체 정리 (로그아웃·토큰 만료·새 탭) */
|
||||
export const clearSessionStorage = (): void => {
|
||||
SESSION_KEYS.forEach((key) => localStorage.removeItem(key));
|
||||
};
|
||||
Reference in new issue
Block a user