import os
import subprocess
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import threading
import re
# Configuration
DEFAULT_DOWNLOAD_DIR = os.path.expanduser("~/Downloads")
YTDLP_TOOL = "yt-dlp" # Assumes it's in PATH
CURL_TOOL = "curl" # Assumes it's in PATH
class DownloaderApp:
def __init__(self, root):
self.root = root
self.root.title("Universal Downloader")
self.root.geometry("600x500")
self.root.resizable(False, False)
# URL Input
tk.Label(root, text="Paste URL:").pack(pady=5)
self.url_entry = tk.Entry(root, width=70)
self.url_entry.pack(pady=5)
# Download Folder
tk.Label(root, text="Download Folder:").pack(pady=5)
self.download_dir = tk.StringVar(value=DEFAULT_DOWNLOAD_DIR)
self.dir_entry = tk.Entry(root, textvariable=self.download_dir, width=70)
self.dir_entry.pack(pady=5)
tk.Button(root, text="Browse", command=self.browse_folder).pack(pady=5)
# Options Frame (hidden until URL is checked)
self.options_frame = tk.Frame(root)
self.options_frame.pack(pady=10, fill=tk.X)
# Status Log
tk.Label(root, text="Status:").pack(pady=5)
self.status_text = scrolledtext.ScrolledText(root, height=10, width=70, state=tk.DISABLED)
self.status_text.pack(pady=5)
# Buttons
tk.Button(root, text="Check URL & Show Options", command=self.check_url).pack(pady=10)
tk.Button(root, text="Exit", command=root.quit).pack(pady=5)
self.download_options = None
self.is_youtube = False
def browse_folder(self):
folder = filedialog.askdirectory(initialdir=self.download_dir.get())
if folder:
self.download_dir.set(folder)
def check_url(self):
url = self.url_entry.get().strip()
if not url:
messagebox.showerror("Error", "URL cannot be empty!")
return
# Clear previous options
for widget in self.options_frame.winfo_children():
widget.destroy()
# Check if YouTube
self.is_youtube = bool(re.search(r"(youtube\.com|youtu\.be)", url, re.IGNORECASE))
if self.is_youtube:
self.show_youtube_options(url)
else:
self.show_generic_options(url)
def show_youtube_options(self, url):
tk.Label(self.options_frame, text="YouTube Options:").pack(pady=5)
options = [
("Highest Quality Video (up to 1080p)", "bestvideo[height<=1080]+bestaudio/best", "mp4", "--merge-output-format mp4"),
("Good Quality Video (up to 720p)", "bestvideo[height<=720]+bestaudio/best", "mp4", "--merge-output-format mp4"),
("Basic Quality Video (up to 480p)", "bestvideo[height<=480]+bestaudio/best", "mp4", "--merge-output-format mp4"),
("Audio Only (MP3)", "bestaudio", "mp3", "--extract-audio --audio-format mp3 --audio-quality 0")
]
self.download_options = tk.StringVar(value=options[0][0])
for label, format_str, ext, postprocess in options:
tk.Radiobutton(self.options_frame, text=label, variable=self.download_options, value=f"{format_str}|{ext}|{postprocess}").pack(anchor=tk.W)
tk.Button(self.options_frame, text="Download", command=lambda: self.start_download(url)).pack(pady=10)
def show_generic_options(self, url):
tk.Label(self.options_frame, text="Generic URL: Will download directly.").pack(pady=5)
tk.Button(self.options_frame, text="Download", command=lambda: self.start_download(url)).pack(pady=10)
def start_download(self, url):
download_dir = self.download_dir.get()
if not os.path.exists(download_dir):
messagebox.showerror("Error", "Download folder does not exist!")
return
# Run download in a separate thread to keep GUI responsive
threading.Thread(target=self.perform_download, args=(url, download_dir), daemon=True).start()
def perform_download(self, url, download_dir):
self.log("Starting download...")
try:
if self.is_youtube:
selected = self.download_options.get().split("|")
format_str, ext, postprocess = selected
output_template = os.path.join(download_dir, "%(title)s." + ext)
cmd = [YTDLP_TOOL, "-f", format_str] + postprocess.split() + ["--output", output_template, url]
else:
# Generic download with curl
filename = url.split("/")[-1] or "downloaded_file"
output_path = os.path.join(download_dir, filename)
cmd = [CURL_TOOL, "-L", "-o", output_path, url]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
while True:
output = process.stdout.readline()
if output:
self.log(output.strip())
if process.poll() is not None:
break
if process.returncode != 0:
error = process.stderr.read()
self.log(f"Error: {error}")
messagebox.showerror("Error", "Download failed! Check status log.")
else:
self.log("Download complete!")
messagebox.showinfo("Success", f"Downloaded to: {download_dir}")
except Exception as e:
self.log(f"Unexpected error: {str(e)}")
messagebox.showerror("Error", "An unexpected error occurred.")
def log(self, message):
self.status_text.config(state=tk.NORMAL)
self.status_text.insert(tk.END, message + "\n")
self.status_text.see(tk.END)
self.status_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = DownloaderApp(root)
root.mainloop()