v2
This commit is contained in:
1 parent
b0d54efbea
commit
76e758339f
2 files changed
+276
-196
No files matched your search
@@ -1,23 +1,95 @@
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
import random
|
||||
from flask import Flask, request, jsonify, send_file, render_template
|
||||
import yt_dlp
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "downloads")
|
||||
CACHE_DIR = os.path.join(os.path.dirname(__file__), ".yt-dlp-cache")
|
||||
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||
os.makedirs(CACHE_DIR, exist_ok=True)
|
||||
|
||||
# Track job progress
|
||||
jobs = {}
|
||||
|
||||
AUDIO_FORMATS = ["mp3", "aac", "m4a", "opus", "flac", "wav", "vorbis", "alac"]
|
||||
VIDEO_FORMATS = ["mp4", "mkv", "webm", "mov", "avi", "flv"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-memory info cache — avoids hitting YouTube again for the same URL
|
||||
# within INFO_CACHE_TTL seconds (10 minutes).
|
||||
# ---------------------------------------------------------------------------
|
||||
_info_cache = {} # url -> {"data": {...}, "ts": float}
|
||||
_info_lock = threading.Lock()
|
||||
INFO_CACHE_TTL = 600 # seconds
|
||||
|
||||
def _cache_get(url):
|
||||
with _info_lock:
|
||||
entry = _info_cache.get(url)
|
||||
if entry and time.time() - entry["ts"] < INFO_CACHE_TTL:
|
||||
return entry["data"]
|
||||
return None
|
||||
|
||||
def _cache_set(url, data):
|
||||
with _info_lock:
|
||||
_info_cache[url] = {"data": data, "ts": time.time()}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rotate through realistic browser User-Agents so repeated requests don't
|
||||
# look like a single bot fingerprint to YouTube.
|
||||
# ---------------------------------------------------------------------------
|
||||
_USER_AGENTS = [
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15",
|
||||
]
|
||||
|
||||
def _random_ua():
|
||||
return random.choice(_USER_AGENTS)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Base yt-dlp options shared by all calls.
|
||||
#
|
||||
# • cachedir – persists solved JS sig/nsig to disk; node only re-runs
|
||||
# when YouTube rotates their player (every few days).
|
||||
# • sleep_interval /
|
||||
# max_sleep_interval– small random sleep between fragment requests;
|
||||
# makes traffic pattern look more human.
|
||||
# • http_chunk_size – stream in 10 MB chunks rather than one giant request;
|
||||
# reduces the chance of a mid-transfer 429.
|
||||
# • js_runtimes – use local node v20+ for JS challenge solving.
|
||||
# ---------------------------------------------------------------------------
|
||||
def _base_opts(extra=None):
|
||||
opts = {
|
||||
"cachedir": CACHE_DIR,
|
||||
"js_runtimes": {"node": {"executable": "/usr/bin/node"}},
|
||||
"http_headers": {"User-Agent": _random_ua()},
|
||||
"sleep_interval": 1,
|
||||
"max_sleep_interval": 3,
|
||||
"http_chunk_size": 10 * 1024 * 1024, # 10 MB
|
||||
"socket_timeout": 30,
|
||||
"retries": 6,
|
||||
"fragment_retries": 6,
|
||||
}
|
||||
if extra:
|
||||
opts.update(extra)
|
||||
return opts
|
||||
|
||||
|
||||
def sanitize_filename(name):
|
||||
return re.sub(r'[\\/*?:"<>|]', "_", name)
|
||||
|
||||
def run_download(job_id, url, fmt, quality):
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Background download worker
|
||||
# ---------------------------------------------------------------------------
|
||||
def run_download(job_id, url, fmt, chosen_format):
|
||||
jobs[job_id]["status"] = "downloading"
|
||||
jobs[job_id]["progress"] = 0
|
||||
|
||||
@@ -26,55 +98,44 @@ def run_download(job_id, url, fmt, quality):
|
||||
total = d.get("total_bytes") or d.get("total_bytes_estimate", 0)
|
||||
downloaded = d.get("downloaded_bytes", 0)
|
||||
if total:
|
||||
pct = int(downloaded / total * 100)
|
||||
jobs[job_id]["progress"] = pct
|
||||
jobs[job_id]["progress"] = int(downloaded / total * 100)
|
||||
jobs[job_id]["speed"] = d.get("_speed_str", "")
|
||||
jobs[job_id]["eta"] = d.get("_eta_str", "")
|
||||
elif d["status"] == "finished":
|
||||
jobs[job_id]["progress"] = 99
|
||||
|
||||
try:
|
||||
import shutil
|
||||
|
||||
common = {
|
||||
"progress_hooks": [progress_hook],
|
||||
"quiet": True,
|
||||
"extractor_args": {"youtube": {
|
||||
"js_runtimes": [f"node:/usr/bin/node"]
|
||||
}},
|
||||
}
|
||||
common = _base_opts({"progress_hooks": [progress_hook]})
|
||||
|
||||
if fmt == "audio":
|
||||
codec = chosen_format or "mp3"
|
||||
ydl_opts = {
|
||||
**common,
|
||||
"format": "bestaudio/best",
|
||||
"outtmpl": os.path.join(DOWNLOAD_DIR, f"{job_id}_%(title)s.%(ext)s"),
|
||||
"postprocessors": [{
|
||||
"key": "FFmpegExtractAudio",
|
||||
"preferredcodec": quality or "mp3",
|
||||
"preferredcodec": codec,
|
||||
"preferredquality": "192",
|
||||
}],
|
||||
}
|
||||
else:
|
||||
res = quality or "best"
|
||||
if res == "best":
|
||||
fmt_str = "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"
|
||||
else:
|
||||
h = res.replace("p", "")
|
||||
fmt_str = f"bestvideo[height<={h}][ext=mp4]+bestaudio[ext=m4a]/best[height<={h}][ext=mp4]/best"
|
||||
|
||||
video_fmt = chosen_format or "mp4"
|
||||
ydl_opts = {
|
||||
**common,
|
||||
"format": fmt_str,
|
||||
"format": "bestvideo+bestaudio/best",
|
||||
"outtmpl": os.path.join(DOWNLOAD_DIR, f"{job_id}_%(title)s.%(ext)s"),
|
||||
"merge_output_format": "mp4",
|
||||
"merge_output_format": video_fmt,
|
||||
"postprocessors": [{
|
||||
"key": "FFmpegVideoConvertor",
|
||||
"preferedformat": video_fmt,
|
||||
}],
|
||||
}
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(url, download=True)
|
||||
title = info.get("title", "video")
|
||||
|
||||
# Find the downloaded file
|
||||
files = [f for f in os.listdir(DOWNLOAD_DIR) if f.startswith(job_id)]
|
||||
if files:
|
||||
jobs[job_id]["status"] = "done"
|
||||
@@ -90,41 +151,45 @@ def run_download(job_id, url, fmt, quality):
|
||||
jobs[job_id]["error"] = str(e)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Routes
|
||||
# ---------------------------------------------------------------------------
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.route("/formats", methods=["GET"])
|
||||
def get_formats():
|
||||
return jsonify({"audio": AUDIO_FORMATS, "video": VIDEO_FORMATS})
|
||||
|
||||
|
||||
@app.route("/info", methods=["POST"])
|
||||
def get_info():
|
||||
data = request.get_json()
|
||||
url = data.get("url", "").strip()
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
# Serve from cache if still fresh — no YouTube request at all
|
||||
cached = _cache_get(url)
|
||||
if cached:
|
||||
return jsonify(cached)
|
||||
|
||||
try:
|
||||
import shutil
|
||||
node_bin = shutil.which("node") or shutil.which("nodejs") or "/usr/bin/node"
|
||||
ydl_opts = {
|
||||
"quiet": True,
|
||||
"skip_download": True,
|
||||
"extractor_args": {"youtube": {
|
||||
"js_runtimes": [f"node:{node_bin}"]
|
||||
}},
|
||||
}
|
||||
ydl_opts = _base_opts({"skip_download": True})
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(url, download=False)
|
||||
formats = info.get("formats", [])
|
||||
heights = sorted(set(
|
||||
f.get("height") for f in formats
|
||||
if f.get("height") and f.get("vcodec") != "none"
|
||||
), reverse=True)
|
||||
return jsonify({
|
||||
|
||||
result = {
|
||||
"title": info.get("title"),
|
||||
"thumbnail": info.get("thumbnail"),
|
||||
"duration": info.get("duration"),
|
||||
"uploader": info.get("uploader"),
|
||||
"resolutions": [f"{h}p" for h in heights[:6]],
|
||||
})
|
||||
}
|
||||
_cache_set(url, result)
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 400
|
||||
|
||||
@@ -134,7 +199,7 @@ def start_download():
|
||||
data = request.get_json()
|
||||
url = data.get("url", "").strip()
|
||||
fmt = data.get("format", "video")
|
||||
quality = data.get("quality", "best")
|
||||
chosen_format = data.get("chosen_format", None)
|
||||
|
||||
if not url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
@@ -142,9 +207,12 @@ def start_download():
|
||||
job_id = str(uuid.uuid4())[:8]
|
||||
jobs[job_id] = {"status": "queued", "progress": 0}
|
||||
|
||||
t = threading.Thread(target=run_download, args=(job_id, url, fmt, quality), daemon=True)
|
||||
t = threading.Thread(
|
||||
target=run_download,
|
||||
args=(job_id, url, fmt, chosen_format),
|
||||
daemon=True,
|
||||
)
|
||||
t.start()
|
||||
|
||||
return jsonify({"job_id": job_id})
|
||||
|
||||
|
||||
@@ -164,8 +232,14 @@ def download_file(job_id):
|
||||
filepath = os.path.join(DOWNLOAD_DIR, job["filename"])
|
||||
if not os.path.exists(filepath):
|
||||
return jsonify({"error": "File missing"}), 404
|
||||
return send_file(filepath, as_attachment=True, download_name=job["filename"].split("_", 1)[-1])
|
||||
return send_file(
|
||||
filepath,
|
||||
as_attachment=True,
|
||||
download_name=job["filename"].split("_", 1)[-1],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
||||
# use_reloader=False prevents the Werkzeug reloader from forking the
|
||||
# process and accidentally firing double requests during development.
|
||||
app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=False)
|
||||
+155
-149
@@ -84,6 +84,7 @@
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 28px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
input[type="text"] {
|
||||
@@ -94,17 +95,29 @@
|
||||
color: var(--text);
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
padding: 12px 14px;
|
||||
padding: 12px 42px 12px 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
input[type="text"]:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
input[type="text"]:focus { border-color: var(--accent); }
|
||||
input[type="text"]::placeholder { color: var(--muted); }
|
||||
|
||||
.url-spinner {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--border);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
display: none;
|
||||
}
|
||||
.url-spinner.active { display: block; }
|
||||
|
||||
.btn {
|
||||
font-family: 'Syne', sans-serif;
|
||||
font-weight: 700;
|
||||
@@ -118,29 +131,11 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.btn-ghost:hover { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
.btn-accent {
|
||||
background: var(--accent);
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.btn-accent { background: var(--accent); color: #000; }
|
||||
.btn-accent:hover { background: #d4eb3a; transform: translateY(-1px); }
|
||||
.btn-accent:active { transform: translateY(0); }
|
||||
.btn-accent:disabled { opacity: 0.4; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn-accent:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
/* Video info preview */
|
||||
#info-box {
|
||||
display: none;
|
||||
background: var(--bg);
|
||||
@@ -151,7 +146,6 @@
|
||||
gap: 14px;
|
||||
animation: fadeUp 0.3s ease both;
|
||||
}
|
||||
|
||||
#info-box.visible { display: flex; }
|
||||
|
||||
.thumb-wrap {
|
||||
@@ -162,12 +156,7 @@
|
||||
overflow: hidden;
|
||||
background: var(--border);
|
||||
}
|
||||
|
||||
.thumb-wrap img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.thumb-wrap img { width: 100%; height: 100%; object-fit: cover; }
|
||||
|
||||
.info-meta { flex: 1; min-width: 0; }
|
||||
|
||||
@@ -187,7 +176,6 @@
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* Format toggle */
|
||||
.format-toggle {
|
||||
display: flex;
|
||||
background: var(--bg);
|
||||
@@ -214,18 +202,12 @@
|
||||
justify-content: center;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.fmt-btn.active {
|
||||
background: var(--accent);
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.fmt-btn.active { background: var(--accent); color: #000; }
|
||||
.fmt-btn:not(.active):hover { color: var(--text); }
|
||||
|
||||
/* Quality selector */
|
||||
#quality-row { margin-bottom: 28px; }
|
||||
#format-row { margin-bottom: 28px; }
|
||||
|
||||
.quality-chips {
|
||||
.format-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
@@ -242,22 +224,13 @@
|
||||
color: var(--muted);
|
||||
transition: all 0.15s;
|
||||
background: transparent;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.chip.selected {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
background: rgba(232, 255, 71, 0.07);
|
||||
}
|
||||
|
||||
.chip.selected { border-color: var(--accent); color: var(--accent); background: rgba(232,255,71,0.07); }
|
||||
.chip:hover:not(.selected) { border-color: #444; color: var(--text); }
|
||||
|
||||
/* Progress */
|
||||
#progress-box {
|
||||
display: none;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
#progress-box { display: none; margin-bottom: 24px; }
|
||||
#progress-box.visible { display: block; }
|
||||
|
||||
.progress-bar-bg {
|
||||
@@ -284,7 +257,6 @@
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
/* Status messages */
|
||||
#status-msg {
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 0.72rem;
|
||||
@@ -293,30 +265,22 @@
|
||||
margin-bottom: 20px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#status-msg.error {
|
||||
background: rgba(255, 80, 80, 0.1);
|
||||
border: 1px solid rgba(255, 80, 80, 0.3);
|
||||
background: rgba(255,80,80,0.1);
|
||||
border: 1px solid rgba(255,80,80,0.3);
|
||||
color: #ff8080;
|
||||
display: block;
|
||||
}
|
||||
|
||||
#status-msg.success {
|
||||
background: rgba(232, 255, 71, 0.08);
|
||||
border: 1px solid rgba(232, 255, 71, 0.3);
|
||||
background: rgba(232,255,71,0.08);
|
||||
border: 1px solid rgba(232,255,71,0.3);
|
||||
color: var(--accent);
|
||||
display: block;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.action-row { display: flex; gap: 10px; justify-content: flex-end; }
|
||||
#download-btn-wrap { display: none; }
|
||||
|
||||
/* Spinner */
|
||||
.spin {
|
||||
display: inline-block;
|
||||
width: 12px; height: 12px;
|
||||
@@ -328,15 +292,8 @@
|
||||
}
|
||||
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
@keyframes fadeDown {
|
||||
from { opacity: 0; transform: translateY(-20px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes fadeUp {
|
||||
from { opacity: 0; transform: translateY(16px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes fadeDown { from { opacity:0; transform:translateY(-20px); } to { opacity:1; transform:translateY(0); } }
|
||||
@keyframes fadeUp { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } }
|
||||
|
||||
footer {
|
||||
margin-top: 48px;
|
||||
@@ -358,14 +315,12 @@
|
||||
|
||||
<div class="card">
|
||||
|
||||
<!-- URL Input -->
|
||||
<div class="section-label">Paste URL</div>
|
||||
<div class="url-row">
|
||||
<input type="text" id="url-input" placeholder="https://youtube.com/watch?v=..." />
|
||||
<button class="btn btn-ghost" onclick="fetchInfo()">Inspect</button>
|
||||
<input type="text" id="url-input" placeholder="https://youtube.com/watch?v=..." autocomplete="off" spellcheck="false" />
|
||||
<div class="url-spinner" id="url-spinner"></div>
|
||||
</div>
|
||||
|
||||
<!-- Video Info Preview -->
|
||||
<div id="info-box">
|
||||
<div class="thumb-wrap"><img id="thumb" src="" alt="thumb" /></div>
|
||||
<div class="info-meta">
|
||||
@@ -374,35 +329,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Status Message -->
|
||||
<div id="status-msg"></div>
|
||||
|
||||
<!-- Format Toggle -->
|
||||
<div class="section-label">Format</div>
|
||||
<div class="section-label">Type</div>
|
||||
<div class="format-toggle" id="fmt-toggle">
|
||||
<button class="fmt-btn active" data-fmt="video" onclick="setFormat('video')">
|
||||
<button class="fmt-btn active" data-fmt="video" onclick="setMediaType('video')">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="15" height="14" rx="2"/><polygon points="17 8 22 12 17 16 17 8"/></svg>
|
||||
Video
|
||||
</button>
|
||||
<button class="fmt-btn" data-fmt="audio" onclick="setFormat('audio')">
|
||||
<button class="fmt-btn" data-fmt="audio" onclick="setMediaType('audio')">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
|
||||
Audio Only
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Quality -->
|
||||
<div id="quality-row">
|
||||
<div class="section-label" id="quality-label">Resolution</div>
|
||||
<div class="quality-chips" id="quality-chips">
|
||||
<button class="chip selected" data-q="best">best</button>
|
||||
<button class="chip" data-q="1080p">1080p</button>
|
||||
<button class="chip" data-q="720p">720p</button>
|
||||
<button class="chip" data-q="480p">480p</button>
|
||||
<button class="chip" data-q="360p">360p</button>
|
||||
</div>
|
||||
<div id="format-row">
|
||||
<div class="section-label" id="format-label">Output Format</div>
|
||||
<div class="format-chips" id="format-chips"></div>
|
||||
</div>
|
||||
|
||||
<!-- Progress -->
|
||||
<div id="progress-box">
|
||||
<div class="section-label" id="progress-label">Downloading...</div>
|
||||
<div class="progress-bar-bg">
|
||||
@@ -414,7 +359,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="action-row">
|
||||
<div id="download-btn-wrap">
|
||||
<a id="dl-link" class="btn btn-accent" href="#">⬇ Save File</a>
|
||||
@@ -427,68 +371,121 @@
|
||||
<footer>yt-dlp + flask · for personal use only · respect copyright</footer>
|
||||
|
||||
<script>
|
||||
let selectedFormat = 'video';
|
||||
let selectedQuality = 'best';
|
||||
let selectedMediaType = 'video';
|
||||
let selectedOutputFormat = 'mp4';
|
||||
let pollTimer = null;
|
||||
let videoQualities = [];
|
||||
let debounceTimer = null;
|
||||
let currentFetchController = null; // lets us abort in-flight /info requests
|
||||
|
||||
const audioQualities = ['mp3', 'aac', 'm4a', 'opus', 'flac'];
|
||||
const videoDefaultChips = ['best', '1080p', '720p', '480p', '360p'];
|
||||
let availableFormats = { audio: [], video: [] };
|
||||
|
||||
function setFormat(fmt) {
|
||||
selectedFormat = fmt;
|
||||
document.querySelectorAll('.fmt-btn').forEach(b => b.classList.toggle('active', b.dataset.fmt === fmt));
|
||||
renderQualityChips();
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers to detect a recognisable video URL before bothering the server.
|
||||
// Covers youtube.com/watch, youtu.be, and common short-link patterns.
|
||||
// -------------------------------------------------------------------------
|
||||
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);
|
||||
}
|
||||
|
||||
function renderQualityChips(customList) {
|
||||
const label = document.getElementById('quality-label');
|
||||
const wrap = document.getElementById('quality-chips');
|
||||
const list = customList || (selectedFormat === 'audio' ? audioQualities : videoDefaultChips);
|
||||
label.textContent = selectedFormat === 'audio' ? 'Audio Format' : 'Resolution';
|
||||
const defaultQ = selectedFormat === 'audio' ? 'mp3' : 'best';
|
||||
selectedQuality = defaultQ;
|
||||
wrap.innerHTML = list.map(q =>
|
||||
`<button class="chip${q === defaultQ ? ' selected' : ''}" data-q="${q}" onclick="selectQuality(this,'${q}')">${q}</button>`
|
||||
// -------------------------------------------------------------------------
|
||||
// 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 selectQuality(el, q) {
|
||||
document.querySelectorAll('.chip').forEach(c => c.classList.remove('selected'));
|
||||
function selectFormat(el, f) {
|
||||
document.querySelectorAll('#format-chips .chip').forEach(c => c.classList.remove('selected'));
|
||||
el.classList.add('selected');
|
||||
selectedQuality = q;
|
||||
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')}`;
|
||||
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;
|
||||
el.textContent = msg; el.className = type;
|
||||
}
|
||||
|
||||
function clearStatus() {
|
||||
const el = document.getElementById('status-msg');
|
||||
el.className = '';
|
||||
el.textContent = '';
|
||||
el.className = ''; el.textContent = '';
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Auto-fetch video info
|
||||
//
|
||||
// Anti-throttle measures on the frontend side:
|
||||
// • Only fires when the URL matches a known video pattern — typing a URL
|
||||
// character by character won't trigger dozens of requests.
|
||||
// • 1200 ms debounce on typing (much longer than before).
|
||||
// • 400 ms debounce on paste (user pasted a complete URL, fire faster).
|
||||
// • Aborts any in-flight request before starting a new one, so rapidly
|
||||
// changing the URL never queues up multiple simultaneous /info calls.
|
||||
// • Backend caches results for 10 min, so navigating away and back is free.
|
||||
// -------------------------------------------------------------------------
|
||||
async function fetchInfo() {
|
||||
const url = document.getElementById('url-input').value.trim();
|
||||
if (!url) return;
|
||||
|
||||
if (!looksLikeVideoUrl(url)) {
|
||||
document.getElementById('info-box').classList.remove('visible');
|
||||
clearStatus();
|
||||
return;
|
||||
}
|
||||
|
||||
// Abort previous in-flight request
|
||||
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 })
|
||||
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 || '';
|
||||
@@ -497,21 +494,25 @@
|
||||
[data.uploader, fmtDuration(data.duration)].filter(Boolean).join(' · ');
|
||||
document.getElementById('info-box').classList.add('visible');
|
||||
|
||||
// Update video resolution chips from real data
|
||||
if (data.resolutions && data.resolutions.length) {
|
||||
videoQualities = ['best', ...data.resolutions];
|
||||
if (selectedFormat === 'video') renderQualityChips(videoQualities);
|
||||
}
|
||||
} catch(e) {
|
||||
showStatus('⚠ Could not reach server.', 'error');
|
||||
} 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();
|
||||
|
||||
// Abort any pending info fetch so it doesn't interfere
|
||||
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...';
|
||||
@@ -527,12 +528,12 @@
|
||||
const res = await fetch('/download', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ url, format: selectedFormat, quality: selectedQuality })
|
||||
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(e) {
|
||||
} catch {
|
||||
showStatus('⚠ Server error.', 'error');
|
||||
resetBtn();
|
||||
}
|
||||
@@ -542,13 +543,13 @@
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch('/status/' + jobId);
|
||||
const data = await res.json();
|
||||
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.speed) document.getElementById('prog-speed').textContent =
|
||||
data.speed + (data.eta ? ' · ETA ' + data.eta : '');
|
||||
}
|
||||
|
||||
if (data.status === 'done') {
|
||||
@@ -556,10 +557,9 @@
|
||||
document.getElementById('progress-label').textContent = 'Complete!';
|
||||
document.getElementById('prog-speed').textContent = '';
|
||||
showStatus('✓ Download ready: ' + (data.title || 'file'), 'success');
|
||||
const dlWrap = document.getElementById('download-btn-wrap');
|
||||
document.getElementById('dl-link').href = '/file/' + jobId;
|
||||
document.getElementById('dl-link').download = true;
|
||||
dlWrap.style.display = 'flex';
|
||||
document.getElementById('download-btn-wrap').style.display = 'flex';
|
||||
resetBtn();
|
||||
} else if (data.status === 'error') {
|
||||
clearInterval(pollTimer);
|
||||
@@ -567,22 +567,28 @@
|
||||
document.getElementById('progress-box').classList.remove('visible');
|
||||
resetBtn();
|
||||
}
|
||||
} catch(e) {
|
||||
// ignore transient poll errors
|
||||
}
|
||||
} catch { /* ignore transient poll errors */ }
|
||||
}, 800);
|
||||
}
|
||||
|
||||
function resetBtn() {
|
||||
const btn = document.getElementById('start-btn');
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = 'Download';
|
||||
btn.disabled = false; btn.innerHTML = 'Download';
|
||||
}
|
||||
|
||||
// Allow Enter key in URL input
|
||||
document.getElementById('url-input').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') fetchInfo();
|
||||
// Typing: long debounce + URL pattern guard = very few actual requests
|
||||
document.getElementById('url-input').addEventListener('input', () => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(fetchInfo, 1200);
|
||||
});
|
||||
|
||||
// Paste: user pasted a complete URL, fire faster
|
||||
document.getElementById('url-input').addEventListener('paste', () => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(fetchInfo, 400);
|
||||
});
|
||||
|
||||
loadFormats();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user