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 = ' 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 = ' ¡Descarga Completada!'; } function resetForm() { document.getElementById('downloadBtn').disabled = false; document.getElementById('downloadBtn').innerHTML = ' 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 = `
No hay descargas aún