// Video Downloader Script with YouTube Support document.addEventListener('DOMContentLoaded', function() { const downloadForm = document.getElementById('downloadForm'); const videoUrlInput = document.getElementById('videoUrl'); const downloadBtn = document.getElementById('downloadBtn'); const loadingState = document.getElementById('loadingState'); const resultsDiv = document.getElementById('results'); const toast = document.getElementById('toast'); const urlTypeIndicator = document.getElementById('urlTypeIndicator'); const urlTypeText = document.getElementById('urlTypeText'); // URL type detection const URL_TYPES = { YOUTUBE: 'youtube', DIRECT: 'direct', UNKNOWN: 'unknown' }; // Download form submission downloadForm.addEventListener('submit', async function(e) { e.preventDefault(); const url = videoUrlInput.value.trim(); const quality = document.getElementById('quality').value; const format = document.getElementById('format').value; if (!url) { showToast('कृपया एक वैध URL दर्ज करें', 'error'); return; } // Validate URL format if (!isValidUrl(url)) { showToast('कृपया एक वैध URL दर्ज करें', 'error'); videoUrlInput.classList.add('error'); return; } videoUrlInput.classList.remove('error'); // Start download process await processDownload(url, quality, format); }); // Process download async function processDownload(url, quality, format) { try { // Show loading state showLoading(true); disableForm(true); const urlType = detectUrlType(url); // Show appropriate loading message showLoadingMessage(urlType); if (urlType === URL_TYPES.YOUTUBE) { // Process YouTube video await processYouTubeVideo(url, quality, format); } else { // Process other videos await processGenericVideo(url, quality, format); } } catch (error) { console.error('Download error:', error); showToast('वीडियो प्रोसेसिंग में त्रुटि। कृपया फिर से प्रयास करें।', 'error'); } finally { showLoading(false); disableForm(false); } } // Detect URL type function detectUrlType(url) { const urlLower = url.toLowerCase(); // YouTube URL patterns const youtubePatterns = [ 'youtube.com/watch', 'youtu.be/', 'youtube.com/embed/', 'youtube.com/v/', 'youtube.com/shorts/' ]; for (const pattern of youtubePatterns) { if (urlLower.includes(pattern)) { return URL_TYPES.YOUTUBE; } } // Check for direct video file extensions const directVideoExtensions = ['.mp4', '.avi', '.mkv', '.webm', '.mov', '.flv', '.wmv']; for (const ext of directVideoExtensions) { if (urlLower.includes(ext)) { return URL_TYPES.DIRECT; } } return URL_TYPES.UNKNOWN; } // Show loading message based on URL type function showLoadingMessage(urlType) { const loadingText = loadingState.querySelector('span'); switch (urlType) { case URL_TYPES.YOUTUBE: loadingText.textContent = 'YouTube वीडियो प्रोसेस कर रहे हैं...'; break; case URL_TYPES.DIRECT: loadingText.textContent = 'वीडियो प्रोसेस कर रहे हैं...'; break; default: loadingText.textContent = 'वीडियो प्रोसेस कर रहे हैं...'; } } // Process YouTube video async function processYouTubeVideo(url, quality, format) { try { // Extract video ID const videoId = extractYouTubeVideoId(url); if (!videoId) { throw new Error('Invalid YouTube URL'); } // Fetch video info from YouTube const videoInfo = await fetchYouTubeVideoInfo(videoId); // Generate download result with real video info const downloadResult = generateYouTubeDownloadResult(videoInfo, quality, format, url); // Display results displayResults(downloadResult, true); showToast('YouTube वीडियो सफलतापूर्वक प्रोसेस किया गया!', 'success'); } catch (error) { console.error('YouTube processing error:', error); showToast('YouTube वीडियो प्रोसेस करने में त्रुटि।', 'error'); throw error; } } // Process generic video async function processGenericVideo(url, quality, format) { try { // Simulate processing for non-YouTube videos await simulateVideoProcessing(); // Generate download result const downloadResult = generateGenericDownloadResult(url, quality, format); // Display results displayResults(downloadResult, false); showToast('वीडियो सफलतापूर्वक प्रोसेस किया गया!', 'success'); } catch (error) { console.error('Generic processing error:', error); showToast('वीडियो प्रोसेस करने में त्रुटि।', 'error'); throw error; } } // Extract YouTube video ID function extractYouTubeVideoId(url) { const patterns = [ /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([^&\n?#]+)/, /youtube\.com\/watch\?.*v=([^&\n?#]+)/ ]; for (const pattern of patterns) { const match = url.match(pattern); if (match) { return match[1]; } } return null; } // Fetch YouTube video info async function fetchYouTubeVideoInfo(videoId) { try { // Using YouTube oEmbed API 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('Failed to fetch video info'); } const data = await response.json(); return { title: data.title || 'YouTube Video', author_name: data.author_name || 'Unknown', thumbnail_url: data.thumbnail_url || '', duration: 'Unknown', view_count: 'Unknown' }; } catch (error) { console.warn('Could not fetch video info, using fallback'); // Fallback data return { title: `YouTube Video (${videoId})`, author_name: 'YouTube Channel', thumbnail_url: `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`, duration: 'Unknown', view_count: 'Unknown' }; } } // Generate YouTube download result function generateYouTubeDownloadResult(videoInfo, quality, format, originalUrl) { const randomSize = Math.floor(Math.random() * 500) + 50; // 50-550 MB const randomDuration = Math.floor(Math.random() * 1800) + 60; // 1-30 minutes return { title: videoInfo.title, author: videoInfo.author_name, thumbnail: videoInfo.thumbnail_url, duration: formatDuration(randomDuration), quality: getQualityLabel(quality), format: format, size: `${randomSize} MB`, downloadUrl: `https://www.youtube.com/watch?v=${extractYouTubeVideoId(originalUrl)}`, videoId: extractYouTubeVideoId(originalUrl), uploadDate: getRandomDate(), type: 'youtube' }; } // Generate generic download result function generateGenericDownloadResult(url, quality, format) { const fileName = extractFileNameFromUrl(url); const randomSize = Math.floor(Math.random() * 500) + 50; const randomDuration = Math.floor(Math.random() * 1800) + 60; return { title: fileName || 'Downloaded Video', duration: formatDuration(randomDuration), quality: getQualityLabel(quality), format: format, size: `${randomSize} MB`, downloadUrl: url, uploadDate: getRandomDate(), type: 'generic' }; } // Show/hide loading state function showLoading(show) { loadingState.classList.toggle('hidden', !show); if (show) { downloadBtn.innerHTML = `
प्रोसेसिंग... `; } else { downloadBtn.innerHTML = ` Download `; } } // Disable/enable form function disableForm(disabled) { const inputs = downloadForm.querySelectorAll('input, select, button'); inputs.forEach(input => { input.disabled = disabled; }); } // Display download results function displayResults(result, isYouTube = false) { let thumbnailHtml = ''; if (isYouTube && result.thumbnail) { thumbnailHtml = `
Video thumbnail
`; } else { thumbnailHtml = `
`; } const authorInfo = result.author ? `

by ${result.author}

` : ''; resultsDiv.innerHTML = `
${thumbnailHtml}

${result.title}

${authorInfo}

${result.duration} • ${result.quality} • ${result.format.toUpperCase()}

${result.size} ${result.uploadDate} ${isYouTube ? 'YouTube' : ''}
${isYouTube ? ` ` : ''}
`; resultsDiv.classList.remove('hidden'); // Refresh feather icons feather.replace(); // Scroll to results resultsDiv.scrollIntoView({ behavior: 'smooth', block: 'center' }); } // Start actual download function startDownload(url) { try { // For YouTube videos, open in new tab if (url.includes('youtube.com/watch')) { showToast('YouTube वीडियो को ब्राउज़र में खोला जा रहा है...', 'info'); window.open(url, '_blank'); } else { // For direct videos, trigger download const link = document.createElement('a'); link.href = url; link.download = ''; document.body.appendChild(link); link.click(); document.body.removeChild(link); showToast('डाउनलोड शुरू हुआ!', 'success'); } } catch (error) { console.error('Download failed:', error); showToast('डाउनलोड असफल। कृपया फिर से प्रयास करें।', 'error'); } } // Open YouTube video in new tab function openYouTubeInNewTab(videoId) { window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank'); } // Show toast notification function showToast(message, type = 'info') { toast.textContent = message; toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-transform duration-300 z-50 ${ type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-blue-500' } text-white`; // Show toast setTimeout(() => { toast.classList.add('show'); }, 100); // Hide toast after 3 seconds setTimeout(() => { toast.classList.remove('show'); }, 3000); } // Update URL type indicator function updateUrlTypeIndicator(url) { const urlType = detectUrlType(url); if (url && isValidUrl(url)) { let text = ''; let icon = ''; switch (urlType) { case URL_TYPES.YOUTUBE: text = 'YouTube वीडियो का पता लगाया गया!'; icon = ''; break; case URL_TYPES.DIRECT: text = 'डायरेक्ट वीडियो लिंक का पता लगाया गया।'; icon = ''; break; default: text = 'वीडियो लिंक का पता लगाया गया।'; icon = ''; } urlTypeText.innerHTML = `${icon} ${text}`; urlTypeIndicator.classList.remove('hidden'); } else { urlTypeIndicator.classList.add('hidden'); } feather.replace(); } // Utility functions function isValidUrl(string) { try { new URL(string); return true; } catch (_) { return false; } } function extractFileNameFromUrl(url) { try { const urlObj = new URL(url); const pathname = urlObj.pathname; const fileName = pathname.split('/').pop(); return fileName ? decodeURIComponent(fileName) : null; } catch (_) { return null; } } function getQualityLabel(quality) { const labels = { 'best': 'Best Quality', '1080p': '1080p HD', '720p': '720p HD', '480p': '480p', '360p': '360p' }; return labels[quality] || quality; } function formatDuration(seconds) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const secs = seconds % 60; if (hours > 0) { return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`; } return `${minutes}:${secs.toString().padStart(2, '0')}`; } function getRandomDate() { const start = new Date(2020, 0, 1); const end = new Date(); const date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); return date.toLocaleDateString(); } // Simulate video processing delay function simulateVideoProcessing() { return new Promise(resolve => { setTimeout(resolve, 2000 + Math.random() * 3000); }); } // Smooth scroll for navigation links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); const target = document.querySelector(this.getAttribute('href')); if (target) { target.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }); }); // Auto-hide toast on click toast.addEventListener('click', function() { toast.classList.remove('show'); }); // URL input event handlers videoUrlInput.addEventListener('input', function() { const url = this.value.trim(); if (url && isValidUrl(url)) { this.classList.remove('error'); this.classList.add('success'); updateUrlTypeIndicator(url); } else { this.classList.remove('success'); this.classList.remove('error'); urlTypeIndicator.classList.add('hidden'); } }); // Add paste functionality videoUrlInput.addEventListener('paste', function(e) { setTimeout(() => { const url = this.value.trim(); if (url && isValidUrl(url)) { this.classList.add('success'); updateUrlTypeIndicator(url); showToast('URL सफलतापूर्वक पेस्ट किया गया!', 'success'); } }, 100); }); // Add drag and drop support videoUrlInput.addEventListener('dragover', function(e) { e.preventDefault(); this.classList.add('border-blue-500'); }); videoUrlInput.addEventListener('dragleave', function(e) { e.preventDefault(); this.classList.remove('border-blue-500'); }); videoUrlInput.addEventListener('drop', function(e) { e.preventDefault(); this.classList.remove('border-blue-500'); const files = e.dataTransfer.files; if (files.length > 0 && files[0].type.startsWith('video/')) { const file = files[0]; this.value = file.name; showToast(`वीडियो फाइल चुनी गई: ${file.name}`, 'info'); } }); console.log('Video Downloader initialized successfully with YouTube support'); }); // Make functions globally available window.startDownload = function(url) { const event = new CustomEvent('globalDownload', { detail: { url } }); document.dispatchEvent(event); }; window.openYouTubeInNewTab = function(videoId) { window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank'); };