유튜브 업로드 기능 완료 .

This commit is contained in:
HyeongBaeYang committed 2026-02-02 16:43:41 +09:00
1 parent e1b860a15f
commit fd9db31e52
12 files changed
+2257 -30

No files matched your search

+487
View File
@@ -0,0 +1,487 @@
import React, { useState, useEffect, useRef } from 'react';
import { getSocialAccounts, uploadToSocial, waitForUploadComplete } from '../utils/api';
import { SocialAccount, VideoListItem, SocialUploadStatusResponse } from '../types/api';
import UploadProgressModal, { UploadStatus } from './UploadProgressModal';
interface SocialPostingModalProps {
isOpen: boolean;
onClose: () => void;
video: VideoListItem | null;
}
type PrivacyType = 'public' | 'unlisted' | 'private';
type PublishTimeType = 'now' | 'schedule';
// 플랫폼별 아이콘 경로
const getPlatformIcon = (platform: string) => {
switch (platform) {
case 'youtube':
return '/assets/images/social-youtube.png';
case 'instagram':
return '/assets/images/social-instagram.png';
default:
return '/assets/images/social-youtube.png';
}
};
const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
isOpen,
onClose,
video
}) => {
const [socialAccounts, setSocialAccounts] = useState<SocialAccount[]>([]);
const [selectedChannel, setSelectedChannel] = useState<string>('');
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [tags, setTags] = useState('');
const [privacy, setPrivacy] = useState<PrivacyType>('public');
const [publishTime, setPublishTime] = useState<PublishTimeType>('now');
const [isLoadingAccounts, setIsLoadingAccounts] = useState(false);
const [isPosting, setIsPosting] = useState(false);
const [isChannelDropdownOpen, setIsChannelDropdownOpen] = useState(false);
const [isPrivacyDropdownOpen, setIsPrivacyDropdownOpen] = useState(false);
const channelDropdownRef = useRef<HTMLDivElement>(null);
const privacyDropdownRef = useRef<HTMLDivElement>(null);
// Upload progress modal state
const [showUploadProgress, setShowUploadProgress] = useState(false);
const [uploadStatus, setUploadStatus] = useState<UploadStatus>('pending');
const [uploadProgress, setUploadProgress] = useState(0);
const [uploadYoutubeUrl, setUploadYoutubeUrl] = useState<string | undefined>();
const [uploadErrorMessage, setUploadErrorMessage] = useState<string | undefined>();
// 업로드 정보 (모달이 닫힌 후에도 유지)
const [uploadVideoTitle, setUploadVideoTitle] = useState<string>('');
const [uploadChannelName, setUploadChannelName] = useState<string>('');
// 드롭다운 외부 클릭 시 닫기
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (channelDropdownRef.current && !channelDropdownRef.current.contains(event.target as Node)) {
setIsChannelDropdownOpen(false);
}
if (privacyDropdownRef.current && !privacyDropdownRef.current.contains(event.target as Node)) {
setIsPrivacyDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// 소셜 계정 로드
useEffect(() => {
if (isOpen) {
loadSocialAccounts();
// 비디오 정보로 기본 제목 설정
if (video) {
const date = new Date(video.created_at);
const formattedDate = `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
setTitle(`${video.store_name} ${formattedDate}`);
}
}
}, [isOpen, video]);
const loadSocialAccounts = async () => {
setIsLoadingAccounts(true);
try {
const response = await getSocialAccounts();
const activeAccounts = response.accounts?.filter(acc => acc.is_active) || [];
setSocialAccounts(activeAccounts);
if (activeAccounts.length > 0) {
setSelectedChannel(activeAccounts[0].platform_user_id);
}
} catch (error) {
console.error('Failed to load social accounts:', error);
} finally {
setIsLoadingAccounts(false);
}
};
const handlePost = async () => {
if (!selectedChannel || !title.trim() || !video) {
alert('채널과 제목을 입력해주세요.');
return;
}
const selectedAcc = socialAccounts.find(acc => acc.platform_user_id === selectedChannel);
if (!selectedAcc) {
alert('채널을 선택해주세요.');
return;
}
// video.video_id 검증 - 반드시 존재해야 함
if (!video.video_id) {
console.error('Video object missing video_id:', video);
alert('영상 정보가 올바르지 않습니다. (video_id 누락)');
return;
}
setIsPosting(true);
// Reset upload progress state
setUploadStatus('pending');
setUploadProgress(0);
setUploadYoutubeUrl(undefined);
setUploadErrorMessage(undefined);
// 업로드 정보 저장 (모달이 닫힌 후에도 유지)
setUploadVideoTitle(title.trim());
setUploadChannelName(selectedAcc.display_name);
setShowUploadProgress(true);
try {
// Parse tags from comma-separated string
const tagsArray = tags
.split(',')
.map(tag => tag.trim())
.filter(tag => tag.length > 0);
// Request payload 로그
const requestPayload = {
video_id: video.video_id,
social_account_id: selectedAcc.id,
title: title.trim(),
description: description.trim(),
tags: tagsArray,
privacy_status: privacy,
scheduled_at: publishTime === 'now' ? null : null,
};
console.log('[Upload] Request payload:', requestPayload);
// Call upload API
const uploadResponse = await uploadToSocial(requestPayload);
if (!uploadResponse.success) {
throw new Error(uploadResponse.message || '업로드 시작에 실패했습니다.');
}
// Poll for upload completion
const result = await waitForUploadComplete(
uploadResponse.upload_id,
(status, progress) => {
setUploadStatus(status as UploadStatus);
setUploadProgress(progress || 0);
}
);
// Upload completed successfully
setUploadStatus('completed');
setUploadProgress(100);
setUploadYoutubeUrl(result.platform_url);
// Close the posting modal (keep progress modal open)
onClose();
resetForm();
} catch (error) {
console.error('Upload failed:', error);
setUploadStatus('failed');
setUploadErrorMessage(error instanceof Error ? error.message : '업로드에 실패했습니다.');
} finally {
setIsPosting(false);
}
};
const resetForm = () => {
setTitle('');
setDescription('');
setTags('');
setPrivacy('public');
setPublishTime('now');
setSelectedChannel('');
setIsChannelDropdownOpen(false);
setIsPrivacyDropdownOpen(false);
};
const handleUploadProgressClose = () => {
setShowUploadProgress(false);
setUploadStatus('pending');
setUploadProgress(0);
setUploadYoutubeUrl(undefined);
setUploadErrorMessage(undefined);
setUploadVideoTitle('');
setUploadChannelName('');
};
const handleClose = () => {
onClose();
resetForm();
};
const selectedAccount = socialAccounts.find(acc => acc.platform_user_id === selectedChannel);
const privacyOptions = [
{ value: 'public', label: '공개' },
{ value: 'unlisted', label: '미등록 (링크로만 접근)' },
{ value: 'private', label: '비공개' }
];
const selectedPrivacyOption = privacyOptions.find(opt => opt.value === privacy);
// Always render UploadProgressModal, even when main modal is closed
const uploadProgressModalElement = (
<UploadProgressModal
isOpen={showUploadProgress}
onClose={handleUploadProgressClose}
status={uploadStatus}
progress={uploadProgress}
videoTitle={uploadVideoTitle || title || (video?.store_name || '')}
channelName={uploadChannelName || selectedAccount?.display_name || ''}
youtubeUrl={uploadYoutubeUrl}
errorMessage={uploadErrorMessage}
/>
);
if (!isOpen || !video) {
// Still render upload progress modal even when main modal is closed
return showUploadProgress ? uploadProgressModalElement : null;
}
return (
<>
<div className="social-posting-overlay" onClick={handleClose}>
<div className="social-posting-modal" onClick={(e) => e.stopPropagation()}>
{/* Header */}
<div className="social-posting-header">
<h2 className="social-posting-title">소셜 미디어 포스팅</h2>
<button className="social-posting-close" onClick={handleClose}>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<line x1="18" y1="6" x2="6" y2="18"/>
<line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
{/* Content */}
<div className="social-posting-content">
{/* Left: Video Preview */}
<div className="social-posting-preview">
<div className="social-posting-video-container">
<video
src={video.result_movie_url}
className="social-posting-video"
controls
playsInline
/>
</div>
</div>
{/* Right: Form */}
<div className="social-posting-form">
{/* Video Info */}
<div className="social-posting-video-info">
<span className="social-posting-label-badge">게시물 1</span>
<span className="social-posting-add-btn">+</span>
</div>
<div className="social-posting-video-meta">
<p className="social-posting-video-title">
{video.store_name} {new Date(video.created_at).toLocaleString('ko-KR')}
</p>
<p className="social-posting-video-specs">1080x1920 · 10초</p>
</div>
{/* Channel Selector - Custom Dropdown */}
<div className="social-posting-field">
<label className="social-posting-label">
게시 채널 <span className="required">*</span>
</label>
{isLoadingAccounts ? (
<div className="social-posting-loading">계정 로딩 중...</div>
) : socialAccounts.length === 0 ? (
<div className="social-posting-no-accounts">
<p>연결된 소셜 계정이 없습니다.</p>
<p className="social-posting-no-accounts-hint">내 정보에서 계정을 연결해주세요.</p>
</div>
) : (
<div className="social-posting-channel-dropdown" ref={channelDropdownRef}>
<button
type="button"
className={`social-posting-channel-trigger ${isChannelDropdownOpen ? 'open' : ''}`}
onClick={() => setIsChannelDropdownOpen(!isChannelDropdownOpen)}
>
<div className="social-posting-channel-selected">
{selectedAccount && (
<>
<img
src={getPlatformIcon(selectedAccount.platform)}
alt={selectedAccount.platform}
className="social-posting-channel-icon"
/>
<span>{selectedAccount.display_name}</span>
</>
)}
</div>
<svg className="social-posting-channel-arrow" viewBox="0 0 12 8" fill="none">
<path d="M1 1.5L6 6.5L11 1.5" stroke="rgba(255,255,255,0.5)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
{isChannelDropdownOpen && (
<div className="social-posting-channel-menu">
{socialAccounts.map(account => (
<button
key={account.id}
type="button"
className={`social-posting-channel-option ${selectedChannel === account.platform_user_id ? 'selected' : ''}`}
onClick={() => {
setSelectedChannel(account.platform_user_id);
setIsChannelDropdownOpen(false);
}}
>
<img
src={getPlatformIcon(account.platform)}
alt={account.platform}
className="social-posting-channel-option-icon"
/>
<span>{account.display_name}</span>
</button>
))}
</div>
)}
</div>
)}
</div>
{/* Title */}
<div className="social-posting-field">
<label className="social-posting-label">
게시물 제목 <span className="required">*</span>
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="게시물 제목을 입력하세요."
className="social-posting-input"
maxLength={100}
/>
<span className="social-posting-char-count">{title.length}/100</span>
</div>
{/* Description */}
<div className="social-posting-field">
<label className="social-posting-label">게시물 내용</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="게시물 내용을 입력하세요."
className="social-posting-textarea"
maxLength={5000}
rows={4}
/>
<span className="social-posting-char-count">{description.length}/5,000</span>
</div>
{/* Tags */}
<div className="social-posting-field">
<label className="social-posting-label">태그</label>
<input
type="text"
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="태그를 입력하세요. (쉼표로 구분)"
className="social-posting-input"
maxLength={500}
/>
<span className="social-posting-char-count">{tags.length}/500</span>
</div>
{/* Privacy - Custom Dropdown */}
<div className="social-posting-field">
<label className="social-posting-label">
게시물 공개 범위 <span className="required">*</span>
</label>
<div className="social-posting-channel-dropdown" ref={privacyDropdownRef}>
<button
type="button"
className={`social-posting-channel-trigger ${isPrivacyDropdownOpen ? 'open' : ''}`}
onClick={() => setIsPrivacyDropdownOpen(!isPrivacyDropdownOpen)}
>
<div className="social-posting-channel-selected">
<span>{selectedPrivacyOption?.label}</span>
</div>
<svg className="social-posting-channel-arrow" viewBox="0 0 12 8" fill="none">
<path d="M1 1.5L6 6.5L11 1.5" stroke="rgba(255,255,255,0.5)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
{isPrivacyDropdownOpen && (
<div className="social-posting-channel-menu">
{privacyOptions.map(option => (
<button
key={option.value}
type="button"
className={`social-posting-channel-option ${privacy === option.value ? 'selected' : ''}`}
onClick={() => {
setPrivacy(option.value as PrivacyType);
setIsPrivacyDropdownOpen(false);
}}
>
<span>{option.label}</span>
</button>
))}
</div>
)}
</div>
</div>
{/* Publish Time */}
<div className="social-posting-field">
<label className="social-posting-label">
게시 시간 <span className="required">*</span>
</label>
<div className="social-posting-radio-group">
<label className="social-posting-radio">
<input
type="radio"
name="publishTime"
value="now"
checked={publishTime === 'now'}
onChange={() => setPublishTime('now')}
/>
<span className="radio-label">지금 게시</span>
</label>
<label className="social-posting-radio">
<input
type="radio"
name="publishTime"
value="schedule"
checked={publishTime === 'schedule'}
onChange={() => setPublishTime('schedule')}
disabled
/>
<span className="radio-label disabled">시간 설정 (준비 중)</span>
</label>
</div>
</div>
</div>
</div>
{/* Footer */}
<div className="social-posting-footer">
<p className="social-posting-footer-note">
게시는 <a href="#" className="social-posting-link">요금제 업그레이드</a> 후 가능합니다.
</p>
<div className="social-posting-actions">
<button
className="social-posting-btn cancel"
onClick={handleClose}
disabled={isPosting}
>
취소
</button>
<button
className="social-posting-btn submit"
onClick={handlePost}
disabled={isPosting || socialAccounts.length === 0 || !title.trim()}
>
{isPosting ? '게시 중...' : '게시'}
</button>
</div>
</div>
</div>
</div>
{uploadProgressModalElement}
</>
);
};
export default SocialPostingModal;