version19
This commit is contained in:
1 parent
d820394ccc
commit
07a3a1093b
59 files changed
+19645
-2399
No files matched your search
+305
-112
@@ -2,7 +2,7 @@
|
||||
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { GeneratedAssets } from '../types';
|
||||
import { Play, Pause, RefreshCw, Download, Image as ImageIcon, Video as VideoIcon, Music, Mic, Loader2, Film, Share2, Youtube, ArrowLeft, Volume2, VolumeX } from 'lucide-react';
|
||||
import { Play, Pause, RefreshCw, Download, Image as ImageIcon, Video as VideoIcon, Music, Mic, Loader2, Film, Share2, Youtube, Instagram, ArrowLeft, Volume2, VolumeX } from 'lucide-react';
|
||||
import { mergeVideoAndAudio } from '../services/ffmpegService';
|
||||
import ShareModal from './ShareModal';
|
||||
import SlideshowBackground from './SlideshowBackground';
|
||||
@@ -55,6 +55,16 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
const [showShareModal, setShowShareModal] = useState(false);
|
||||
const [showSEOPreview, setShowSEOPreview] = useState(false);
|
||||
|
||||
// Instagram 업로드 상태
|
||||
const [isUploadingInstagram, setIsUploadingInstagram] = useState(false);
|
||||
const [instagramUploadStatus, setInstagramUploadStatus] = useState('');
|
||||
const [instagramUrl, setInstagramUrl] = useState<string | null>(null);
|
||||
|
||||
// 렌더링 큐 상태
|
||||
const [currentJobId, setCurrentJobId] = useState<string | null>(null);
|
||||
const [renderStatus, setRenderStatus] = useState<'idle' | 'submitting' | 'processing' | 'completed' | 'failed'>('idle');
|
||||
const [renderMessage, setRenderMessage] = useState('');
|
||||
|
||||
// AutoPlay 로직
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
@@ -199,49 +209,118 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
return () => clearInterval(interval);
|
||||
}, [isPlaying, assets.adCopy.length]);
|
||||
|
||||
// URL을 Base64로 변환하는 유틸리티 함수
|
||||
const urlToBase64 = async (url: string): Promise<string | undefined> => {
|
||||
if (!url) return undefined;
|
||||
try {
|
||||
let response: Response;
|
||||
if (url.startsWith('blob:')) {
|
||||
response = await fetch(url);
|
||||
} else if (url.startsWith('http')) {
|
||||
response = await fetch(`/api/proxy/audio?url=${encodeURIComponent(url)}`);
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
const blob = await response.blob();
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
resolve(result.split(',')[1]);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('URL to Base64 failed:', e);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// 렌더링 작업 상태 폴링
|
||||
const pollJobStatus = async (jobId: string) => {
|
||||
const token = localStorage.getItem('token');
|
||||
let pollCount = 0;
|
||||
const maxPolls = 180; // 최대 3분 (1초 간격)
|
||||
|
||||
const poll = async () => {
|
||||
if (pollCount >= maxPolls) {
|
||||
setRenderStatus('failed');
|
||||
setRenderMessage('렌더링 시간 초과');
|
||||
setIsServerDownloading(false);
|
||||
setIsRendering(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/render/status/${jobId}`, {
|
||||
headers: { 'Authorization': token ? `Bearer ${token}` : '' }
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (!data.success) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
const { job } = data;
|
||||
setDownloadProgress(job.progress || 0);
|
||||
|
||||
if (job.status === 'completed') {
|
||||
setRenderStatus('completed');
|
||||
setRenderMessage('렌더링 완료!');
|
||||
setLastProjectFolder(job.downloadUrl?.split('/')[2] || null);
|
||||
setIsServerDownloading(false);
|
||||
setIsRendering(false);
|
||||
|
||||
// 자동 다운로드
|
||||
if (job.downloadUrl) {
|
||||
const a = document.createElement('a');
|
||||
a.href = job.downloadUrl;
|
||||
a.download = `CastAD_${assets.businessName}_Final.mp4`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (job.status === 'failed') {
|
||||
setRenderStatus('failed');
|
||||
setRenderMessage(job.error_message || '렌더링 실패');
|
||||
setIsServerDownloading(false);
|
||||
setIsRendering(false);
|
||||
alert(`렌더링 실패: ${job.error_message || '알 수 없는 오류'}\n크레딧이 환불되었습니다.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 계속 폴링
|
||||
pollCount++;
|
||||
setTimeout(poll, 1000);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('폴링 오류:', error);
|
||||
pollCount++;
|
||||
setTimeout(poll, 2000); // 오류 시 2초 후 재시도
|
||||
}
|
||||
};
|
||||
|
||||
poll();
|
||||
};
|
||||
|
||||
const handleServerDownload = async () => {
|
||||
if (isServerDownloading) return;
|
||||
setIsServerDownloading(true);
|
||||
setDownloadProgress(10);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 300000);
|
||||
setRenderStatus('submitting');
|
||||
setRenderMessage('렌더링 요청 중...');
|
||||
setDownloadProgress(5);
|
||||
|
||||
try {
|
||||
const urlToBase64 = async (url: string): Promise<string | undefined> => {
|
||||
if (!url) return undefined;
|
||||
try {
|
||||
// blob URL이든 외부 URL이든 모두 처리
|
||||
let response: Response;
|
||||
if (url.startsWith('blob:')) {
|
||||
response = await fetch(url);
|
||||
} else if (url.startsWith('http')) {
|
||||
// 외부 URL은 프록시를 통해 가져옴 (CORS 우회)
|
||||
response = await fetch(`/api/proxy/audio?url=${encodeURIComponent(url)}`);
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
const blob = await response.blob();
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
const result = reader.result as string;
|
||||
resolve(result.split(',')[1]);
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Audio URL to Base64 failed:', e);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
setDownloadProgress(20);
|
||||
// 데이터 준비
|
||||
setDownloadProgress(10);
|
||||
const posterBase64 = await urlToBase64(assets.posterUrl);
|
||||
const audioBase64 = await urlToBase64(assets.audioUrl);
|
||||
|
||||
setDownloadProgress(30);
|
||||
setDownloadProgress(15);
|
||||
let imagesBase64: string[] = [];
|
||||
if (assets.images && assets.images.length > 0) {
|
||||
imagesBase64 = await Promise.all(
|
||||
@@ -257,64 +336,72 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
);
|
||||
}
|
||||
|
||||
setDownloadProgress(40);
|
||||
setDownloadProgress(20);
|
||||
|
||||
const payload = {
|
||||
...assets,
|
||||
historyId: assets.id,
|
||||
posterBase64,
|
||||
audioBase64,
|
||||
imagesBase64
|
||||
imagesBase64,
|
||||
adCopy: assets.adCopy,
|
||||
textEffect: assets.textEffect || 'effect-fade',
|
||||
businessName: assets.businessName,
|
||||
aspectRatio: assets.aspectRatio || '9:16',
|
||||
pensionId: assets.pensionId
|
||||
};
|
||||
|
||||
setIsRendering(true);
|
||||
setDownloadProgress(50);
|
||||
|
||||
const token = localStorage.getItem('token');
|
||||
const response = await fetch('/render', {
|
||||
|
||||
// 렌더링 작업 시작 요청
|
||||
const response = await fetch('/api/render/start', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
setDownloadProgress(80);
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.text();
|
||||
throw new Error(`서버 오류: ${err}`);
|
||||
if (!response.ok || !data.success) {
|
||||
// 이미 진행 중인 작업이 있는 경우
|
||||
if (data.errorCode === 'RENDER_IN_PROGRESS') {
|
||||
setCurrentJobId(data.existingJobId);
|
||||
setRenderStatus('processing');
|
||||
setRenderMessage(`기존 작업 진행 중 (${data.existingJobProgress || 0}%)`);
|
||||
setIsRendering(true);
|
||||
setDownloadProgress(data.existingJobProgress || 0);
|
||||
|
||||
// 기존 작업 상태 폴링 시작
|
||||
pollJobStatus(data.existingJobId);
|
||||
return;
|
||||
}
|
||||
throw new Error(data.error || '렌더링 요청 실패');
|
||||
}
|
||||
|
||||
const folderNameHeader = response.headers.get('X-Project-Folder');
|
||||
if (folderNameHeader) {
|
||||
setLastProjectFolder(decodeURIComponent(folderNameHeader));
|
||||
}
|
||||
// 작업 ID 저장 및 폴링 시작
|
||||
setCurrentJobId(data.jobId);
|
||||
setRenderStatus('processing');
|
||||
setRenderMessage(`렌더링 중... (크레딧 ${data.creditsCharged} 차감)`);
|
||||
setIsRendering(true);
|
||||
setDownloadProgress(25);
|
||||
|
||||
setDownloadProgress(90);
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `CastAD_${assets.businessName}_Final.mp4`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
// 상태 폴링 시작
|
||||
pollJobStatus(data.jobId);
|
||||
|
||||
setDownloadProgress(100);
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
if (e.name === 'AbortError') {
|
||||
alert("영상 생성 시간 초과 (5분). 서버 부하가 높거나 네트워크 문제일 수 있습니다.");
|
||||
} else {
|
||||
alert("영상 생성 실패: 서버가 실행 중인지 확인해주세요.");
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
setRenderStatus('failed');
|
||||
setRenderMessage(e.message || '렌더링 요청 실패');
|
||||
setIsServerDownloading(false);
|
||||
setIsRendering(false);
|
||||
setTimeout(() => setDownloadProgress(0), 2000);
|
||||
setDownloadProgress(0);
|
||||
|
||||
if (e.message?.includes('크레딧')) {
|
||||
alert(e.message);
|
||||
} else {
|
||||
alert(`렌더링 요청 실패: ${e.message}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -356,49 +443,35 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
// 비디오 경로 생성
|
||||
const videoPath = `downloads/${lastProjectFolder}/final.mp4`;
|
||||
|
||||
let response;
|
||||
|
||||
if (connData.connected) {
|
||||
// 사용자 채널에 업로드 (새 API)
|
||||
setUploadStatus("내 채널에 업로드 중...");
|
||||
response = await fetch('/api/youtube/my-upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify({
|
||||
videoPath,
|
||||
seoData: { title, description, tags, pinnedComment },
|
||||
historyId: assets.id,
|
||||
categoryId
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// 레거시 업로드 (시스템 채널)
|
||||
setUploadStatus("시스템 채널에 업로드 중...");
|
||||
response = await fetch('/api/youtube/upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify({
|
||||
videoPath,
|
||||
seoData: { title, description, tags },
|
||||
categoryId
|
||||
})
|
||||
});
|
||||
// YouTube 연결 확인
|
||||
if (!connData.connected) {
|
||||
throw new Error("YouTube 계정이 연결되지 않았습니다. 설정에서 YouTube 계정을 먼저 연결해주세요.");
|
||||
}
|
||||
|
||||
// 사용자 채널에 업로드
|
||||
setUploadStatus("내 채널에 업로드 중...");
|
||||
const response = await fetch('/api/youtube/my-upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify({
|
||||
videoPath,
|
||||
seoData: { title, description, tags, pinnedComment },
|
||||
historyId: assets.id,
|
||||
categoryId
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errData = await response.json();
|
||||
throw new Error(errData.error || "업로드 실패");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setYoutubeUrl(data.youtubeUrl);
|
||||
setUploadStatus(connData.connected ? "내 채널에 업로드 완료!" : "업로드 완료!");
|
||||
setYoutubeUrl(data.youtubeUrl || data.url);
|
||||
setUploadStatus("내 채널에 업로드 완료!");
|
||||
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
@@ -409,6 +482,67 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
}
|
||||
};
|
||||
|
||||
// Instagram 업로드 핸들러
|
||||
const handleInstagramUpload = async () => {
|
||||
if (!lastProjectFolder) {
|
||||
alert("먼저 영상을 생성(다운로드)해야 업로드할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsUploadingInstagram(true);
|
||||
setInstagramUploadStatus("Instagram 연결 확인 중...");
|
||||
setInstagramUrl(null);
|
||||
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
try {
|
||||
// Instagram 연결 상태 확인
|
||||
const statusRes = await fetch('/api/instagram/status', {
|
||||
headers: { 'Authorization': token ? `Bearer ${token}` : '' }
|
||||
});
|
||||
const statusData = await statusRes.json();
|
||||
|
||||
if (!statusData.connected) {
|
||||
throw new Error("Instagram 계정이 연결되지 않았습니다. 설정에서 Instagram 계정을 먼저 연결해주세요.");
|
||||
}
|
||||
|
||||
// 캡션 생성 (광고 카피)
|
||||
const adCopyText = assets.adCopy?.join('\n') || assets.businessName || '';
|
||||
const hashtags = `#${assets.businessName?.replace(/\s+/g, '')} #펜션 #숙소 #여행 #힐링 #휴가 #AI마케팅 #CaStAD`;
|
||||
|
||||
setInstagramUploadStatus("Instagram Reels 업로드 중...");
|
||||
|
||||
const response = await fetch('/api/instagram/upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : ''
|
||||
},
|
||||
body: JSON.stringify({
|
||||
history_id: assets.id,
|
||||
caption: adCopyText,
|
||||
hashtags: hashtags
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errData = await response.json();
|
||||
throw new Error(errData.error || "Instagram 업로드 실패");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setInstagramUrl(data.mediaUrl || data.url || 'uploaded');
|
||||
setInstagramUploadStatus("Instagram Reels 업로드 완료!");
|
||||
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setInstagramUploadStatus(e.message || "업로드 실패");
|
||||
alert(`Instagram 업로드 실패: ${e.message}`);
|
||||
} finally {
|
||||
setIsUploadingInstagram(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMergeDownload = async () => {
|
||||
if (isMerging) return;
|
||||
|
||||
@@ -896,16 +1030,75 @@ const ResultPlayer: React.FC<ResultPlayerProps> = ({ assets, onReset, autoPlay =
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Instagram 업로드 */}
|
||||
{!instagramUrl ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleInstagramUpload}
|
||||
disabled={isUploadingInstagram || !lastProjectFolder}
|
||||
className={cn(
|
||||
"gap-2",
|
||||
lastProjectFolder && "bg-gradient-to-r from-purple-500 via-pink-500 to-orange-500 hover:from-purple-600 hover:via-pink-600 hover:to-orange-600 text-white border-0"
|
||||
)}
|
||||
>
|
||||
{isUploadingInstagram ? <Loader2 className="w-4 h-4 animate-spin" /> : <Instagram className="w-4 h-4" />}
|
||||
Instagram
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{!lastProjectFolder
|
||||
? (t('textStyle') === '자막 스타일' ? '먼저 영상을 저장하세요' : 'Save video first')
|
||||
: (t('textStyle') === '자막 스타일' ? 'Instagram Reels 업로드' : 'Upload to Instagram Reels')
|
||||
}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
className="bg-gradient-to-r from-purple-500 via-pink-500 to-orange-500 gap-2"
|
||||
>
|
||||
<Instagram className="w-4 h-4" />
|
||||
{t('textStyle') === '자막 스타일' ? '완료' : 'Done'}
|
||||
</Button>
|
||||
<Badge variant="outline" className="text-green-500 border-green-500/50">
|
||||
{t('textStyle') === '자막 스타일' ? '업로드 완료' : 'Uploaded'}
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
{/* 다운로드 진행률 */}
|
||||
{downloadProgress > 0 && downloadProgress < 100 && (
|
||||
{/* 렌더링 진행률 및 상태 */}
|
||||
{(downloadProgress > 0 || renderStatus === 'processing') && (
|
||||
<div className="w-full pt-2 border-t border-border/50">
|
||||
<Progress value={downloadProgress} className="h-2" />
|
||||
<p className="text-xs text-muted-foreground text-center mt-1">
|
||||
{t('textStyle') === '자막 스타일' ? '렌더링 중...' : 'Rendering...'} {downloadProgress}%
|
||||
</p>
|
||||
<div className="flex items-center justify-center gap-2 mt-1">
|
||||
{renderStatus === 'processing' && <Loader2 className="w-3 h-3 animate-spin" />}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{renderMessage || (t('textStyle') === '자막 스타일' ? '렌더링 중...' : 'Rendering...')} {downloadProgress}%
|
||||
</p>
|
||||
</div>
|
||||
{renderStatus === 'processing' && (
|
||||
<p className="text-xs text-muted-foreground/70 text-center mt-1">
|
||||
{t('textStyle') === '자막 스타일'
|
||||
? '페이지를 나가도 렌더링은 계속됩니다'
|
||||
: 'Rendering continues even if you leave'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Instagram 업로드 상태 */}
|
||||
{isUploadingInstagram && instagramUploadStatus && (
|
||||
<div className="w-full pt-2 border-t border-border/50">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-pink-500" />
|
||||
<p className="text-xs text-muted-foreground">{instagramUploadStatus}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
Reference in new issue
Block a user