Spaces:
Running
Running
Download script.js from marcomail/videopost-wizard-pro: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/marcomail/videopost-wizard-pro/resolve/main/script.js
- Command line
-
hf download hf://spaces/marcomail/videopost-wizard-pro/script.js
-
curl -L -o script.js https://huggingface.co/spaces/marcomail/videopost-wizard-pro/resolve/main/script.js
14.6 kB
| document.addEventListener('DOMContentLoaded', function() { | |
| // Authentication state | |
| const authState = { | |
| facebook: false, | |
| instagram: false, | |
| facebookToken: null, | |
| instagramToken: null | |
| }; | |
| // Facebook App ID - replace with your actual Facebook App ID | |
| const FACEBOOK_APP_ID = 'your-facebook-app-id'; | |
| // Instagram App ID - replace with your actual Instagram App ID | |
| const INSTAGRAM_APP_ID = 'your-instagram-app-id'; | |
| // Initialize UI elements | |
| const youtubeUrlInput = document.getElementById('youtube-url'); | |
| const fetchBtn = document.getElementById('fetch-btn'); | |
| const videoPreviewContainer = document.getElementById('video-preview-container'); | |
| const videoPreview = document.getElementById('video-preview'); | |
| const videoInfo = document.getElementById('video-info'); | |
| const postBtn = document.getElementById('post-btn'); | |
| const fbAuthBtn = document.getElementById('fb-auth-btn'); | |
| const igAuthBtn = document.getElementById('ig-auth-btn'); | |
| const fbAuthStatus = document.getElementById('fb-auth-status'); | |
| const igAuthStatus = document.getElementById('ig-auth-status'); | |
| // Authentication handlers | |
| fbAuthBtn.addEventListener('click', async function() { | |
| fbAuthBtn.disabled = true; | |
| fbAuthBtn.innerHTML = '<i data-feather="loader" class="animate-spin mr-2"></i> Authenticating...'; | |
| feather.replace(); | |
| // Open Facebook OAuth dialog | |
| const width = 600; | |
| const height = 600; | |
| const left = (screen.width - width) / 2; | |
| const top = (screen.height - height) / 2; | |
| const authWindow = window.open( | |
| `https://www.facebook.com/v12.0/dialog/oauth?client_id=${FACEBOOK_APP_ID}&redirect_uri=${encodeURIComponent(window.location.href)}&scope=pages_manage_posts,pages_read_engagement&response_type=token`, | |
| 'FacebookAuth', | |
| `width=${width},height=${height},top=${top},left=${left}` | |
| ); | |
| // Poll for auth completion | |
| const checkAuth = setInterval(() => { | |
| try { | |
| if (authWindow.closed) { | |
| clearInterval(checkAuth); | |
| fbAuthBtn.disabled = false; | |
| fbAuthBtn.innerHTML = '<i data-feather="facebook" class="mr-2"></i> Authenticate Facebook'; | |
| feather.replace(); | |
| } | |
| if (authWindow.location.href.includes('access_token=')) { | |
| const token = new URL(authWindow.location.href).hash.match(/access_token=([^&]+)/)[1]; | |
| authState.facebook = true; | |
| authState.facebookToken = token; | |
| fbAuthBtn.classList.add('hidden'); | |
| fbAuthStatus.classList.remove('hidden'); | |
| feather.replace(); | |
| authWindow.close(); | |
| clearInterval(checkAuth); | |
| } | |
| } catch (e) { | |
| // Cross-origin errors are expected until auth completes | |
| } | |
| }, 500); | |
| }); | |
| igAuthBtn.addEventListener('click', async function() { | |
| igAuthBtn.disabled = true; | |
| igAuthBtn.innerHTML = '<i data-feather="loader" class="animate-spin mr-2"></i> Authenticating...'; | |
| feather.replace(); | |
| // Open Instagram OAuth dialog | |
| const width = 600; | |
| const height = 600; | |
| const left = (screen.width - width) / 2; | |
| const top = (screen.height - height) / 2; | |
| const authWindow = window.open( | |
| `https://api.instagram.com/oauth/authorize?client_id=${INSTAGRAM_APP_ID}&redirect_uri=${encodeURIComponent(window.location.href)}&scope=user_profile,user_media&response_type=code`, | |
| 'InstagramAuth', | |
| `width=${width},height=${height},top=${top},left=${left}` | |
| ); | |
| // Poll for auth completion | |
| const checkAuth = setInterval(() => { | |
| try { | |
| if (authWindow.closed) { | |
| clearInterval(checkAuth); | |
| igAuthBtn.disabled = false; | |
| igAuthBtn.innerHTML = '<i data-feather="instagram" class="mr-2"></i> Authenticate Instagram'; | |
| feather.replace(); | |
| } | |
| if (authWindow.location.href.includes('code=')) { | |
| const code = new URL(authWindow.location.href).searchParams.get('code'); | |
| // In a real app, you would exchange this code for a token via your backend | |
| authState.instagram = true; | |
| authState.instagramToken = code; | |
| igAuthBtn.classList.add('hidden'); | |
| igAuthStatus.classList.remove('hidden'); | |
| feather.replace(); | |
| authWindow.close(); | |
| clearInterval(checkAuth); | |
| } | |
| } catch (e) { | |
| // Cross-origin errors are expected until auth completes | |
| } | |
| }, 500); | |
| }); | |
| // Fetch video details when button is clicked | |
| fetchBtn.addEventListener('click', async function() { | |
| const url = youtubeUrlInput.value.trim(); | |
| if (!url) { | |
| alert('Please enter a YouTube URL'); | |
| return; | |
| } | |
| // Validate YouTube URL format | |
| const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+/; | |
| if (!youtubeRegex.test(url)) { | |
| alert('Please enter a valid YouTube URL (e.g., https://www.youtube.com/watch?v=...)'); | |
| return; | |
| } | |
| // Show loading state | |
| fetchBtn.disabled = true; | |
| fetchBtn.innerHTML = '<i data-feather="loader" class="animate-spin mr-2"></i> Fetching...'; | |
| feather.replace(); | |
| try { | |
| // Extract video ID from URL | |
| const videoId = extractVideoId(url); | |
| if (!videoId) { | |
| throw new Error('Could not extract video ID from URL'); | |
| } | |
| // Display video preview with proper embed URL | |
| videoPreview.src = `https://www.youtube.com/embed/${videoId}?autoplay=0&rel=0&showinfo=1`; | |
| // Use oEmbed API which doesn't require an API key | |
| const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`); | |
| if (!response.ok) { | |
| throw new Error('Video not found or private'); | |
| } | |
| const videoData = await response.json(); | |
| const title = videoData.title; | |
| const thumbnail = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`; | |
| // For duration we'll need to make a separate call to a public API | |
| const durationResponse = await fetch(`https://yt.lemnoslife.com/videos?part=contentDetails&id=${videoId}`); | |
| const durationData = await durationResponse.json(); | |
| const duration = durationData.items?.[0]?.contentDetails?.duration || 'N/A'; | |
| videoInfo.innerHTML = ` | |
| <div class="flex items-start"> | |
| <img src="${thumbnail}" alt="Thumbnail" class="w-32 h-18 rounded mr-4"> | |
| <div> | |
| <p><strong>Title:</strong> ${title}</p> | |
| <p><strong>Duration:</strong> ${formatDuration(duration)}</p> | |
| </div> | |
| </div> | |
| `; | |
| // Show preview container | |
| videoPreviewContainer.classList.remove('hidden'); | |
| videoPreviewContainer.classList.add('fade-in'); | |
| } catch (error) { | |
| console.error('Error:', error); | |
| let errorMessage = 'Failed to fetch video details.'; | |
| if (error.message.includes('quota')) { | |
| errorMessage += ' YouTube API quota exceeded. Try again later.'; | |
| } else if (error.message.includes('invalid')) { | |
| errorMessage += ' Invalid video ID or URL format.'; | |
| } else { | |
| errorMessage += ' Please check the URL and try again.'; | |
| } | |
| alert(errorMessage); | |
| } finally { | |
| // Reset button state | |
| fetchBtn.disabled = false; | |
| fetchBtn.innerHTML = '<i data-feather="download" class="mr-2"></i> Fetch'; | |
| feather.replace(); | |
| } | |
| }); | |
| // Handle post button click | |
| postBtn.addEventListener('click', async function() { | |
| const fbChecked = document.getElementById('post-to-facebook').checked; | |
| const igChecked = document.getElementById('post-to-instagram').checked; | |
| const caption = document.getElementById('post-caption').value; | |
| const videoUrl = youtubeUrlInput.value.trim(); | |
| if (!fbChecked && !igChecked) { | |
| showError('Please select at least one platform to post to'); | |
| return; | |
| } | |
| // Check authentication | |
| if (fbChecked && !authState.facebook) { | |
| showError('Please authenticate with Facebook first'); | |
| return; | |
| } | |
| if (igChecked && !authState.instagram) { | |
| showError('Please authenticate with Instagram first'); | |
| return; | |
| } | |
| if (!videoUrl) { | |
| showError('Please enter a YouTube URL first'); | |
| return; | |
| } | |
| // Show loading state | |
| postBtn.disabled = true; | |
| postBtn.innerHTML = '<i data-feather="loader" class="animate-spin mr-2"></i> Posting...'; | |
| feather.replace(); | |
| try { | |
| // Download YouTube video (would need a backend service in production) | |
| const downloadResponse = await fetch(`https://your-backend-service.com/download?url=${encodeURIComponent(videoUrl)}`); | |
| const videoFile = await downloadResponse.blob(); | |
| // Prepare form data for posting | |
| const promises = []; | |
| if (fbChecked) { | |
| const fbForm = new FormData(); | |
| fbForm.append('access_token', authState.facebookToken); | |
| fbForm.append('source', videoFile); | |
| fbForm.append('description', caption); | |
| promises.push( | |
| fetch('https://graph.facebook.com/v12.0/me/videos', { | |
| method: 'POST', | |
| body: fbForm | |
| }).then(response => response.json()) | |
| .then(data => { | |
| if (data.error) throw new Error(data.error.message); | |
| return 'Facebook'; | |
| }) | |
| ); | |
| } | |
| if (igChecked) { | |
| const igForm = new FormData(); | |
| igForm.append('access_token', authState.instagramToken); | |
| igForm.append('media_type', 'VIDEO'); | |
| igForm.append('video_url', URL.createObjectURL(videoFile)); | |
| igForm.append('caption', caption); | |
| promises.push( | |
| fetch('https://graph.instagram.com/v1.0/media', { | |
| method: 'POST', | |
| body: igForm | |
| }).then(response => response.json()) | |
| .then(data => { | |
| if (data.error) throw new Error(data.error.message); | |
| return 'Instagram'; | |
| }) | |
| ); | |
| } | |
| // Wait for all posts to complete | |
| const settledResults = await Promise.allSettled(promises); | |
| // Check for errors | |
| const errors = settledResults | |
| .filter(result => result.status === 'rejected') | |
| .map(result => result.reason.message); | |
| if (errors.length > 0) { | |
| throw new Error(errors.join('\n')); | |
| } | |
| // Show success for successful platforms | |
| const successPlatforms = settledResults | |
| .filter(result => result.status === 'fulfilled') | |
| .map(result => result.value); | |
| alert(`Video successfully posted to: ${successPlatforms.join(', ')}`); | |
| } catch (error) { | |
| showError(`Posting failed:\n${error.message}`); | |
| } finally { | |
| // Reset button state | |
| postBtn.disabled = false; | |
| postBtn.innerHTML = '<i data-feather="share-2" class="mr-2"></i> Post Now'; | |
| feather.replace(); | |
| } | |
| }); | |
| function showError(message) { | |
| const errorDiv = document.createElement('div'); | |
| errorDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-4 py-2 rounded shadow-lg z-50'; | |
| errorDiv.textContent = message; | |
| document.body.appendChild(errorDiv); | |
| setTimeout(() => { | |
| errorDiv.classList.add('opacity-0', 'transition-opacity', 'duration-500'); | |
| setTimeout(() => errorDiv.remove(), 500); | |
| }, 3000); | |
| } | |
| function formatDuration(duration) { | |
| if (!duration || duration === 'N/A') return 'N/A'; | |
| try { | |
| // Convert ISO 8601 duration to readable format | |
| const match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); | |
| const hours = (match[1] ? parseInt(match[1]) : 0); | |
| const minutes = (match[2] ? parseInt(match[2]) : 0); | |
| const seconds = (match[3] ? parseInt(match[3]) : 0); | |
| return [ | |
| hours ? `${hours}h` : '', | |
| minutes ? `${minutes}m` : '', | |
| seconds ? `${seconds}s` : '' | |
| ].filter(Boolean).join(' '); | |
| } catch (e) { | |
| return duration; // Return raw duration if parsing fails | |
| } | |
| } | |
| // Helper functions | |
| function extractVideoId(url) { | |
| // Handle various YouTube URL formats including shorts | |
| const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=|shorts\/)([^#&?]*).*/; | |
| const match = url.match(regExp); | |
| return (match && match[2].length === 11) ? match[2] : null; | |
| } | |
| // Helper function to download video from YouTube | |
| async function downloadYouTubeVideo(videoId) { | |
| // Note: In a production app, this should be done on a backend server | |
| // due to YouTube's terms of service and CORS restrictions | |
| // This is just a placeholder implementation | |
| return new Promise((resolve) => { | |
| // Simulate download | |
| setTimeout(() => { | |
| const blob = new Blob(['Simulated video content'], { type: 'video/mp4' }); | |
| resolve(blob); | |
| }, 2000); | |
| }); | |
| } | |
| }); |