Spaces:
Running
Running
File size: 14,614 Bytes
0b6a6b9 724c435 0b6a6b9 5ecd689 0b6a6b9 5ecd689 724c435 0b6a6b9 724c435 0b6a6b9 5ecd689 0b6a6b9 5ecd689 0b6a6b9 5ecd689 0b6a6b9 724c435 b80404d 724c435 b80404d 724c435 b80404d 9645fc3 5ecd689 9645fc3 5ecd689 9645fc3 724c435 9645fc3 5ecd689 724c435 5ecd689 724c435 b80404d 724c435 0b6a6b9 724c435 5ecd689 724c435 5ecd689 724c435 5ecd689 724c435 5ecd689 724c435 5ecd689 9645fc3 5ecd689 9645fc3 724c435 5ecd689 9645fc3 724c435 9645fc3 724c435 b80404d 5ecd689 724c435 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
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);
});
}
}); |