Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cdb47ec2e | ||
|
|
23938871b0 | ||
|
|
c4c46db0d9 | ||
|
|
f19cba7d75 | ||
|
|
f36fd5a3cb |
No files matched your search
+18
@@ -15,6 +15,20 @@
|
||||
<meta property="og:type" content="website" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon_32.svg" sizes="32x32">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon_48.svg" sizes="48x48">
|
||||
<!-- Meta Pixel Code -->
|
||||
<script>
|
||||
!function(f,b,e,v,n,t,s)
|
||||
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
|
||||
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
|
||||
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
|
||||
n.queue=[];t=b.createElement(e);t.async=!0;
|
||||
t.src=v;s=b.getElementsByTagName(e)[0];
|
||||
s.parentNode.insertBefore(t,s)}(window, document,'script',
|
||||
'https://connect.facebook.net/en_US/fbevents.js');
|
||||
fbq('init', '1572679738203392');
|
||||
fbq('track', 'PageView');
|
||||
</script>
|
||||
<!-- End Meta Pixel Code -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
@@ -164,6 +178,10 @@
|
||||
</script>
|
||||
</head>
|
||||
<body class="bg-[#121a1d]">
|
||||
<!-- Meta Pixel noscript fallback (head의 noscript에는 img가 허용되지 않아 body에 위치) -->
|
||||
<noscript><img height="1" width="1" style="display:none"
|
||||
src="https://www.facebook.com/tr?id=1572679738203392&ev=PageView&noscript=1"
|
||||
/></noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
</body>
|
||||
|
||||
+23
-3
@@ -14,7 +14,7 @@ import SocialConnectError from './pages/Social/SocialConnectError';
|
||||
import YouTubeOAuthCallback from './pages/Social/YouTubeOAuthCallback';
|
||||
import ADO2ContentsPage from './pages/Dashboard/ADO2ContentsPage';
|
||||
import VideoDetailPage from './components/VideoDetailPage';
|
||||
import { crawlUrl, autocomplete, marketingAnalysis, kakaoCallback, isLoggedIn, saveTokens, getVideosList, AutocompleteRequest } from './utils/api';
|
||||
import { crawlUrl, autocomplete, marketingAnalysis, kakaoCallback, isLoggedIn, saveTokens, getVideosList, AutocompleteRequest, storeUtmFromUrl, trackViewContent, trackCompleteRegistration } from './utils/api';
|
||||
import { saveSearchHistory } from './components/SearchHistory/useSearchHistory';
|
||||
import { CrawlingResponse } from './types/api';
|
||||
|
||||
@@ -123,6 +123,9 @@ const App: React.FC = () => {
|
||||
|
||||
// 카카오 로그인 콜백 처리 (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');
|
||||
@@ -136,17 +139,21 @@ const App: React.FC = () => {
|
||||
// 백엔드에서 토큰을 URL 파라미터로 전달한 경우
|
||||
if (accessToken && refreshToken && !isProcessingCallback) {
|
||||
setIsProcessingCallback(true);
|
||||
handleTokenCallback(accessToken, refreshToken);
|
||||
handleTokenCallback(accessToken, refreshToken, urlParams.get('is_new_user') === 'true');
|
||||
}
|
||||
// 기존 code 방식 (Redirect URI가 프론트엔드인 경우) - Social OAuth는 제외
|
||||
else if (code && !isProcessingCallback && !isSocialOAuthCallback) {
|
||||
setIsProcessingCallback(true);
|
||||
handleKakaoCallback(code);
|
||||
}
|
||||
// 콜백이 아닌 일반 진입이고 랜딩이 첫 화면이면 ViewContent 발화
|
||||
else if (viewMode === 'landing') {
|
||||
trackViewContent();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 백엔드에서 토큰을 URL 파라미터로 전달받은 경우 처리
|
||||
const handleTokenCallback = (accessToken: string, refreshToken: string) => {
|
||||
const handleTokenCallback = async (accessToken: string, refreshToken: string, isNewUser: boolean = false) => {
|
||||
try {
|
||||
// 토큰 저장
|
||||
saveTokens(accessToken, refreshToken);
|
||||
@@ -155,8 +162,15 @@ const App: React.FC = () => {
|
||||
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();
|
||||
}
|
||||
|
||||
const savedData = localStorage.getItem(ANALYSIS_DATA_KEY);
|
||||
if (savedData) {
|
||||
// 분석 데이터가 있으면 에셋 관리(step 1)부터 시작
|
||||
@@ -184,6 +198,12 @@ const App: React.FC = () => {
|
||||
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) {
|
||||
|
||||
+9
-3
@@ -260,15 +260,21 @@
|
||||
"selectedImages": "Selected Images",
|
||||
"imageAlt": "Image",
|
||||
"uploadBadge": "Uploaded",
|
||||
"previewUnavailable": "No preview",
|
||||
"imageUpload": "Image Upload",
|
||||
"dragAndDrop": "Drag & drop or\nclick to upload",
|
||||
"videoRatio": "Video Ratio",
|
||||
"minImages": "Min. 5 images",
|
||||
"minImages": "Recommended 30+ images",
|
||||
"youtubeShorts": "YouTube Shorts",
|
||||
"youtubeVideo": "YouTube Video",
|
||||
"back": "Go Back",
|
||||
"loadMore": "Load more",
|
||||
"uploadFailed": "Image upload failed.",
|
||||
"uploadErrorTitle": "Image Upload Error",
|
||||
"uploadErrorConfirm": "OK",
|
||||
"duplicateSkippedTitle": "Duplicate Images Skipped",
|
||||
"duplicateSkippedMessage": "Skipped {{count}} image(s) that were already added.",
|
||||
"preparingPreviews": "Preparing previews ({{done}} / {{total}})",
|
||||
"uploading": "Uploading... (30 sec – 1 min)",
|
||||
"nextStep": "Next Step"
|
||||
},
|
||||
@@ -463,8 +469,8 @@
|
||||
"monthOverMonth": "Month-over-Month Growth",
|
||||
"noAudienceData": "Not enough data to show real audience insights.",
|
||||
"mockContentNotice": "The content shown below is sample data, not your actual content.",
|
||||
"dataDelayTitle": "Data is being prepared",
|
||||
"dataDelayDesc": "According to YouTube's policy, analytics data may take up to 48 hours to be reflected after a video is uploaded. Please check back later.",
|
||||
"dataDelayTitle": "No data to display",
|
||||
"dataDelayDesc": "There is no analytics data to display. YouTube may take up to 48 hours to reflect data after upload, and statistics are also not collected if the video was uploaded as private or has been deleted from YouTube.",
|
||||
"sampleHide": "Hide Sample",
|
||||
"sampleShow": "Show Sample",
|
||||
"recentVideosDesc": "Showing stats for the latest 30 videos uploaded via ADO2.",
|
||||
|
||||
+9
-3
@@ -259,15 +259,21 @@
|
||||
"selectedImages": "선택된 이미지",
|
||||
"imageAlt": "이미지",
|
||||
"uploadBadge": "업로드",
|
||||
"previewUnavailable": "미리보기 없음",
|
||||
"imageUpload": "이미지 업로드",
|
||||
"dragAndDrop": "이미지를 끌어다 놓거나\n클릭하여 업로드",
|
||||
"videoRatio": "영상 비율",
|
||||
"minImages": "최소 5장",
|
||||
"minImages": "권장 30장 이상",
|
||||
"youtubeShorts": "유튜브 쇼츠",
|
||||
"youtubeVideo": "유튜브 일반",
|
||||
"back": "뒤로가기",
|
||||
"loadMore": "더보기",
|
||||
"uploadFailed": "이미지 업로드에 실패했습니다.",
|
||||
"uploadErrorTitle": "이미지 업로드 초과",
|
||||
"uploadErrorConfirm": "확인",
|
||||
"duplicateSkippedTitle": "중복 이미지 제외",
|
||||
"duplicateSkippedMessage": "이미 추가된 이미지 {{count}}장을 제외했습니다.",
|
||||
"preparingPreviews": "미리보기 준비 중 ({{done}} / {{total}})",
|
||||
"uploading": "업로드 중 (30~60초 소요)",
|
||||
"nextStep": "다음 단계"
|
||||
},
|
||||
@@ -462,8 +468,8 @@
|
||||
"monthOverMonth": "전월 대비 성장",
|
||||
"noAudienceData": "누적 데이터가 부족하여 실제 시청자 정보가 없습니다.",
|
||||
"mockContentNotice": "현재 표시된 콘텐츠는 실제 데이터가 아닌 샘플 데이터입니다.",
|
||||
"dataDelayTitle": "데이터 준비 중",
|
||||
"dataDelayDesc": "유튜브 정책에 따라 분석 데이터는 영상 업로드 후 최대 48시간이 지나야 반영됩니다. 나중에 다시 확인해 주세요.",
|
||||
"dataDelayTitle": "표시할 데이터 없음",
|
||||
"dataDelayDesc": "표시할 분석 데이터가 없습니다. 유튜브 정책상 업로드 후 최대 48시간이 지나야 데이터가 반영되며, 영상을 비공개로 업로드했거나 유튜브에서 삭제한 경우에도 통계가 집계되지 않습니다.",
|
||||
"sampleHide": "Sample 숨기기",
|
||||
"sampleShow": "Sample 보기",
|
||||
"recentVideosDesc": "ADO2에서 업로드한 최근 30개의 영상 통계가 표시됩니다.",
|
||||
|
||||
@@ -3,13 +3,19 @@ import React, { useRef, useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ImageItem, ImageUrlItem } from '../../types/api';
|
||||
import { uploadImages } from '../../utils/api';
|
||||
import { isImageInputFile } from '../../utils/imageCompression.ts';
|
||||
import { MAX_IMAGES_PER_UPLOAD_TASK } from '../../utils/imageUpload.ts';
|
||||
import { splitDuplicateFiles } from '../../utils/imageDedup.ts';
|
||||
|
||||
interface AssetManagementContentProps {
|
||||
onNext: (imageTaskId: string) => void;
|
||||
onBack?: () => void;
|
||||
imageList: ImageItem[];
|
||||
onRemoveImage: (index: number) => void;
|
||||
onAddImages: (files: File[]) => void;
|
||||
onAddImages: (
|
||||
files: File[],
|
||||
onProgress: (done: number, total: number) => void
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
type VideoRatio = 'vertical' | 'horizontal';
|
||||
@@ -27,9 +33,11 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
// 업로드 실패와 중복 제외 안내가 같은 다이얼로그 마크업을 공유한다.
|
||||
const [dialog, setDialog] = useState<{ title: string; message: string } | null>(null);
|
||||
const [videoRatio, setVideoRatio] = useState<VideoRatio>('vertical');
|
||||
const [displayCount, setDisplayCount] = useState(IMAGES_PER_PAGE);
|
||||
const [thumbnailProgress, setThumbnailProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const savedRatio = localStorage.getItem('castad_video_ratio') as VideoRatio;
|
||||
@@ -38,12 +46,26 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!dialog) return;
|
||||
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
setDialog(null);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleEscape);
|
||||
return () => window.removeEventListener('keydown', handleEscape);
|
||||
}, [dialog]);
|
||||
|
||||
const handleVideoRatioChange = (ratio: VideoRatio) => {
|
||||
setVideoRatio(ratio);
|
||||
localStorage.setItem('castad_video_ratio', ratio);
|
||||
};
|
||||
|
||||
const getImageSrc = (item: ImageItem): string => {
|
||||
const getImageSrc = (item: ImageItem): string | null => {
|
||||
return item.type === 'url' ? item.preview_url : item.preview;
|
||||
};
|
||||
|
||||
@@ -52,7 +74,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
setIsUploading(true);
|
||||
setUploadProgress(0);
|
||||
setUploadError(null);
|
||||
setDialog(null);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
@@ -85,13 +107,37 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
} catch (error) {
|
||||
clearInterval(interval);
|
||||
console.error('Image upload failed:', error);
|
||||
setUploadError(error instanceof Error ? error.message : t('assetManagement.uploadFailed'));
|
||||
setDialog({
|
||||
title: t('assetManagement.uploadErrorTitle'),
|
||||
message: error instanceof Error ? error.message : t('assetManagement.uploadFailed'),
|
||||
});
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
setUploadProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
const runAddImages = async (files: File[]) => {
|
||||
const { newFiles, duplicateCount } = splitDuplicateFiles(imageList, files);
|
||||
|
||||
if (newFiles.length > 0) {
|
||||
setThumbnailProgress({ done: 0, total: newFiles.length });
|
||||
try {
|
||||
await onAddImages(newFiles, (done, total) => setThumbnailProgress({ done, total }));
|
||||
} finally {
|
||||
setThumbnailProgress(null);
|
||||
}
|
||||
}
|
||||
|
||||
// 썸네일 생성 오버레이에 가려지지 않도록 작업이 끝난 뒤에 안내한다.
|
||||
if (duplicateCount > 0) {
|
||||
setDialog({
|
||||
title: t('assetManagement.duplicateSkippedTitle'),
|
||||
message: t('assetManagement.duplicateSkippedMessage', { count: duplicateCount }),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -100,10 +146,8 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const files = Array.from(e.dataTransfer.files).filter((file: File) =>
|
||||
file.type.startsWith('image/')
|
||||
);
|
||||
if (files.length > 0) onAddImages(files);
|
||||
const files = Array.from(e.dataTransfer.files).filter(isImageInputFile);
|
||||
if (files.length > 0) void runAddImages(files);
|
||||
};
|
||||
|
||||
const handleFileSelect = () => {
|
||||
@@ -113,7 +157,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
onAddImages(Array.from(files));
|
||||
void runAddImages(Array.from(files));
|
||||
e.target.value = '';
|
||||
}
|
||||
};
|
||||
@@ -123,6 +167,25 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
return (
|
||||
<main className="asset-page">
|
||||
{thumbnailProgress && (
|
||||
<div className="asset-upload-overlay">
|
||||
<div className="asset-upload-overlay-content">
|
||||
<div className="loading-spinner">
|
||||
<div className="loading-ring"></div>
|
||||
<div className="loading-dot">
|
||||
<div className="loading-dot-inner"></div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="comp2-loading-text">
|
||||
{t('assetManagement.preparingPreviews', {
|
||||
done: thumbnailProgress.done,
|
||||
total: thumbnailProgress.total,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isUploading && (
|
||||
<div className="asset-upload-overlay">
|
||||
<div className="asset-upload-overlay-content">
|
||||
@@ -146,6 +209,37 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dialog && (
|
||||
<div
|
||||
className="asset-upload-error-overlay"
|
||||
onClick={() => setDialog(null)}
|
||||
>
|
||||
<div
|
||||
className="asset-upload-error-dialog"
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="asset-upload-error-title"
|
||||
aria-describedby="asset-upload-error-message"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<h2 id="asset-upload-error-title" className="asset-upload-error-title">
|
||||
{dialog.title}
|
||||
</h2>
|
||||
<p id="asset-upload-error-message" className="asset-upload-error-message">
|
||||
{dialog.message}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="asset-upload-error-confirm"
|
||||
onClick={() => setDialog(null)}
|
||||
autoFocus
|
||||
>
|
||||
{t('assetManagement.uploadErrorConfirm')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fixed Header - 뒤로가기 버튼 */}
|
||||
<div className="asset-sticky-header">
|
||||
{onBack && (
|
||||
@@ -169,6 +263,13 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<div className="asset-section-header-left">
|
||||
<h3 className="asset-section-title">{t('assetManagement.selectedImages')}</h3>
|
||||
<span className="asset-section-subtitle">{t('assetManagement.minImages')}</span>
|
||||
<span
|
||||
className={`asset-section-count${
|
||||
imageList.length > MAX_IMAGES_PER_UPLOAD_TASK ? ' asset-section-count-over' : ''
|
||||
}`}
|
||||
>
|
||||
{imageList.length} / {MAX_IMAGES_PER_UPLOAD_TASK}
|
||||
</span>
|
||||
</div>
|
||||
<button onClick={handleFileSelect} className="asset-mobile-upload-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
|
||||
@@ -182,27 +283,46 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<div className="asset-image-list">
|
||||
{visibleImages.length > 0 && (
|
||||
<div className="asset-image-grid">
|
||||
{visibleImages.map((item, i) => (
|
||||
<div key={i} className="asset-image-item">
|
||||
<img
|
||||
src={getImageSrc(item)}
|
||||
alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
{item.type === 'file' && (
|
||||
<div className="asset-image-badge">{t('assetManagement.uploadBadge')}</div>
|
||||
)}
|
||||
<button
|
||||
onClick={() => onRemoveImage(i)}
|
||||
className="asset-image-remove"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{visibleImages.map((item, i) => {
|
||||
const src = getImageSrc(item);
|
||||
const fileName = item.type === 'file' ? item.file.name : '';
|
||||
return (
|
||||
<div key={i} className="asset-image-item">
|
||||
{src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
|
||||
referrerPolicy="no-referrer"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
) : (
|
||||
<div className="asset-image-placeholder" title={fileName}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2"/>
|
||||
<circle cx="8.5" cy="8.5" r="1.5"/>
|
||||
<path d="M21 15l-5-5L5 21"/>
|
||||
</svg>
|
||||
<span className="asset-image-placeholder-name">
|
||||
{fileName || t('assetManagement.previewUnavailable')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{item.type === 'file' && (
|
||||
<div className="asset-image-badge">{t('assetManagement.uploadBadge')}</div>
|
||||
)}
|
||||
<button
|
||||
onClick={() => onRemoveImage(i)}
|
||||
className="asset-image-remove"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
||||
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -268,9 +388,6 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
{/* Fixed Footer - 다음 단계 버튼 */}
|
||||
<div className="asset-sticky-footer">
|
||||
{uploadError && (
|
||||
<p className="text-red-500 text-sm mb-2">{uploadError}</p>
|
||||
)}
|
||||
<button
|
||||
onClick={handleNextWithUpload}
|
||||
disabled={imageList.length === 0 || isUploading}
|
||||
@@ -283,7 +400,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="image/*,.heic,.heif"
|
||||
multiple
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { generateVideo, waitForVideoComplete, getSubtitleStatus, waitForSubtitleComplete } from '../../utils/api';
|
||||
import { generateVideo, waitForVideoComplete, getSubtitleStatus, waitForSubtitleComplete, trackFirstVideoCreated } from '../../utils/api';
|
||||
import SocialPostingModal from '../../components/SocialPostingModal';
|
||||
import { useTutorial } from '../../components/Tutorial/useTutorial';
|
||||
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
|
||||
@@ -266,6 +266,9 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
|
||||
setVideoStatus('complete');
|
||||
setStatusMessage('');
|
||||
saveToStorage(videoTaskId, currentSongTaskId, 'complete', videoUrlFromResponse, videoId);
|
||||
|
||||
// Meta FirstVideoCreated 전환 이벤트 발화 (서버가 계정당 최초 1회 판정, 실패해도 무시)
|
||||
trackFirstVideoCreated();
|
||||
} else {
|
||||
throw new Error(t('completion.videoUrlMissing'));
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { useTutorial } from '../../components/Tutorial/useTutorial';
|
||||
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
|
||||
import TutorialOverlay, { TutorialRestartPopup } from '../../components/Tutorial/TutorialOverlay';
|
||||
import WizardStepper from '../../components/WizardStepper';
|
||||
import { createPreviewThumbnail } from '../../utils/imageCompression.ts';
|
||||
|
||||
const WIZARD_STEP_KEY = 'castad_wizard_step';
|
||||
const ACTIVE_ITEM_KEY = 'castad_active_item';
|
||||
@@ -28,6 +29,15 @@ const IMAGE_TASK_ID_KEY = 'castad_image_task_id';
|
||||
const ANALYSIS_DATA_KEY = 'castad_analysis_data';
|
||||
import { saveSearchHistory } from '../../components/SearchHistory/useSearchHistory';
|
||||
|
||||
/** 파일 이미지의 썸네일 objectURL 을 일괄 해제한다. preview 가 null 인 항목은 건너뛴다. */
|
||||
const revokeAllPreviews = (items: ImageItem[]) => {
|
||||
items.forEach(item => {
|
||||
if (item.type === 'file' && item.preview) {
|
||||
URL.revokeObjectURL(item.preview);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 다른 컴포넌트에서 사용하는 storage key들 (초기화용)
|
||||
const SONG_GENERATION_KEY = 'castad_song_generation';
|
||||
const VIDEO_GENERATION_KEY = 'castad_video_generation';
|
||||
@@ -175,6 +185,15 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
};
|
||||
|
||||
const [imageList, setImageList] = useState<ImageItem[]>(getInitialImageList());
|
||||
const imageListRef = useRef<ImageItem[]>(imageList);
|
||||
imageListRef.current = imageList;
|
||||
|
||||
// 의존성 배열에 imageList 를 넣으면 이미지를 추가할 때마다 cleanup 이 돌아
|
||||
// 방금 만든 썸네일이 즉시 revoke 된다. 반드시 빈 배열이어야 한다.
|
||||
useEffect(() => {
|
||||
return () => revokeAllPreviews(imageListRef.current);
|
||||
}, []);
|
||||
|
||||
const prevAnalysisMIdRef = useRef<number | null | undefined>(analysisData?.m_id);
|
||||
|
||||
// analysisData 변경 시 m_id가 바뀐 경우(새로운 분석)에만 imageList 업데이트
|
||||
@@ -183,6 +202,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
console.log('[GenerationFlow] analysisData updated, m_id:', analysisData?.m_id);
|
||||
if (analysisData?.image_list && analysisData.image_list.length > 0) {
|
||||
if (prevAnalysisMIdRef.current !== analysisData.m_id) {
|
||||
// 목록을 통째로 교체하므로 기존 파일 썸네일을 먼저 해제한다.
|
||||
revokeAllPreviews(imageListRef.current);
|
||||
setImageList(analysisData.image_list.map(item => ({ type: 'url' as const, url: item.original, preview_url: item.preview })));
|
||||
}
|
||||
}
|
||||
@@ -192,21 +213,35 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
const handleRemoveImage = (index: number) => {
|
||||
setImageList(prev => {
|
||||
const item = prev[index];
|
||||
// 파일 이미지인 경우 메모리 해제
|
||||
if (item.type === 'file') {
|
||||
// 파일 이미지인 경우 썸네일 메모리 해제 (생성 실패 시 preview 는 null)
|
||||
if (item.type === 'file' && item.preview) {
|
||||
URL.revokeObjectURL(item.preview);
|
||||
}
|
||||
return prev.filter((_, i) => i !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddImages = (files: File[]) => {
|
||||
const newImages: ImageItem[] = files.map(file => ({
|
||||
type: 'file',
|
||||
file,
|
||||
preview: URL.createObjectURL(file),
|
||||
}));
|
||||
// 새로 업로드된 이미지를 배열 앞에 추가 (최신 이미지가 상단에 표시)
|
||||
const handleAddImages = async (
|
||||
files: File[],
|
||||
onProgress: (done: number, total: number) => void
|
||||
) => {
|
||||
const total = files.length;
|
||||
const newImages: ImageItem[] = [];
|
||||
|
||||
onProgress(0, total);
|
||||
|
||||
// 반드시 순차 처리한다. Promise.all 로 동시에 돌리면 원본 크기 비트맵이
|
||||
// 한꺼번에 메모리에 올라가, 이 작업이 없애려던 문제가 그대로 재현된다.
|
||||
for (const file of files) {
|
||||
const preview = await createPreviewThumbnail(file);
|
||||
newImages.push({ type: 'file', file, preview });
|
||||
onProgress(newImages.length, total);
|
||||
// 진행률이 실제로 화면에 그려지도록 매 장마다 렌더링 기회를 넘긴다.
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
// 장마다 setState 하면 그리드가 N 번 재조정된다. 전부 끝난 뒤 한 번만 반영한다.
|
||||
// 새로 추가된 이미지를 배열 앞에 둔다 (최신 이미지가 상단에 표시)
|
||||
setImageList(prev => [...newImages, ...prev]);
|
||||
};
|
||||
|
||||
@@ -218,6 +253,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
setSongTaskId(null);
|
||||
setImageTaskId(null);
|
||||
setAnalysisData(null);
|
||||
revokeAllPreviews(imageListRef.current);
|
||||
setImageList([]);
|
||||
onHome();
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { getKakaoLoginUrl, kakaoCallback } from '../../utils/api';
|
||||
import { getKakaoLoginUrl, kakaoCallback, trackCompleteRegistration } from '../../utils/api';
|
||||
|
||||
interface LoginSectionProps {
|
||||
onBack: () => void;
|
||||
@@ -28,7 +28,13 @@ const LoginSection: React.FC<LoginSectionProps> = ({ onBack, onLogin }) => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await kakaoCallback(code);
|
||||
const response = await kakaoCallback(code);
|
||||
|
||||
// 신규 가입이면 Meta CompleteRegistration 전환 이벤트 발화
|
||||
// (서버가 계정당 최초 1회 판정 — App.tsx 경로와 중복 호출돼도 무해)
|
||||
if (response.is_new_user) {
|
||||
await trackCompleteRegistration();
|
||||
}
|
||||
|
||||
// URL에서 code 파라미터 제거
|
||||
const url = new URL(window.location.href);
|
||||
|
||||
@@ -689,10 +689,6 @@
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.video-detail-header {
|
||||
/* margin-bottom: 24px; */
|
||||
}
|
||||
|
||||
.video-detail-back-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -832,6 +832,72 @@
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
/* Upload Error Dialog */
|
||||
.asset-upload-error-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
background: rgba(0, 17, 18, 0.82);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.asset-upload-error-dialog {
|
||||
width: min(100%, 420px);
|
||||
padding: 1.5rem;
|
||||
background: #01393B;
|
||||
border: 1px solid #379599;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.asset-upload-error-title {
|
||||
margin: 0;
|
||||
color: #94FBE0;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.asset-upload-error-message {
|
||||
margin: 0.75rem 0 1.5rem;
|
||||
color: #E5F1F2;
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
padding: 0.75rem 1rem;
|
||||
color: #002224;
|
||||
background: #94FBE0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s, transform 0.2s;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:hover {
|
||||
background: #B8FFE9;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:focus-visible {
|
||||
outline: 3px solid #CFABFB;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
|
||||
/* Fixed Header - 뒤로가기 */
|
||||
.asset-sticky-header {
|
||||
@@ -1032,6 +1098,20 @@
|
||||
letter-spacing: -0.006em;
|
||||
}
|
||||
|
||||
.asset-section-count {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: #9BCACC;
|
||||
line-height: 1.19;
|
||||
letter-spacing: -0.006em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 업로드 상한(100장)을 넘긴 상태. 추가 자체는 막지 않고 시각적으로만 경고한다. */
|
||||
.asset-section-count-over {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
/* Asset Section Title */
|
||||
.asset-section-title {
|
||||
font-size: 1.5rem;
|
||||
@@ -1134,6 +1214,30 @@
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.asset-image-placeholder {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
background-color: #001416;
|
||||
color: #379599;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.asset-image-placeholder-name {
|
||||
width: 100%;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.2;
|
||||
color: #9BCACC;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-image-badge {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
|
||||
+4
-13
@@ -61,8 +61,8 @@ export interface UrlImage {
|
||||
// 업로드된 파일 이미지
|
||||
export interface FileImage {
|
||||
type: 'file';
|
||||
file: File;
|
||||
preview: string; // createObjectURL로 생성된 미리보기 URL
|
||||
file: File; // 업로드용 원본. 썸네일로 대체하지 않는다.
|
||||
preview: string | null; // 미리보기용 축소 썸네일 objectURL. 생성 실패 시 null.
|
||||
}
|
||||
|
||||
export type ImageItem = UrlImage | FileImage;
|
||||
@@ -233,22 +233,13 @@ export interface KakaoLoginUrlResponse {
|
||||
auth_url: string;
|
||||
}
|
||||
|
||||
// 카카오 콜백 사용자 정보
|
||||
export interface KakaoCallbackUser {
|
||||
id: number;
|
||||
nickname: string;
|
||||
email: string | null;
|
||||
profile_image_url: string | null;
|
||||
is_new_user: boolean;
|
||||
}
|
||||
|
||||
// 카카오 콜백 응답 (JWT 토큰)
|
||||
// 카카오 콜백 응답 (JWT 토큰) — 백엔드 LoginResponse와 동일 구조
|
||||
export interface KakaoCallbackResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
user: KakaoCallbackUser;
|
||||
is_new_user: boolean;
|
||||
redirect_url: string;
|
||||
}
|
||||
|
||||
|
||||
+203
-21
@@ -35,6 +35,7 @@ import {
|
||||
CommentItem,
|
||||
LikeToggleResponse,
|
||||
} from '../types/api';
|
||||
import { uploadImagesSequentially } from './imageUpload.ts';
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
|
||||
console.log('[API] API_URL:', API_URL);
|
||||
@@ -309,6 +310,183 @@ export async function generateVideo(taskId: string, orientation: 'vertical' | 'h
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Meta 전환 추적
|
||||
// ============================================================
|
||||
|
||||
// Meta 픽셀이 심는 1st-party 쿠키 값 읽기 (_fbc/_fbp)
|
||||
function getCookieValue(name: string): string | null {
|
||||
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
// URL의 fbclid로 조립해둔 fbc 폴백 값을 보관하는 localStorage 키
|
||||
// UTM과 분리해 두어야 가입 완료 후 UTM을 정리해도 이후 이벤트에서 계속 쓸 수 있다.
|
||||
const FBC_STORAGE_KEY = 'castad_fbc';
|
||||
|
||||
// Meta 클릭 ID(fbc) 조회
|
||||
// 픽셀이 심은 _fbc 쿠키를 우선 사용하고, 없으면 랜딩 시 fbclid로 조립해둔 값을 쓴다.
|
||||
// 애드블로커·쿠키 정리 등으로 쿠키가 유실돼도 광고 클릭 기여를 잃지 않기 위한 폴백이다.
|
||||
function getFbc(): string | null {
|
||||
const cookie = getCookieValue('_fbc');
|
||||
if (cookie) return cookie;
|
||||
|
||||
try {
|
||||
return localStorage.getItem(FBC_STORAGE_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 첫 영상 생성 완료(FirstVideoCreated) 전환 이벤트 발화 API
|
||||
// 서버가 first_video_created_at null 여부로 계정당 최초 1회를 판정하고,
|
||||
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
|
||||
export async function trackFirstVideoCreated(): Promise<void> {
|
||||
try {
|
||||
const response = await authenticatedFetch(`${API_URL}/tracking/meta/first-video-created`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
fbc: getFbc(),
|
||||
fbp: getCookieValue('_fbp'),
|
||||
event_source_url: window.location.href,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) return;
|
||||
|
||||
const data: { fired: boolean; event_id: string | null } = await response.json();
|
||||
|
||||
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
|
||||
if (data.fired && data.event_id && typeof fbq === 'function') {
|
||||
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
|
||||
fbq('trackCustom', 'FirstVideoCreated', {}, { eventID: data.event_id });
|
||||
}
|
||||
} catch (error) {
|
||||
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
|
||||
console.error('[Tracking] FirstVideoCreated failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// UTM 파라미터 localStorage 키 (first-touch 보존)
|
||||
const UTM_STORAGE_KEY = 'castad_utm';
|
||||
const UTM_PARAM_NAMES = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const;
|
||||
|
||||
// 이벤트 중복제거용 UUID 생성
|
||||
// crypto.randomUUID는 보안 컨텍스트(https/localhost) 전용이라 미지원 환경 폴백 포함
|
||||
function generateEventId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = (Math.random() * 16) | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
// fbq 전역 함수 안전 접근
|
||||
function getFbq(): ((...args: unknown[]) => void) | null {
|
||||
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
|
||||
return typeof fbq === 'function' ? fbq : null;
|
||||
}
|
||||
|
||||
// 랜딩 진입 URL에서 광고 유입 정보(UTM, fbclid)를 localStorage에 보관한다.
|
||||
export function storeUtmFromUrl(): void {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
|
||||
// UTM: 이미 저장된 값이 있으면 덮어쓰지 않아 최초 유입 경로(first-touch)를 보존
|
||||
if (!localStorage.getItem(UTM_STORAGE_KEY)) {
|
||||
const utm: Record<string, string> = {};
|
||||
for (const name of UTM_PARAM_NAMES) {
|
||||
const value = params.get(name);
|
||||
if (value) utm[name] = value;
|
||||
}
|
||||
|
||||
if (Object.keys(utm).length > 0) {
|
||||
localStorage.setItem(UTM_STORAGE_KEY, JSON.stringify(utm));
|
||||
}
|
||||
}
|
||||
|
||||
// fbclid: 광고 클릭 기여는 최신 클릭이 가져가므로 새 값이 오면 덮어쓴다
|
||||
// (Meta 픽셀의 _fbc 쿠키도 동일하게 last-touch로 동작)
|
||||
// 형식: fb.{subdomainIndex}.{creationTime(ms)}.{fbclid}
|
||||
const fbclid = params.get('fbclid');
|
||||
if (fbclid) {
|
||||
localStorage.setItem(FBC_STORAGE_KEY, `fb.1.${Date.now()}.${fbclid}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Tracking] storeUtmFromUrl failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 랜딩 진입(ViewContent) 이벤트 발화 — 비로그인 시점이므로 브라우저 픽셀 단독
|
||||
export function trackViewContent(): void {
|
||||
try {
|
||||
const fbq = getFbq();
|
||||
if (fbq) {
|
||||
fbq('track', 'ViewContent', {}, { eventID: generateEventId() });
|
||||
console.log('[Tracking] ViewContent fired');
|
||||
} else {
|
||||
console.warn('[Tracking] ViewContent skipped: fbq not loaded');
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? `${error.name}: ${error.message}\n${error.stack}` : String(error);
|
||||
console.error('[Tracking] ViewContent failed:', detail);
|
||||
}
|
||||
}
|
||||
|
||||
// 회원가입 완료(CompleteRegistration) 전환 이벤트 발화 API
|
||||
// 서버가 registration_tracked_at null 여부로 계정당 최초 1회를 판정하고 UTM을 함께 기록한다.
|
||||
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
|
||||
export async function trackCompleteRegistration(): Promise<void> {
|
||||
try {
|
||||
let utm: Record<string, string> = {};
|
||||
try {
|
||||
utm = JSON.parse(localStorage.getItem(UTM_STORAGE_KEY) ?? '{}');
|
||||
} catch {
|
||||
utm = {};
|
||||
}
|
||||
|
||||
const response = await authenticatedFetch(`${API_URL}/tracking/meta/complete-registration`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
fbc: getFbc(),
|
||||
fbp: getCookieValue('_fbp'),
|
||||
event_source_url: window.location.href,
|
||||
utm_source: utm.utm_source ?? null,
|
||||
utm_medium: utm.utm_medium ?? null,
|
||||
utm_campaign: utm.utm_campaign ?? null,
|
||||
utm_content: utm.utm_content ?? null,
|
||||
utm_term: utm.utm_term ?? null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) return;
|
||||
|
||||
const data: { fired: boolean; event_id: string | null } = await response.json();
|
||||
|
||||
if (data.fired && data.event_id) {
|
||||
const fbq = getFbq();
|
||||
if (fbq) {
|
||||
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
|
||||
fbq('track', 'CompleteRegistration', {}, { eventID: data.event_id });
|
||||
}
|
||||
// 가입 어트리뷰션 저장 완료 → 보관하던 UTM 제거
|
||||
localStorage.removeItem(UTM_STORAGE_KEY);
|
||||
}
|
||||
} catch (error) {
|
||||
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
|
||||
console.error('[Tracking] CompleteRegistration failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 영상 상태 확인 API
|
||||
export async function getVideoStatus(taskId: string): Promise<VideoStatusResponse> {
|
||||
const response = await authenticatedFetch(`${API_URL}/video/status/${taskId}`, {
|
||||
@@ -478,18 +656,10 @@ export async function uploadImages(
|
||||
imageUrls: ImageUrlItem[],
|
||||
files: File[]
|
||||
): Promise<ImageUploadResponse> {
|
||||
const formData = new FormData();
|
||||
|
||||
// URL 이미지들을 images_json으로 전달
|
||||
if (imageUrls.length > 0) {
|
||||
formData.append('images_json', JSON.stringify(imageUrls));
|
||||
}
|
||||
|
||||
// 파일들을 files로 전달
|
||||
files.forEach((file) => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
return uploadImagesSequentially(imageUrls, files, postImageUpload);
|
||||
}
|
||||
|
||||
async function postImageUpload(formData: FormData): Promise<ImageUploadResponse> {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), IMAGE_UPLOAD_TIMEOUT);
|
||||
|
||||
@@ -500,19 +670,21 @@ export async function uploadImages(
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 413) {
|
||||
throw new Error('이미지 파일이 너무 커서 업로드할 수 없습니다. 더 작은 이미지를 선택해주세요.');
|
||||
}
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error('이미지 업로드 시간이 초과되었습니다. 다시 시도해주세요.');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -764,15 +936,25 @@ function clearAllLocalData() {
|
||||
|
||||
// 로그아웃
|
||||
export async function logout(): Promise<void> {
|
||||
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, {
|
||||
method: 'POST',
|
||||
});
|
||||
const refreshToken = getRefreshToken();
|
||||
|
||||
// 응답과 관계없이 로컬 데이터 전체 삭제
|
||||
clearAllLocalData();
|
||||
try {
|
||||
if (refreshToken) {
|
||||
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// 응답과 관계없이 로컬 데이터 전체 삭제
|
||||
clearAllLocalData();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
export const MAX_UPLOAD_IMAGE_BYTES = 2 * 1024 * 1024;
|
||||
export const MAX_UPLOAD_IMAGE_DIMENSION = 2048;
|
||||
export const MAX_FALLBACK_UPLOAD_IMAGE_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
const OUTPUT_MIME_TYPE = 'image/jpeg';
|
||||
const OUTPUT_EXTENSION = 'jpg';
|
||||
const BACKEND_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'webp', 'heic', 'heif']);
|
||||
const BACKEND_IMAGE_MIME_TYPES = new Set([
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/webp',
|
||||
'image/heic',
|
||||
'image/heif',
|
||||
'image/heic-sequence',
|
||||
'image/heif-sequence',
|
||||
]);
|
||||
|
||||
interface ImageDimensions {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface DecodedImage extends ImageDimensions {
|
||||
source: CanvasImageSource;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
interface CompressionAttempt {
|
||||
scale: number;
|
||||
quality: number;
|
||||
}
|
||||
|
||||
const COMPRESSION_ATTEMPTS: CompressionAttempt[] = [
|
||||
{ scale: 1, quality: 0.86 },
|
||||
{ scale: 1, quality: 0.74 },
|
||||
{ scale: 1, quality: 0.62 },
|
||||
{ scale: 1, quality: 0.5 },
|
||||
{ scale: 0.85, quality: 0.7 },
|
||||
{ scale: 0.7, quality: 0.65 },
|
||||
{ scale: 0.55, quality: 0.6 },
|
||||
{ scale: 0.4, quality: 0.55 },
|
||||
];
|
||||
|
||||
export function calculateTargetDimensions(
|
||||
width: number,
|
||||
height: number,
|
||||
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
|
||||
): ImageDimensions {
|
||||
if (
|
||||
!Number.isFinite(width) ||
|
||||
!Number.isFinite(height) ||
|
||||
!Number.isFinite(maxDimension) ||
|
||||
width <= 0 ||
|
||||
height <= 0 ||
|
||||
maxDimension <= 0
|
||||
) {
|
||||
throw new Error('Image dimensions must be positive finite numbers.');
|
||||
}
|
||||
|
||||
const scale = Math.min(1, maxDimension / Math.max(width, height));
|
||||
|
||||
return {
|
||||
width: Math.max(1, Math.round(width * scale)),
|
||||
height: Math.max(1, Math.round(height * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldCompressImage(
|
||||
fileSize: number,
|
||||
dimensions: ImageDimensions,
|
||||
maxBytes = MAX_UPLOAD_IMAGE_BYTES,
|
||||
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
|
||||
): boolean {
|
||||
return (
|
||||
fileSize > maxBytes ||
|
||||
dimensions.width > maxDimension ||
|
||||
dimensions.height > maxDimension
|
||||
);
|
||||
}
|
||||
|
||||
export function buildCompressedFileName(fileName: string): string {
|
||||
const extensionIndex = fileName.lastIndexOf('.');
|
||||
const baseName = extensionIndex > 0 ? fileName.slice(0, extensionIndex) : fileName;
|
||||
return `${baseName || 'image'}.${OUTPUT_EXTENSION}`;
|
||||
}
|
||||
|
||||
function getFileExtension(fileName: string): string {
|
||||
const extensionIndex = fileName.lastIndexOf('.');
|
||||
return extensionIndex >= 0 ? fileName.slice(extensionIndex + 1).toLowerCase() : '';
|
||||
}
|
||||
|
||||
export function isImageInputFile(file: Pick<File, 'name' | 'type'>): boolean {
|
||||
return file.type.startsWith('image/') || BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
|
||||
}
|
||||
|
||||
export function canUploadOriginalImage(file: Pick<File, 'name' | 'type'>): boolean {
|
||||
const hasAllowedExtension = BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
|
||||
const hasAllowedMimeType = file.type === '' || BACKEND_IMAGE_MIME_TYPES.has(file.type.toLowerCase());
|
||||
return hasAllowedExtension && hasAllowedMimeType;
|
||||
}
|
||||
|
||||
export function canUploadOriginalAfterCompressionFailure(
|
||||
fileSize: number,
|
||||
maxBytes = MAX_FALLBACK_UPLOAD_IMAGE_BYTES
|
||||
): boolean {
|
||||
return fileSize <= maxBytes;
|
||||
}
|
||||
|
||||
function useOriginalOrThrow(file: File, cause: unknown): File {
|
||||
if (!canUploadOriginalImage(file)) {
|
||||
throw new Error(
|
||||
`${file.name} 파일을 지원하는 이미지 형식으로 변환할 수 없습니다. ` +
|
||||
'JPEG, PNG 또는 WebP로 변환한 뒤 다시 시도해주세요.',
|
||||
{ cause }
|
||||
);
|
||||
}
|
||||
|
||||
if (!canUploadOriginalAfterCompressionFailure(file.size)) {
|
||||
throw new Error(
|
||||
`${file.name} 파일은 15 MB보다 크고 브라우저에서 크기를 줄일 수 없습니다. ` +
|
||||
'JPEG나 PNG로 변환하거나 더 작은 이미지를 선택해주세요.',
|
||||
{ cause }
|
||||
);
|
||||
}
|
||||
|
||||
console.warn(`Image compression was unavailable for ${file.name}; uploading the original.`, cause);
|
||||
return file;
|
||||
}
|
||||
|
||||
function decodeWithImageElement(file: File): Promise<DecodedImage> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
const image = new Image();
|
||||
|
||||
image.onload = () => {
|
||||
resolve({
|
||||
source: image,
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
dispose: () => URL.revokeObjectURL(objectUrl),
|
||||
});
|
||||
};
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
reject(new Error(`Unable to decode image: ${file.name}`));
|
||||
};
|
||||
image.src = objectUrl;
|
||||
});
|
||||
}
|
||||
|
||||
async function decodeImage(file: File): Promise<DecodedImage> {
|
||||
if (typeof createImageBitmap === 'function') {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
return {
|
||||
source: bitmap,
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
dispose: () => bitmap.close(),
|
||||
};
|
||||
}
|
||||
|
||||
return decodeWithImageElement(file);
|
||||
}
|
||||
|
||||
function canvasToBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject(new Error('The browser could not compress the image.'));
|
||||
}
|
||||
},
|
||||
OUTPUT_MIME_TYPE,
|
||||
quality
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function compressImageForUpload(file: File): Promise<File> {
|
||||
if (!isImageInputFile(file)) {
|
||||
throw new Error(`지원하지 않는 이미지 파일입니다: ${file.name}`);
|
||||
}
|
||||
|
||||
let decoded: DecodedImage;
|
||||
try {
|
||||
decoded = await decodeImage(file);
|
||||
} catch (error) {
|
||||
return useOriginalOrThrow(file, error);
|
||||
}
|
||||
|
||||
try {
|
||||
if (
|
||||
canUploadOriginalImage(file) &&
|
||||
!shouldCompressImage(file.size, {
|
||||
width: decoded.width,
|
||||
height: decoded.height,
|
||||
})
|
||||
) {
|
||||
return file;
|
||||
}
|
||||
|
||||
const baseDimensions = calculateTargetDimensions(decoded.width, decoded.height);
|
||||
let smallestBlob: Blob | null = null;
|
||||
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
const context = canvas.getContext('2d');
|
||||
|
||||
if (!context) {
|
||||
throw new Error('The browser does not support image compression.');
|
||||
}
|
||||
|
||||
for (const attempt of COMPRESSION_ATTEMPTS) {
|
||||
canvas.width = Math.max(1, Math.round(baseDimensions.width * attempt.scale));
|
||||
canvas.height = Math.max(1, Math.round(baseDimensions.height * attempt.scale));
|
||||
|
||||
// JPEG has no alpha channel. A white background avoids transparent pixels
|
||||
// becoming black when PNG/WebP images are converted.
|
||||
context.fillStyle = '#ffffff';
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(decoded.source, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
const blob = await canvasToBlob(canvas, attempt.quality);
|
||||
if (!smallestBlob || blob.size < smallestBlob.size) {
|
||||
smallestBlob = blob;
|
||||
}
|
||||
|
||||
if (blob.size <= MAX_UPLOAD_IMAGE_BYTES) {
|
||||
return new File([blob], buildCompressedFileName(file.name), {
|
||||
type: blob.type || OUTPUT_MIME_TYPE,
|
||||
lastModified: file.lastModified,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return useOriginalOrThrow(file, error);
|
||||
}
|
||||
|
||||
const measuredSize = smallestBlob?.size ?? file.size;
|
||||
throw new Error(
|
||||
`${file.name} 파일을 ${Math.round(MAX_UPLOAD_IMAGE_BYTES / (1024 * 1024))} MB 이하로 ` +
|
||||
`압축할 수 없습니다(압축 결과: ${Math.ceil(measuredSize / (1024 * 1024))} MB).`
|
||||
);
|
||||
} finally {
|
||||
decoded.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export const MAX_PREVIEW_DIMENSION = 400;
|
||||
export const PREVIEW_QUALITY = 0.7;
|
||||
|
||||
/**
|
||||
* 그리드 미리보기 전용 축소 썸네일을 만든다.
|
||||
*
|
||||
* 업로드에는 원본 File 을 그대로 쓰고, 여기서 만든 objectURL 은 <img> 에만 쓰인다.
|
||||
* 핵심은 finally 의 dispose() 로, createImageBitmap 경로에서 원본 비트맵을 즉시
|
||||
* 해제해 메모리에 원본 크기 비트맵이 남지 않게 한다.
|
||||
*
|
||||
* 실패해도 예외를 던지지 않고 null 을 돌려준다. 호출부가 자리표시자를 그린다.
|
||||
*/
|
||||
export async function createPreviewThumbnail(file: File): Promise<string | null> {
|
||||
if (!isImageInputFile(file)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let decoded: DecodedImage;
|
||||
try {
|
||||
decoded = await decodeImage(file);
|
||||
} catch (error) {
|
||||
console.warn(`미리보기 썸네일 디코딩 실패: ${file.name}`, error);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const { width, height } = calculateTargetDimensions(
|
||||
decoded.width,
|
||||
decoded.height,
|
||||
MAX_PREVIEW_DIMENSION
|
||||
);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// JPEG 에는 알파 채널이 없다. 투명 픽셀이 검게 나오지 않도록 흰 배경을 깐다.
|
||||
context.fillStyle = '#ffffff';
|
||||
context.fillRect(0, 0, width, height);
|
||||
context.drawImage(decoded.source, 0, 0, width, height);
|
||||
|
||||
const blob = await canvasToBlob(canvas, PREVIEW_QUALITY);
|
||||
return URL.createObjectURL(blob);
|
||||
} catch (error) {
|
||||
console.warn(`미리보기 썸네일 생성 실패: ${file.name}`, error);
|
||||
return null;
|
||||
} finally {
|
||||
decoded.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ImageItem } from '../types/api';
|
||||
|
||||
/**
|
||||
* 같은 파일을 가리키는지 판별하기 위한 키.
|
||||
*
|
||||
* 브라우저는 동일한 파일에 대해 name/size/lastModified 를 항상 동일하게 주므로,
|
||||
* 내용 해시를 계산하지 않고도 비용 없이 중복을 걸러낼 수 있다.
|
||||
*/
|
||||
export function getFileIdentity(file: Pick<File, 'name' | 'size' | 'lastModified'>): string {
|
||||
return `${file.name}|${file.size}|${file.lastModified}`;
|
||||
}
|
||||
|
||||
export interface FileDedupResult {
|
||||
/** 목록에 새로 넣어야 할 파일 */
|
||||
newFiles: File[];
|
||||
/** 중복이라 제외된 파일 수 */
|
||||
duplicateCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미 목록에 있는 파일, 그리고 이번 배치 안에서 서로 겹치는 파일을 걸러낸다.
|
||||
*
|
||||
* url 타입 이미지(크롤링으로 가져온 원격 이미지)는 로컬 파일과 비교할 수단이
|
||||
* 없으므로 비교 대상에서 제외한다.
|
||||
*/
|
||||
export function splitDuplicateFiles(existing: ImageItem[], incoming: File[]): FileDedupResult {
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const item of existing) {
|
||||
if (item.type === 'file') {
|
||||
seen.add(getFileIdentity(item.file));
|
||||
}
|
||||
}
|
||||
|
||||
const newFiles: File[] = [];
|
||||
let duplicateCount = 0;
|
||||
|
||||
for (const file of incoming) {
|
||||
const identity = getFileIdentity(file);
|
||||
if (seen.has(identity)) {
|
||||
duplicateCount += 1;
|
||||
continue;
|
||||
}
|
||||
seen.add(identity);
|
||||
newFiles.push(file);
|
||||
}
|
||||
|
||||
return { newFiles, duplicateCount };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { ImageUploadResponse, ImageUrlItem } from '../types/api';
|
||||
import { compressImageForUpload } from './imageCompression.ts';
|
||||
|
||||
export const MAX_IMAGES_PER_UPLOAD_TASK = 100;
|
||||
|
||||
export type ImageUploadRequest = (formData: FormData) => Promise<ImageUploadResponse>;
|
||||
export type ImageCompressor = (file: File) => Promise<File>;
|
||||
|
||||
interface ImageUploadFormOptions {
|
||||
imageUrls?: ImageUrlItem[];
|
||||
file?: File;
|
||||
taskId?: string;
|
||||
finalize?: boolean;
|
||||
}
|
||||
|
||||
export function createImageUploadFormData({
|
||||
imageUrls = [],
|
||||
file,
|
||||
taskId,
|
||||
finalize,
|
||||
}: ImageUploadFormOptions): FormData {
|
||||
const formData = new FormData();
|
||||
|
||||
if (imageUrls.length > 0) {
|
||||
formData.append('images_json', JSON.stringify(imageUrls));
|
||||
}
|
||||
if (taskId) {
|
||||
formData.append('task_id', taskId);
|
||||
}
|
||||
if (finalize !== undefined) {
|
||||
formData.append('finalize', String(finalize));
|
||||
}
|
||||
if (file) {
|
||||
formData.append('files', file);
|
||||
}
|
||||
|
||||
return formData;
|
||||
}
|
||||
|
||||
export async function uploadImagesSequentially(
|
||||
imageUrls: ImageUrlItem[],
|
||||
files: File[],
|
||||
sendRequest: ImageUploadRequest,
|
||||
compressFile: ImageCompressor = compressImageForUpload
|
||||
): Promise<ImageUploadResponse> {
|
||||
const totalImageCount = imageUrls.length + files.length;
|
||||
if (totalImageCount > MAX_IMAGES_PER_UPLOAD_TASK) {
|
||||
throw new Error(`이미지는 최대 ${MAX_IMAGES_PER_UPLOAD_TASK}장까지 업로드할 수 있습니다.`);
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
return sendRequest(createImageUploadFormData({ imageUrls }));
|
||||
}
|
||||
|
||||
let taskId: string | undefined;
|
||||
let finalResponse: ImageUploadResponse | undefined;
|
||||
|
||||
for (let index = 0; index < files.length; index += 1) {
|
||||
// Compress and upload one source at a time. This prevents both decoded
|
||||
// image buffers and multipart request bodies from accumulating in memory.
|
||||
const compressedFile = await compressFile(files[index]);
|
||||
const isFirstRequest = index === 0;
|
||||
const isLastRequest = index === files.length - 1;
|
||||
const formData = createImageUploadFormData({
|
||||
imageUrls: isFirstRequest ? imageUrls : [],
|
||||
file: compressedFile,
|
||||
taskId,
|
||||
finalize: isLastRequest,
|
||||
});
|
||||
|
||||
finalResponse = await sendRequest(formData);
|
||||
if (!finalResponse.task_id) {
|
||||
throw new Error('이미지 업로드 응답에 작업 ID가 없습니다.');
|
||||
}
|
||||
if (taskId && finalResponse.task_id !== taskId) {
|
||||
throw new Error('이미지 업로드 작업 ID가 요청 사이에 변경되었습니다. 다시 시도해주세요.');
|
||||
}
|
||||
taskId = finalResponse.task_id;
|
||||
}
|
||||
|
||||
// files.length > 0 guarantees that the loop produced a response.
|
||||
return finalResponse as ImageUploadResponse;
|
||||
}
|
||||
Reference in new issue
Block a user