Files
youtube-downloader/static/js/app.js
renato97 c20b40b57c 🎉 Inicializar YouTube Downloader Dashboard
-  Dashboard web moderno con Flask y Bootstrap 5
-  Descarga de videos en formato MP3 y MP4
-  Configuración optimizada de yt-dlp para evitar errores 403
-  Progreso en tiempo real con velocidad y ETA
-  Soporte Docker con docker-compose
-  Script de despliegue automático
-  API REST para integraciones
-  Manejo robusto de errores con reintentos
-  Limpieza automática de archivos temporales
-  README detallado con instrucciones de uso

🚀 Funciona con YouTube y está listo para producción 24/7

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-10 15:03:45 +00:00

269 lines
8.7 KiB
JavaScript

let currentDownloadId = null;
let progressInterval = null;
document.addEventListener('DOMContentLoaded', function() {
loadDownloads();
document.getElementById('downloadForm').addEventListener('submit', function(e) {
e.preventDefault();
startDownload();
});
});
function startDownload() {
const url = document.getElementById('url').value.trim();
const format = document.querySelector('input[name="format"]:checked').value;
if (!url) {
showError('Por favor, ingresa una URL válida de YouTube');
return;
}
// Show progress section
document.getElementById('progressSection').style.display = 'block';
document.getElementById('downloadBtn').disabled = true;
document.getElementById('downloadBtn').innerHTML = '<i class="fas fa-spinner fa-spin"></i> Descargando...';
// Reset progress
updateProgress({
status: 'starting',
progress: 0,
speed: '',
eta: '',
filename: ''
});
// Start download
fetch('/api/downloads', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
url: url,
format: format
})
})
.then(response => response.json())
.then(data => {
if (data.error) {
showError(data.error);
resetForm();
} else {
currentDownloadId = data.download_id;
checkProgress();
}
})
.catch(error => {
console.error('Error:', error);
showError('Error al iniciar la descarga');
resetForm();
});
}
function checkProgress() {
if (!currentDownloadId) return;
let retryCount = 0;
const maxRetries = 3;
progressInterval = setInterval(() => {
fetch(`/api/status/${currentDownloadId}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then(data => {
if (data.error) {
showError(data.error);
resetForm();
return;
}
retryCount = 0; // Reset retry count on successful response
updateProgress(data);
if (data.complete) {
clearInterval(progressInterval);
showSuccess();
resetForm();
loadDownloads();
} else if (data.status === 'error') {
clearInterval(progressInterval);
showError(data.error || 'Error en la descarga');
resetForm();
}
})
.catch(error => {
console.error('Error checking progress:', error);
retryCount++;
if (retryCount >= maxRetries) {
clearInterval(progressInterval);
showError('Error de conexión. Verifica tu internet e intenta nuevamente.');
resetForm();
}
});
}, 2000); // Check every 2 seconds instead of 1
}
function updateProgress(data) {
const progressBar = document.getElementById('progressBar');
const speed = document.getElementById('speed');
const eta = document.getElementById('eta');
const filename = document.getElementById('filename');
const errorMessage = document.getElementById('errorMessage');
progressBar.style.width = data.progress + '%';
progressBar.textContent = data.progress + '%';
speed.textContent = data.speed || '-';
eta.textContent = data.eta || '-';
if (data.filename) {
const name = data.filename.split('/').pop();
filename.textContent = name;
filename.title = name;
}
if (data.error) {
errorMessage.textContent = data.error;
errorMessage.style.display = 'block';
} else {
errorMessage.style.display = 'none';
}
}
function showError(message) {
const errorMessage = document.getElementById('errorMessage');
errorMessage.textContent = message;
errorMessage.style.display = 'block';
}
function showSuccess() {
const progressSection = document.getElementById('progressSection');
progressSection.querySelector('.card-header h5').innerHTML =
'<i class="fas fa-check-circle text-success"></i> ¡Descarga Completada!';
}
function resetForm() {
document.getElementById('downloadBtn').disabled = false;
document.getElementById('downloadBtn').innerHTML = '<i class="fas fa-download"></i> Descargar';
setTimeout(() => {
document.getElementById('progressSection').style.display = 'none';
document.getElementById('url').value = '';
currentDownloadId = null;
}, 3000);
}
// Limpiar interval al perder focus de la ventana
document.addEventListener('visibilitychange', function() {
if (document.hidden && progressInterval) {
clearInterval(progressInterval);
progressInterval = null;
}
});
function loadDownloads() {
fetch('/api/downloads')
.then(response => response.json())
.then(downloads => {
const downloadsList = document.getElementById('downloadsList');
let headerHtml = '';
if (downloads.length > 0) {
headerHtml = `
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="mb-0">${downloads.length} archivo(s)</h6>
<button class="btn btn-outline-secondary btn-sm" onclick="cleanupDownloads()">
<i class="fas fa-broom"></i> Limpiar
</button>
</div>
`;
}
if (downloads.length === 0) {
downloadsList.innerHTML = `
${headerHtml}
<div class="text-center text-muted">
<i class="fas fa-inbox fa-3x mb-3"></i>
<p>No hay descargas aún</p>
</div>
`;
return;
}
downloadsList.innerHTML = `
${headerHtml}
${downloads.map(download => `
<div class="download-item">
<div class="row align-items-center">
<div class="col-md-8">
<h6 class="mb-1">
<i class="fas fa-file-${getFileIcon(download.filename)}"></i>
${download.filename}
</h6>
<small class="text-muted">
${formatFileSize(download.size)}${download.modified}
</small>
</div>
<div class="col-md-4 text-end">
<a href="${download.url}" class="btn btn-primary btn-sm">
<i class="fas fa-download"></i> Descargar
</a>
</div>
</div>
</div>
`).join('')}
`;
})
.catch(error => {
console.error('Error loading downloads:', error);
});
}
function getFileIcon(filename) {
if (filename.endsWith('.mp3')) return 'audio';
if (filename.endsWith('.mp4')) return 'video';
if (filename.endsWith('.webm')) return 'video';
if (filename.endsWith('.m4a')) return 'audio';
return 'alt';
}
function cleanupDownloads() {
if (confirm('¿Eliminar archivos temporales y descargas antiguas?')) {
fetch('/api/cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert('Error: ' + data.error);
} else {
alert(`Se eliminaron ${data.cleaned_files} archivos y ${data.cleaned_downloads} estados de descarga.`);
loadDownloads();
}
})
.catch(error => {
console.error('Error cleaning up:', error);
alert('Error al limpiar archivos');
});
}
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Auto-refresh downloads list every 30 seconds
setInterval(loadDownloads, 30000);