Files
VideoDownloader/static/app.js
T
2026-03-21 02:05:36 -03:00

208 lines
7.7 KiB
JavaScript

let selectedMediaType = 'video';
let selectedOutputFormat = 'mp4';
let pollTimer = null;
let debounceTimer = null;
let currentFetchController = null;
let availableFormats = { audio: [], video: [] };
// ---------------------------------------------------------------------------
// Only fire /info when the input looks like a real supported URL.
// ---------------------------------------------------------------------------
const URL_RE = /^https?:\/\/(www\.)?(youtube\.com\/(watch|shorts|live)|youtu\.be|vimeo\.com|dailymotion\.com|twitch\.tv|soundcloud\.com)/i;
function looksLikeVideoUrl(str) {
try { new URL(str); } catch { return false; }
return URL_RE.test(str);
}
// ---------------------------------------------------------------------------
// Format chips
// ---------------------------------------------------------------------------
async function loadFormats() {
try {
const res = await fetch('/formats');
availableFormats = await res.json();
} catch {
availableFormats = {
audio: ['mp3','aac','m4a','opus','flac','wav','vorbis','alac'],
video: ['mp4','mkv','webm','mov','avi','flv'],
};
}
renderFormatChips();
}
function setMediaType(type) {
selectedMediaType = type;
document.querySelectorAll('.fmt-btn').forEach(b => b.classList.toggle('active', b.dataset.fmt === type));
renderFormatChips();
}
function renderFormatChips() {
const list = selectedMediaType === 'audio' ? availableFormats.audio : availableFormats.video;
const def = list[0] || (selectedMediaType === 'audio' ? 'mp3' : 'mp4');
selectedOutputFormat = def;
document.getElementById('format-chips').innerHTML = list.map(f =>
`<button class="chip${f === def ? ' selected' : ''}" onclick="selectFormat(this,'${f}')">${f}</button>`
).join('');
}
function selectFormat(el, f) {
document.querySelectorAll('#format-chips .chip').forEach(c => c.classList.remove('selected'));
el.classList.add('selected');
selectedOutputFormat = f;
}
// ---------------------------------------------------------------------------
// UI helpers
// ---------------------------------------------------------------------------
function fmtDuration(s) {
if (!s) return '';
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
return h
? `${h}:${String(m).padStart(2,'0')}:${String(sec).padStart(2,'0')}`
: `${m}:${String(sec).padStart(2,'0')}`;
}
function showStatus(msg, type) {
const el = document.getElementById('status-msg');
el.textContent = msg; el.className = type;
}
function clearStatus() {
const el = document.getElementById('status-msg');
el.className = ''; el.textContent = '';
}
// ---------------------------------------------------------------------------
// Auto-fetch video info (debounced, abortable, URL-guarded)
// ---------------------------------------------------------------------------
async function fetchInfo() {
const url = document.getElementById('url-input').value.trim();
if (!looksLikeVideoUrl(url)) {
document.getElementById('info-box').classList.remove('visible');
clearStatus();
return;
}
if (currentFetchController) currentFetchController.abort();
currentFetchController = new AbortController();
clearStatus();
document.getElementById('info-box').classList.remove('visible');
document.getElementById('url-spinner').classList.add('active');
try {
const res = await fetch('/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
signal: currentFetchController.signal,
});
const data = await res.json();
if (data.error) { showStatus('⚠ ' + data.error, 'error'); return; }
document.getElementById('thumb').src = data.thumbnail || '';
document.getElementById('vid-title').textContent = data.title || 'Unknown';
document.getElementById('vid-meta').textContent =
[data.uploader, fmtDuration(data.duration)].filter(Boolean).join(' · ');
document.getElementById('info-box').classList.add('visible');
} catch (e) {
if (e.name !== 'AbortError') showStatus('⚠ Could not reach server.', 'error');
} finally {
document.getElementById('url-spinner').classList.remove('active');
}
}
// ---------------------------------------------------------------------------
// Download
// ---------------------------------------------------------------------------
async function startDownload() {
const url = document.getElementById('url-input').value.trim();
if (!url) { showStatus('⚠ Please enter a URL.', 'error'); return; }
clearStatus();
if (currentFetchController) { currentFetchController.abort(); currentFetchController = null; }
document.getElementById('url-spinner').classList.remove('active');
const btn = document.getElementById('start-btn');
btn.disabled = true;
btn.innerHTML = '<span class="spin"></span> Starting...';
document.getElementById('download-btn-wrap').style.display = 'none';
document.getElementById('progress-box').classList.add('visible');
document.getElementById('progress-label').textContent = 'Downloading...';
document.getElementById('progress-fill').style.width = '0%';
document.getElementById('prog-pct').textContent = '0%';
document.getElementById('prog-speed').textContent = '';
try {
const res = await fetch('/download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url, format: selectedMediaType, chosen_format: selectedOutputFormat }),
});
const data = await res.json();
if (data.error) { showStatus('⚠ ' + data.error, 'error'); resetBtn(); return; }
pollStatus(data.job_id);
} catch {
showStatus('⚠ Server error.', 'error');
resetBtn();
}
}
function pollStatus(jobId) {
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(async () => {
try {
const data = await (await fetch('/status/' + jobId)).json();
if (data.progress !== undefined) {
document.getElementById('progress-fill').style.width = data.progress + '%';
document.getElementById('prog-pct').textContent = data.progress + '%';
if (data.speed) document.getElementById('prog-speed').textContent =
data.speed + (data.eta ? ' · ETA ' + data.eta : '');
}
if (data.status === 'done') {
clearInterval(pollTimer);
document.getElementById('progress-label').textContent = 'Complete!';
document.getElementById('prog-speed').textContent = '';
showStatus('✓ Download ready: ' + (data.title || 'file'), 'success');
document.getElementById('dl-link').href = '/file/' + jobId;
document.getElementById('dl-link').download = true;
document.getElementById('download-btn-wrap').style.display = 'flex';
resetBtn();
} else if (data.status === 'error') {
clearInterval(pollTimer);
showStatus('⚠ ' + (data.error || 'Unknown error'), 'error');
document.getElementById('progress-box').classList.remove('visible');
resetBtn();
}
} catch { /* ignore transient poll errors */ }
}, 800);
}
function resetBtn() {
const btn = document.getElementById('start-btn');
btn.disabled = false; btn.innerHTML = 'Download';
}
// ---------------------------------------------------------------------------
// Event listeners
// ---------------------------------------------------------------------------
document.getElementById('url-input').addEventListener('input', () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(fetchInfo, 1200);
});
document.getElementById('url-input').addEventListener('paste', () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(fetchInfo, 400);
});
loadFormats();