- Agregar funciones check_ffmpeg() y install_ffmpeg() para detectar e instalar FFmpeg - Implementar verificación previa a descargas MP3 para asegurar disponibilidad de FFmpeg - Crear endpoints /api/ffmpeg/status y /api/ffmpeg/install para gestión de FFmpeg - Mejorar frontend con detección de estado de FFmpeg y opción de instalación automática - Deshabilitar opción MP3 si FFmpeg no está disponible - Añadir mensajes de error específicos para problemas de FFmpeg 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
346 lines
12 KiB
JavaScript
346 lines
12 KiB
JavaScript
let currentDownloadId = null;
|
|
let progressInterval = null;
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
loadDownloads();
|
|
checkFFmpegStatus();
|
|
|
|
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];
|
|
}
|
|
|
|
function checkFFmpegStatus() {
|
|
fetch('/api/ffmpeg/status')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
const mp3Option = document.querySelector('input[value="mp3"]');
|
|
const mp3Label = document.querySelector('label[for="mp3"]');
|
|
|
|
if (!data.available) {
|
|
// MP3 option is not available
|
|
mp3Option.disabled = true;
|
|
mp3Label.style.opacity = '0.5';
|
|
mp3Label.style.cursor = 'not-allowed';
|
|
|
|
// Add warning indicator
|
|
if (!document.getElementById('ffmpegWarning')) {
|
|
const warning = document.createElement('div');
|
|
warning.id = 'ffmpegWarning';
|
|
warning.className = 'alert alert-warning alert-sm mt-2';
|
|
warning.innerHTML = `
|
|
<i class="fas fa-exclamation-triangle"></i>
|
|
FFmpeg no está disponible. Las descargas de MP3 requieren FFmpeg.
|
|
<button class="btn btn-sm btn-outline-warning ms-2" onclick="installFFmpeg()">
|
|
<i class="fas fa-download"></i> Instalar FFmpeg
|
|
</button>
|
|
`;
|
|
mp3Label.parentNode.insertBefore(warning, mp3Label.parentNode.nextSibling);
|
|
|
|
// Switch to MP4 by default
|
|
document.querySelector('input[value="mp4"]').checked = true;
|
|
}
|
|
} else {
|
|
// FFmpeg is available
|
|
if (document.getElementById('ffmpegWarning')) {
|
|
document.getElementById('ffmpegWarning').remove();
|
|
}
|
|
mp3Option.disabled = false;
|
|
mp3Label.style.opacity = '1';
|
|
mp3Label.style.cursor = 'pointer';
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error checking FFmpeg status:', error);
|
|
});
|
|
}
|
|
|
|
function installFFmpeg() {
|
|
const btn = document.querySelector('#ffmpegWarning button');
|
|
const originalContent = btn.innerHTML;
|
|
btn.disabled = true;
|
|
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Instalando...';
|
|
|
|
fetch('/api/ffmpeg/install', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success) {
|
|
alert('✅ ' + data.message);
|
|
checkFFmpegStatus(); // Recheck status
|
|
} else {
|
|
alert('❌ ' + data.message);
|
|
btn.disabled = false;
|
|
btn.innerHTML = originalContent;
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error installing FFmpeg:', error);
|
|
alert('Error al intentar instalar FFmpeg: ' + error.message);
|
|
btn.disabled = false;
|
|
btn.innerHTML = originalContent;
|
|
});
|
|
}
|
|
|
|
// Auto-refresh downloads list every 30 seconds
|
|
setInterval(loadDownloads, 30000); |