173 lines
6.7 KiB
TypeScript
Executable File
173 lines
6.7 KiB
TypeScript
Executable File
|
|
import React, { useState, useEffect } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import GenerationFlow from './pages/Dashboard/GenerationFlow';
|
|
import SocialConnectSuccess from './pages/Social/SocialConnectSuccess';
|
|
import SocialConnectError from './pages/Social/SocialConnectError';
|
|
import YouTubeOAuthCallback from './pages/Social/YouTubeOAuthCallback';
|
|
import VideoDetailPage from './components/VideoDetailPage';
|
|
import SsulDetailPage from './pages/Ssulbox/SsulDetailPage';
|
|
import { kakaoCallback, saveTokens, storeUtmFromUrl, trackViewContent, trackCompleteRegistration } from './utils/api';
|
|
import { clearSessionStorage } from './utils/storageKeys';
|
|
import { NAV } from './components/navItems';
|
|
|
|
const SESSION_KEY = 'castad_session_active';
|
|
|
|
// 새 탭/새 창에서 접근 시 localStorage 초기화 (sessionStorage로 현재 세션 확인)
|
|
const initializeOnNewSession = () => {
|
|
const isExistingSession = sessionStorage.getItem(SESSION_KEY);
|
|
|
|
if (!isExistingSession) {
|
|
// 새 세션이면 localStorage 정리하고 세션 표시
|
|
clearSessionStorage();
|
|
sessionStorage.setItem(SESSION_KEY, 'true');
|
|
}
|
|
};
|
|
|
|
// 앱 시작 시 세션 체크
|
|
initializeOnNewSession();
|
|
|
|
const App: React.FC = () => {
|
|
const { t } = useTranslation();
|
|
const [initialTab, setInitialTab] = useState<string>(NAV.HOME);
|
|
const [isProcessingCallback, setIsProcessingCallback] = useState(false);
|
|
|
|
// 카카오 로그인 콜백 처리 (URL에서 토큰 또는 code 파라미터 확인)
|
|
useEffect(() => {
|
|
// 광고 유입 UTM 파라미터 캡처 (콜백 처리로 URL이 정리되기 전에 최우선 실행)
|
|
storeUtmFromUrl();
|
|
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const accessToken = urlParams.get('access_token');
|
|
const refreshToken = urlParams.get('refresh_token');
|
|
const code = urlParams.get('code');
|
|
const currentPath = window.location.pathname;
|
|
|
|
// Social OAuth 콜백 경로는 여기서 처리하지 않음 (백엔드에서 처리)
|
|
const isSocialOAuthCallback = currentPath.includes('/social/oauth/') ||
|
|
currentPath.includes('/social/connect/');
|
|
|
|
// 백엔드에서 토큰을 URL 파라미터로 전달한 경우
|
|
if (accessToken && refreshToken && !isProcessingCallback) {
|
|
setIsProcessingCallback(true);
|
|
handleTokenCallback(accessToken, refreshToken, urlParams.get('is_new_user') === 'true');
|
|
}
|
|
// 기존 code 방식 (Redirect URI가 프론트엔드인 경우) - Social OAuth는 제외
|
|
else if (code && !isProcessingCallback && !isSocialOAuthCallback) {
|
|
setIsProcessingCallback(true);
|
|
handleKakaoCallback(code);
|
|
}
|
|
// 콜백이 아닌 일반 진입 — 광고 유입 추적
|
|
else {
|
|
trackViewContent();
|
|
}
|
|
}, []);
|
|
|
|
// 백엔드에서 토큰을 URL 파라미터로 전달받은 경우 처리
|
|
const handleTokenCallback = async (accessToken: string, refreshToken: string, isNewUser: boolean = false) => {
|
|
try {
|
|
// 토큰 저장
|
|
saveTokens(accessToken, refreshToken);
|
|
|
|
// URL에서 토큰 파라미터 제거
|
|
const url = new URL(window.location.href);
|
|
url.searchParams.delete('access_token');
|
|
url.searchParams.delete('refresh_token');
|
|
url.searchParams.delete('is_new_user');
|
|
window.history.replaceState({}, document.title, url.pathname);
|
|
|
|
// 신규 가입이면 Meta CompleteRegistration 전환 이벤트 발화
|
|
// (서버가 계정당 최초 1회 판정 + UTM 저장, 실패해도 로그인 흐름에 영향 없음)
|
|
if (isNewUser) {
|
|
await trackCompleteRegistration();
|
|
}
|
|
|
|
// 로그인 전 특정 화면(예: /video/{id})에서 유도된 로그인이면 그 경로로 복귀
|
|
const redirectPath = sessionStorage.getItem('castad_login_redirect');
|
|
sessionStorage.removeItem('castad_login_redirect');
|
|
if (redirectPath && redirectPath !== '/') {
|
|
window.location.href = redirectPath;
|
|
return;
|
|
}
|
|
// 그 외(사이드바 게이트 등)는 GenerationFlow 가 castad_login_next_item 으로 자체 복귀 처리
|
|
setInitialTab(NAV.HOME);
|
|
} catch (err) {
|
|
console.error('Token callback failed:', err);
|
|
alert(t('app.loginFailed'));
|
|
} finally {
|
|
setIsProcessingCallback(false);
|
|
}
|
|
};
|
|
|
|
const handleKakaoCallback = async (code: string) => {
|
|
try {
|
|
const response = await kakaoCallback(code);
|
|
|
|
// 신규 가입이면 Meta CompleteRegistration 전환 이벤트 발화
|
|
// (페이지 이동 전에 완료해야 요청이 유실되지 않음)
|
|
if (response.is_new_user) {
|
|
await trackCompleteRegistration();
|
|
}
|
|
|
|
// 로그인 성공 - 서버에서 받은 redirect_url로 이동
|
|
window.location.href = response.redirect_url;
|
|
} catch (err) {
|
|
console.error('Kakao callback failed:', err);
|
|
alert(t('app.kakaoLoginFailed'));
|
|
|
|
// URL에서 code 파라미터 제거
|
|
const url = new URL(window.location.href);
|
|
url.searchParams.delete('code');
|
|
window.history.replaceState({}, document.title, url.pathname);
|
|
} finally {
|
|
setIsProcessingCallback(false);
|
|
}
|
|
};
|
|
|
|
// Social OAuth 콜백 페이지 처리
|
|
const pathname = window.location.pathname;
|
|
|
|
// YouTube OAuth 콜백 처리 (Google에서 리다이렉트)
|
|
if (pathname === '/social/oauth/youtube/callback') {
|
|
return <YouTubeOAuthCallback />;
|
|
}
|
|
|
|
if (pathname === '/social/connect/success') {
|
|
return <SocialConnectSuccess />;
|
|
}
|
|
|
|
if (pathname === '/social/connect/error') {
|
|
return <SocialConnectError />;
|
|
}
|
|
|
|
// 영상 상세 페이지 (/video/{id}) — 인증 게이트는 VideoDetailPage 내부에서 처리
|
|
const videoDetailMatch = pathname.match(/^\/video\/([^/]+)$/);
|
|
if (videoDetailMatch) {
|
|
return <VideoDetailPage videoId={videoDetailMatch[1]} />;
|
|
}
|
|
|
|
// 썰박스 공유 페이지 (/ssul/{id}) — 위와 동일한 패턴, 비로그인 열람 가능.
|
|
// /video/{id} 와 경로를 나눈 이유: video.id 와 ssul_content.id 가 독립 시퀀스라
|
|
// 값이 겹치므로, 한 경로로 합치면 다른 종류의 콘텐츠가 열린다.
|
|
const ssulDetailMatch = pathname.match(/^\/ssul\/(\d+)$/);
|
|
if (ssulDetailMatch) {
|
|
return <SsulDetailPage contentId={ssulDetailMatch[1]} />;
|
|
}
|
|
|
|
// 카카오 콜백 처리 중 로딩 화면 표시
|
|
if (isProcessingCallback) {
|
|
return (
|
|
<div className="login-container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
|
<div style={{ textAlign: 'center', color: '#fff' }}>
|
|
<p style={{ fontSize: '18px' }}>{t('app.loginProcessing')}</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// 그 외 전 경로는 ADO2 콘텐츠 갤러리를 첫 화면으로 하는 GenerationFlow 로 수렴
|
|
return <GenerationFlow initialActiveItem={initialTab} />;
|
|
};
|
|
|
|
export default App;
|