videodownloader / script.js
BIKASHDAS7906's picture
kam nehi kar raha he bhai jo mang reha huwoo de hi nehi raha he youtube ka video donwload ka bat kar rha hu bhia yeh detect hi nehi kar pa rha he bhai me apna ekk youtube video ka link de rah ahu yeh lkoi dusra video dpownload kar de raha he
20b1b4a verified
// 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 = `
<div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
<span>प्रोसेसिंग...</span>
`;
} else {
downloadBtn.innerHTML = `
<i data-feather="youtube" class="w-5 h-5"></i>
<span>Download</span>
`;
}
}
// 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 = `
<div class="w-32 h-20 rounded-lg overflow-hidden">
<img src="${result.thumbnail}" alt="Video thumbnail" class="w-full h-full object-cover" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22128%22 height=%2272%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23f3f4f6%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%236b7280%22>Video</text></svg>'">
</div>
`;
} else {
thumbnailHtml = `
<div class="w-32 h-20 bg-gray-200 rounded-lg flex items-center justify-center">
<i data-feather="video" class="w-8 h-8 text-gray-400"></i>
</div>
`;
}
const authorInfo = result.author ? `<p class="text-gray-600 mb-1">by ${result.author}</p>` : '';
resultsDiv.innerHTML = `
<div class="download-card p-6 rounded-lg border-2 ${isYouTube ? 'border-red-200 bg-red-50' : ''}">
<div class="flex items-start space-x-4">
${thumbnailHtml}
<div class="flex-1">
<h4 class="text-lg font-semibold text-gray-800 mb-1">${result.title}</h4>
${authorInfo}
<p class="text-gray-600 mb-2">${result.duration}${result.quality}${result.format.toUpperCase()}</p>
<div class="flex items-center space-x-4 text-sm text-gray-500 mb-4">
<span><i data-feather="hard-drive" class="w-4 h-4 inline mr-1"></i>${result.size}</span>
<span><i data-feather="clock" class="w-4 h-4 inline mr-1"></i>${result.uploadDate}</span>
${isYouTube ? '<span class="bg-red-100 text-red-700 px-2 py-1 rounded text-xs font-medium">YouTube</span>' : ''}
</div>
<div class="space-y-2">
<button onclick="startDownload('${result.downloadUrl}')" class="btn-primary px-6 py-2 rounded-lg text-white font-medium flex items-center space-x-2 w-full justify-center">
<i data-feather="download" class="w-4 h-4"></i>
<span>Download ${result.format.toUpperCase()}</span>
</button>
${isYouTube ? `
<button onclick="openYouTubeInNewTab('${result.videoId}')" class="w-full px-6 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg font-medium flex items-center justify-center space-x-2 transition-colors">
<i data-feather="external-link" class="w-4 h-4"></i>
<span>Open in YouTube</span>
</button>
` : ''}
</div>
</div>
</div>
</div>
`;
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 = '<i data-feather="youtube" class="w-4 h-4"></i>';
break;
case URL_TYPES.DIRECT:
text = 'डायरेक्ट वीडियो लिंक का पता लगाया गया।';
icon = '<i data-feather="video" class="w-4 h-4"></i>';
break;
default:
text = 'वीडियो लिंक का पता लगाया गया।';
icon = '<i data-feather="link" class="w-4 h-4"></i>';
}
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');
};