commit 8a4fb0c79cdbef49f65702c3874fbd4b19b0d236 Author: LilDosto Date: Tue Oct 27 20:55:29 2026 +0300 LDownloader v2.0: initial release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67c9480 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# PyInstaller & Build outputs +build/ +dist/ + +# Python temporary and cache files +__pycache__/ +*.pyc +*.pyo +*.pyd + +# Runtime logs and cookies +temp.txt +cookies.txt +github-recovery-codes.txt + +# OS specific files +.DS_Store +Thumbs.db + +# Redundant local logs and utilities +yapilan_islemler.txt +ytdlp.bat +make_icon.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..fe8e0ba --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# LDownloader 🎬🎵 v2.0 PRO + +**LDownloader**, Python, Tkinter ve `yt-dlp` tabanlı, koyu temalı bir Windows masaüstü video ve ses indirme uygulamasıdır. Kullanılabilir platformlar ve formatlar, kaynak içeriğe ve `yt-dlp` desteğine bağlıdır. + +![LDownloader Logo](logo.png) + +--- + +## ✨ Öne Çıkan Özellikler + +### 1. 🔍 Akıllı Video Önizleme & Dinamik Çözünürlük Tespiti +* Bir video bağlantısı yapıştırıldığında arka planda video başlığı, yayıncı kanal adı, video süresi ve kapak resmi (thumbnail) otomatik olarak çekilir. +* Sabit çözünürlük tahminleri yerine, videoda **gerçekte bulunan tüm çözünürlük seçenekleri** (4K, 2K, 1080p, 720p vb.) algılanıp seçim menüsüne eklenir. + +### 2. ⚡ 1-Tıkla Otomatik FFmpeg & yt-dlp Kurucusu +* Sisteminizde `ffmpeg` veya `yt-dlp` yoksa **Ayarlar** sekmesinden bunları indirebilirsiniz. +* İndirilen araçlar uygulamanın kullanıcı veri klasöründeki `bin/` dizinine kaydedilir; Windows PATH ayarını değiştirmeniz gerekmez. İndirme için internet bağlantısı gerekir. + +### 3. 📦 Toplu İndirme (Batch Downloader) +* İndirmek istediğiniz birden çok video veya ses bağlantısını alt alta yapıştırın. +* Sıralı indirme kuyruğu her bir öğenin durumunu (Bekliyor / İndiriliyor / Tamamlandı / Hata) anlık olarak takip eder. + +### 4. 🕒 İndirme Geçmişi & Dosya Yöneticisi +* Tekil ve toplu indirme kayıtları tarih, dosya boyutu ve format bilgisiyle yerel olarak saklanır. Oynatma listesi işlemi şu anda tek bir geçmiş kaydı oluşturur. +* 📁 **Klasörde Göster**: Windows Gezgini'ni açıp doğrudan dosyayı seçili olarak görüntüler (`explorer /select`). +* ▶ **Oynat / Aç**: Varsayılan medya oynatıcınızda videoyu veya müziği anında başlatır. + +### 5. 🚀 Çok Parçalı İndirme +* İsteğe bağlı çok parçalı indirme, desteklenen akışlarda indirme hızını artırabilir. Gerçek performans ağınıza ve kaynak platforma bağlıdır; belirli bir hız artışı garanti edilmez. + +### 6. 💬 Altyazı & 🖼️ Kapak Resmi Gömme +* **Altyazı Desteği**: İstenirse Türkçe ve İngilizce altyazılar indirilip, FFmpeg'in desteklediği durumlarda videoya gömülür. +* **Kapak Resmi ve Metadata**: İsteğe bağlı olarak kapak görseli ve metadata, desteklenen formatlara eklenir. + +### 7. 🍪 Zen Browser & Modern Çerez (Cookies) Yönetimi +* Yaş kısıtlamalı, gizli veya YouTube 403 engeline takılan videolarda oturum çerezlerinizi tek tıkla aktarın: + * **Desteklenen tarayıcı seçenekleri**: Zen Browser, Firefox, Chrome, Microsoft Edge, Brave, Opera, Vivaldi, Chromium. Tarayıcı sürümü, profil konumu ve işletim sistemi izinleri nedeniyle doğrudan çerez aktarımı her sistemde çalışmayabilir. + * İsteğe bağlı manuel `cookies.txt` yükleme desteği. + +### 8. 📋 Gelişmiş Playlist İndirme +* Oynatma listelerini sıralı klasör yapısıyla (`Playlist Adı / 01 - Video.mp4`) kaydeder. +* Başlangıç ve bitiş indeks aralığı belirleyebilir, hatalı/gizli videoları atlayarak indirmeye devam edebilirsiniz. + +--- + +## 📁 Proje Mimarisi + +``` +LDownloader/ +├── core/ # İş mantığı ve arka plan motorları +│ ├── config.py # Kalıcı kullanıcı ayarları (config.json) +│ ├── dependencies.py # yt-dlp & FFmpeg algılama, 1-tıkla indirme/kurma +│ ├── downloader.py # Asenkron indirme motoru ve süreç ağacı yönetimi +│ ├── metadata.py # Hızlı video önizleme, thumbnail ve format ayrıştırıcı +│ ├── diagnostics.py # Akıllı Türkçe hata teşhisi ve çözüm motoru +│ └── history.py # İndirme geçmişi (history.json) +├── ui/ # Arayüz bileşenleri ve modern tasarım +│ ├── theme.py # SaaS koyu mod renk paleti ve stilleri +│ ├── components.py # Modern kartlar, butonlar, giriş alanları, önizleme kartı +│ ├── tabs/ +│ │ ├── single_tab.py # Önizlemeli tekil indirme sekmesi +│ │ ├── playlist_tab.py # Oynatma listesi sekmesi +│ │ ├── batch_tab.py # Toplu indirme sekmesi +│ │ ├── history_tab.py # İndirme geçmişi sekmesi +│ │ └── settings_tab.py # Ayarlar, çerezler ve bağımlılık yöneticisi +│ └── app.py # Ana pencere ve sekme orkestrasyonu +├── ytdlp_gui.pyw # Ana çalıştırma dosyası (Geriye dönük %100 uyumlu) +├── main.py # Alternatif çalıştırma noktası +├── ytdlp_indirici.spec # PyInstaller derleme yapılandırması +├── build_exe.bat # Tek tıkla Windows EXE derleme aracı +├── requirements.txt # Python bağımlılıkları +├── logo.ico / logo.png # Görsel ikonlar +└── README.md # Dokümantasyon +``` + +--- + +## 🚀 Kurulum ve Çalıştırma + +### Gizlilik ve kullanım +* Çerezler hesabınıza erişim sağlayabilir. Yalnızca kendi hesabınızın çerezlerini kullanın; çerez dosyalarını veya uygulama tanılama kayıtlarını başkalarıyla paylaşmayın. +* İndirilen içerikleri kullanırken ilgili platformların hizmet koşullarına, içerik sahiplerinin haklarına ve yerel mevzuata uyun. Uygulama, bir içeriği indirme veya yeniden kullanma hakkı vermez. +* Harici araçlar ve medya içeriği internetten indirilir. İndirme ve kurulum işlemleri güvenilir bir ağ üzerinden yapılmalıdır. + +### 1. Gereksinimleri Yükleyin: +```bash +pip install -r requirements.txt +``` + +### 2. Uygulamayı Başlatın: +```bash +python ytdlp_gui.pyw +``` +*(veya `python main.py`)* + +--- + +## 🛠️ Tek Tıkla EXE Olarak Derleme + +Uygulamayı tek bir Windows `.exe` dosyası haline getirmek için: +* `build_exe.bat` dosyasına çift tıklayın veya terminalden çalıştırın: +```bash +pyinstaller --noconfirm ytdlp_indirici.spec +``` +Oluşturulan taşınabilir dosya `dist/LDownloader.exe` konumunda yer alacaktır. + +--- + +## 📝 Lisans ve Katkı + +Bu proje açık kaynaklıdır. Hata bildirimleri veya yeni özellik önerileri için Pull Request gönderebilir veya Issue oluşturabilirsiniz. + +İyi indirmeler! 🚀 diff --git a/build_exe.bat b/build_exe.bat new file mode 100644 index 0000000..5069385 --- /dev/null +++ b/build_exe.bat @@ -0,0 +1,30 @@ +@echo off +chcp 65001 > nul +echo ======================================================== +echo LDownloader v2.0 - PyInstaller Derleme Araci +echo ======================================================== +echo. + +python -m pip install -r requirements.txt +if %ERRORLEVEL% NEQ 0 ( + echo [HATA] Bagimliliklar yuklenemedi! + pause + exit /b 1 +) + +echo. +echo [*] EXE paketi olusturuluyor... +pyinstaller --noconfirm ytdlp_indirici.spec + +if %ERRORLEVEL% EQU 0 ( + echo. + echo ======================================================== + echo [BASARILI] Derleme tamamlandi! + echo Calistirilabilir dosya: dist\LDownloader.exe + echo ======================================================== +) else ( + echo. + echo [HATA] PyInstaller derleme sirasinda hata olustu! +) + +pause diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..8a41def --- /dev/null +++ b/core/__init__.py @@ -0,0 +1 @@ +"""LDownloader Core Modules""" diff --git a/core/config.py b/core/config.py new file mode 100644 index 0000000..e601b2d --- /dev/null +++ b/core/config.py @@ -0,0 +1,106 @@ +import os +import sys +import json +import logging + +logger = logging.getLogger(__name__) + +def get_app_dir(): + """PyInstaller veya kaynak kod dizini.""" + if getattr(sys, 'frozen', False): + return getattr(sys, '_MEIPASS', os.path.dirname(sys.executable)) + return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +def get_data_dir(): + """Kullanıcı verilerinin ve ayarların saklandığı dizin.""" + app_data = os.getenv('APPDATA') + if app_data: + data_dir = os.path.join(app_data, 'LDownloader') + else: + data_dir = os.path.join(os.path.expanduser('~'), '.ldownloader') + os.makedirs(data_dir, exist_ok=True) + return data_dir + +def get_bin_dir(): + """Taşınabilir yt-dlp.exe ve ffmpeg.exe ikililerinin saklandığı dizin.""" + # Öncelik 1: Uygulama çalışma dizinindeki bin/ + local_bin = os.path.join(get_app_dir(), 'bin') + if os.path.exists(local_bin): + return local_bin + + # Öncelik 2: AppData altındaki bin/ + user_bin = os.path.join(get_data_dir(), 'bin') + os.makedirs(user_bin, exist_ok=True) + return user_bin + + +class ConfigManager: + _DEFAULT_CONFIG = { + "theme": "dark", + "download_dir": os.path.join(os.path.expanduser("~"), "Downloads"), + "video_format": "mp4", + "video_quality": "Best Quality (En İyi)", + "audio_format": "mp3", + "audio_quality": "Best Quality (En İyi)", + "cookies_mode": "none", + "cookies_browser": "chrome", + "cookies_path": "", + "embed_subtitles": False, + "subtitle_lang": "tr,en", + "embed_thumbnail": True, + "add_metadata": True, + "concurrent_fragments": 4, + "auto_fetch_metadata": True, + "speed_limit": "", + "proxy": "", + "ignore_errors": True + } + + def __init__(self): + self.config_path = os.path.join(get_data_dir(), "config.json") + self.config = dict(self._DEFAULT_CONFIG) + self.load() + + def load(self): + if os.path.exists(self.config_path): + try: + with open(self.config_path, "r", encoding="utf-8") as f: + saved = json.load(f) + if not isinstance(saved, dict): + raise ValueError("Config file must contain a JSON object.") + if "concurrent_fragments" in saved: + try: + fragments = int(saved["concurrent_fragments"]) + except (TypeError, ValueError): + fragments = self._DEFAULT_CONFIG["concurrent_fragments"] + if fragments not in (1, 2, 4, 8, 16): + fragments = self._DEFAULT_CONFIG["concurrent_fragments"] + saved["concurrent_fragments"] = fragments + self.config.update(saved) + except (OSError, json.JSONDecodeError, ValueError): + logger.exception("Could not load configuration from %s", self.config_path) + + def save(self): + temp_path = self.config_path + ".tmp" + try: + with open(temp_path, "w", encoding="utf-8") as f: + json.dump(self.config, f, indent=4, ensure_ascii=False) + f.flush() + os.fsync(f.fileno()) + os.replace(temp_path, self.config_path) + except OSError: + logger.exception("Could not save configuration to %s", self.config_path) + try: + os.remove(temp_path) + except OSError: + logger.debug("Could not remove temporary configuration file %s", temp_path, exc_info=True) + + def get(self, key, default=None): + return self.config.get(key, default if default is not None else self._DEFAULT_CONFIG.get(key)) + + def set(self, key, value): + self.config[key] = value + self.save() + +# Tekil örnek +config = ConfigManager() diff --git a/core/dependencies.py b/core/dependencies.py new file mode 100644 index 0000000..08a8322 --- /dev/null +++ b/core/dependencies.py @@ -0,0 +1,237 @@ +import os +import sys +import shutil +import zipfile +import subprocess +import requests +from core.config import get_bin_dir, get_app_dir + +# bin/ dizinini çalışma zamanı PATH değişkeninin başına ekle +_bin_dir = get_bin_dir() +if _bin_dir and _bin_dir not in os.environ.get("PATH", ""): + os.environ["PATH"] = f"{_bin_dir};{os.environ.get('PATH', '')}" + +def find_executable(name: str): + """Belirtilen çalıştırılabilir dosyayı bin/ klasöründe veya PATH'te arar.""" + # 1. Local / User bin dizinini kontrol et + bin_dir = get_bin_dir() + local_path = os.path.join(bin_dir, f"{name}.exe" if sys.platform == "win32" else name) + if os.path.isfile(local_path) and os.access(local_path, os.X_OK): + return local_path + + # 2. PyInstaller _MEIPASS veya app dizinindeki bin klasörü + app_bin = os.path.join(get_app_dir(), "bin", f"{name}.exe" if sys.platform == "win32" else name) + if os.path.isfile(app_bin): + return app_bin + + # 3. Python Scripts dizini kontrolü (örn: yt-dlp pip ile kurulmuşsa) + python_dir = os.path.dirname(sys.executable) + py_script = os.path.join(python_dir, "Scripts", f"{name}.exe" if sys.platform == "win32" else name) + if os.path.isfile(py_script): + return py_script + + # 4. Windows Programs Python Scripts kontrolü + if sys.platform == "win32": + local_appdata = os.getenv("LOCALAPPDATA", "") + py_programs = os.path.join(local_appdata, "Programs", "Python") + if os.path.isdir(py_programs): + for entry in os.listdir(py_programs): + candidate = os.path.join(py_programs, entry, "Scripts", f"{name}.exe") + if os.path.isfile(candidate): + return candidate + + # 5. Sistem PATH kontrolü + return shutil.which(name) + + +def get_ytdlp_status(): + """yt-dlp durumunu (kurulu_mu, versiyon, yol) döndürür.""" + exe = find_executable("yt-dlp") + if not exe: + # pip modülü veya PyInstaller gömülü modül kontrolü + try: + import yt_dlp + import yt_dlp.version + ver = getattr(yt_dlp.version, "__version__", "Gömülü") + return True, str(ver), "embedded" + except Exception: + return False, "Bulunamadı", None + + try: + flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0 + out = subprocess.check_output([exe, "--version"], text=True, stderr=subprocess.STDOUT, creationflags=flags) + return True, out.strip(), exe + except Exception: + return True, "Mevcut", exe + + +def get_ffmpeg_status(): + """ffmpeg durumunu (kurulu_mu, versiyon, yol) döndürür.""" + exe = find_executable("ffmpeg") + if not exe: + return False, "Bulunamadı", None + try: + flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0 + out = subprocess.check_output([exe, "-version"], text=True, stderr=subprocess.STDOUT, creationflags=flags) + first_line = out.splitlines()[0] if out else "Mevcut" + return True, first_line[:30], exe + except Exception: + return True, "Mevcut", exe + + +def get_js_status(): + """YouTube n-challenge/EJS için JS motoru durumunu döndürür.""" + for js in ("deno", "node", "qjs"): + exe = find_executable(js) + if exe: + return True, f"Hazır ({js.capitalize()})", exe + return False, "Bulunamadı", None + + +def get_ffmpeg_dir(): + """Eğer ffmpeg yerel bin dizinindeyse dizin yolunu döndürür (--ffmpeg-location için).""" + exe = find_executable("ffmpeg") + if exe: + return os.path.dirname(exe) + return None + + +def install_deno(progress_callback=None): + """YouTube EJS challenge çözümleri için resmi Deno motorunu indirir.""" + bin_dir = get_bin_dir() + os.makedirs(bin_dir, exist_ok=True) + zip_path = os.path.join(bin_dir, "deno_download.zip") + url = "https://github.com/denoland/deno/releases/download/v2.9.6/deno-x86_64-pc-windows-msvc.zip" + download_file_with_progress(url, zip_path, progress_callback) + with zipfile.ZipFile(zip_path, 'r') as zf: + zf.extract("deno.exe", bin_dir) + try: + os.remove(zip_path) + except Exception: + pass + return os.path.join(bin_dir, "deno.exe") + + +def download_file_with_progress(url: str, dest_path: str, progress_callback=None): + """URL'den dosyayı indirir ve ilerlemeyi bildirir.""" + response = requests.get(url, stream=True, timeout=30) + response.raise_for_status() + total_length = response.headers.get('content-length') + + downloaded = 0 + total = int(total_length) if total_length else None + + with open(dest_path, "wb") as f: + for chunk in response.iter_content(chunk_size=1024 * 64): + if chunk: + f.write(chunk) + downloaded += len(chunk) + if progress_callback and total: + pct = (downloaded / total) * 100 + progress_callback(pct, downloaded, total) + + +def install_ytdlp(progress_callback=None): + """Resmi GitHub yayınından en güncel yt-dlp.exe dosyasını indirir.""" + bin_dir = get_bin_dir() + os.makedirs(bin_dir, exist_ok=True) + target = os.path.join(bin_dir, "yt-dlp.exe") + url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe" + + temp_target = target + ".tmp" + download_file_with_progress(url, temp_target, progress_callback) + if os.path.exists(target): + try: + os.remove(target) + except Exception: + pass + shutil.move(temp_target, target) + return target + + +def install_ffmpeg(progress_callback=None): + """yt-dlp tarafından resmi olarak önerilen taşınabilir FFmpeg yapısını indirip ayıklar.""" + bin_dir = get_bin_dir() + os.makedirs(bin_dir, exist_ok=True) + zip_path = os.path.join(bin_dir, "ffmpeg_download.zip") + + # yt-dlp resmi FFmpeg win64 yapısı (gpl) + url = "https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip" + + download_file_with_progress(url, zip_path, progress_callback) + + # Ayıkla ve ffmpeg.exe ile ffprobe.exe'yi bin_dir içine taşı + with zipfile.ZipFile(zip_path, 'r') as zf: + for member in zf.namelist(): + filename = os.path.basename(member) + if filename in ("ffmpeg.exe", "ffprobe.exe"): + source = zf.open(member) + target_path = os.path.join(bin_dir, filename) + with open(target_path, "wb") as target_file: + shutil.copyfileobj(source, target_file) + + try: + os.remove(zip_path) + except Exception: + pass + + return os.path.join(bin_dir, "ffmpeg.exe") + + +def resolve_cookies_args(mode: str, browser: str = "firefox", cookies_file: str = ""): + """Çerez parametrelerini akıllıca çözer. Zen Browser için Firefox profilini bulur.""" + if not mode or mode in ("none", "off", "kapali", "kapalı"): + return [] + + if mode == "file": + if cookies_file and os.path.isfile(cookies_file): + return ["--cookies", cookies_file] + raise FileNotFoundError( + "Seçilen cookies.txt dosyası bulunamadı. Ayarlar bölümünden geçerli bir dosya seçin veya çerez kullanımını kapatın." + ) + + if mode == "browser": + b = (browser or "").lower().strip() + if b == "zen": + # Zen Browser Firefox tabanlıdır, profil klasörünü bul + appdata = os.getenv("APPDATA", "") + zen_profiles = os.path.join(appdata, "Zen", "Profiles") + if os.path.exists(zen_profiles): + for folder in os.listdir(zen_profiles): + if "default" in folder.lower(): + profile_path = os.path.join(zen_profiles, folder) + return ["--cookies-from-browser", f"firefox:{profile_path}"] + return ["--cookies-from-browser", "firefox"] + + return ["--cookies-from-browser", b] + + return [] + + +def test_browser_cookies(browser_name: str): + """Belirtilen tarayıcıdan çerez çekilip çekilemediğini test eder.""" + args = resolve_cookies_args("browser", browser_name) + if not args: + return False, "Geçersiz çerez parametresi" + + exe = find_executable("yt-dlp") or "yt-dlp" + cmd = [exe] + args + ["--simulate", "--no-warnings", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"] + flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0 + try: + proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, creationflags=flags, timeout=12) + if proc.returncode == 0: + return True, f"✅ {browser_name.capitalize()} çerezleri başarıyla okundu!" + + err = proc.stderr.lower() + if "failed to decrypt with dpapi" in err or "dpapi" in err: + return False, ( + f"⚠️ {browser_name.capitalize()}: Windows DPAPI güvenlik koruması nedeniyle doğrudan çerez okunamadı. " + f"Çözüm: Çerezleri 'cookies.txt' eklentisiyle dışa aktarıp 'cookies.txt' modunda kullanın." + ) + if "could not copy" in err or "database" in err: + return False, f"⚠️ {browser_name.capitalize()} şu an açık olduğu için Windows dosyayı kilitliyor. Tarayıcıyı kapatıp tekrar deneyin." + if "could not find" in err: + return False, f"⚠️ {browser_name.capitalize()} çerez veritabanı bulunamadı. Bu tarayıcının sisteminizde yüklü olduğundan emin olun." + return False, f"Hata: {proc.stderr[:150]}" + except Exception as ex: + return False, str(ex) diff --git a/core/diagnostics.py b/core/diagnostics.py new file mode 100644 index 0000000..84de395 --- /dev/null +++ b/core/diagnostics.py @@ -0,0 +1,80 @@ +import re + +DIAGNOSTIC_RULES = [ + { + "keywords": ["confirm your age", "sign in to confirm your age", "age-restricted"], + "title": "🔞 Yaş Kısıtlamalı Video", + "solution": "Bu video yaş sınırına sahiptir. Ayarlar veya Çerezler bölümünden tarayıcınızı seçerek veya 'cookies.txt' dosyası ekleyerek indirmeyi yeniden deneyin." + }, + { + "keywords": ["private video", "this video is private"], + "title": "🔒 Gizli (Özel) Video", + "solution": "Bu video gizli veya yalnızca belirli kullanıcılara açıktır. İndirebilmek için videoya erişim izni olan bir hesabın çerezlerini (cookies) yüklemelisiniz." + }, + { + "keywords": ["members-only", "join this channel"], + "title": "⭐ Katıl / Üyelere Özel Video", + "solution": "Bu video yalnızca kanal üyelerine özeldir. Yalnızca bu kanala ücretli üye olan hesabınızın çerezlerini (cookies.txt) aktararak indirebilirsiniz." + }, + { + "keywords": ["n challenge solving failed", "javascript runtime", "wiki/ejs", "no supported javascript runtime"], + "title": "⚡ JavaScript EJS Motoru Gerekli", + "solution": "YouTube'un yeni güvenlik imzalarını çözmek için JavaScript motoru (Deno) gereklidir. Uygulamanız Deno motorunu bin/ klasörüne otomatik olarak entegre etmiştir." + }, + { + "keywords": ["only images are available for download", "requested format is not available"], + "title": "⚠️ Video Akışı Bulunamadı", + "solution": "Video akışı çekilemedi (yalnızca kapak görselleri mevcut). Bu video kısıtlı/üyelere özel olabilir veya yaş doğrulaması gerektirebilir." + }, + { + "keywords": ["not available in your country", "uploader has not made this video available in your country"], + "title": "🌍 Bölge Kısıtlaması (Geo-block)", + "solution": "Bu video ülkenizde kullanılamıyor. Ayarlar sekmesinden bir Proxy tanımlayabilir veya VPN kullanarak deneyebilirsiniz." + }, + { + "keywords": ["http error 403", "403: forbidden", "sign in to confirm you’re not a bot", "bot detection"], + "title": "🛡️ YouTube Bot / 403 Koruması", + "solution": "YouTube sunucuları doğrudan erişimi kısıtladı. Tarayıcınızdan taze çerezler (cookies) aktararak kimlik doğrulamasını yenileyin." + }, + { + "keywords": ["ffmpeg is not installed", "ffmpeg not found", "ffmpeg missing", "ffprobe not found"], + "title": "⚠️ FFmpeg Bulunamadı", + "solution": "Yüksek çözünürlüklü video birleştirme ve MP3 dönüşümleri için FFmpeg gereklidir. Ayarlar sekmesinden '⚡ 1-Tıkla FFmpeg Kur' butonuna tıklayarak otomatik kurabilirsiniz." + }, + { + "keywords": ["permission denied", "permissionerror", "access is denied"], + "title": "⛔ Klasör Yazma İzni Reddedildi", + "solution": "Seçilen kayıt klasörüne yazma izniniz yok. Lütfen 'İndirilenler' veya masaüstünde farklı bir klasör seçin ya da uygulamayı yönetici olarak başlatın." + }, + { + "keywords": ["no space left on device", "disk full"], + "title": "💾 Yetersiz Disk Alanı", + "solution": "Kayıt yapılan diskte yeterli boş alan bulunmuyor. Lütfen diskte yer açın veya başka bir sürücü seçin." + }, + { + "keywords": ["is not a valid url", "unsupported url"], + "title": "🔗 Geçersiz veya Desteklenmeyen URL", + "solution": "Girilen bağlantı geçerli bir video/ses bağlantısı değil. Lütfen URL'yi tarayıcınızdan kopyalayıp tekrar yapıştırın." + }, + { + "keywords": ["could not copy chrome cookie database", "could not copy", "cookie database"], + "title": "🍪 Tarayıcı Çerez Dosyası Kilitli", + "solution": "Seçilen tarayıcı açık olduğu için Windows çerez dosyasını kilitliyor. Çözüm: İndirme yaparken tarayıcıyı tamamen kapatın veya 'cookies.txt' dosya seçeneğini kullanın." + }, + { + "keywords": ["failed to decrypt with dpapi", "dpapi"], + "title": "🔐 Windows DPAPI Koruması", + "solution": "Windows güvenlik koruması (DPAPI) nedeniyle tarayıcıdan doğrudan çerez çekilemedi. Çözüm: 1) Normal videolarda çerez gerekmez, Çerezleri 'Kapalı' yapabilirsiniz. 2) Yaş kısıtlamalı videolar için tarayıcınıza 'Get cookies.txt' eklentisi kurup dışa aktardığınız dosyayı yükleyin." + } +] + +def diagnose(line: str) -> dict | None: + """Verilen log satırını analiz edip varsa tanı ve Türkçe çözüm önerisi döndürür.""" + lower_line = line.lower() + for rule in DIAGNOSTIC_RULES: + if any(kw in lower_line for kw in rule["keywords"]): + return { + "title": rule["title"], + "solution": rule["solution"] + } + return None diff --git a/core/downloader.py b/core/downloader.py new file mode 100644 index 0000000..b2b7fb1 --- /dev/null +++ b/core/downloader.py @@ -0,0 +1,330 @@ +import os +import sys +import re +import subprocess +import threading +from core.dependencies import find_executable, get_ffmpeg_dir +from core.diagnostics import diagnose + +class DownloadEngine: + _PROGRESS_RE = re.compile( + r"\[PROGRESS\]\s*(?P[\d.]+)(?:%\s*)?\|\s*(?P.*?)\s*\|\s*(?P.*?)\s*\|\s*(?P.*)" + ) + _DL_RE = re.compile( + r"\[download\]\s+(?P[\d.]+)%\s+of\s+~?(?P\S+)\s+" + r"at\s+(?P.*?)\s+ETA\s+(?P\S+)" + ) + _DEST_RE = re.compile( + r"\[(?:download|Merger|ExtractAudio|FixupM3u8)\]\s+(?:Destination:\s+|Merging formats into\s+\"|Writing video subtitles to:\s+)(?P[^\"]+)" + ) + + def __init__(self): + self._proc = None + self._running = False + self._cancelled = False + self._current_file = None + self._lock = threading.Lock() + + @property + def is_running(self): + return self._running + + def cancel(self): + """Devam eden indirmeyi ve tüm alt süreç ağacını güvenle sonlandırır.""" + with self._lock: + if not self._running or not self._proc: + return + self._cancelled = True + try: + if sys.platform == "win32": + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(self._proc.pid)], + creationflags=subprocess.CREATE_NO_WINDOW, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + else: + self._proc.kill() + except Exception: + pass + + def start_download(self, cmd_args, callbacks): + """ + İndirmeyi arka planda başlatır. + callbacks dict: + - on_progress(pct, speed, total, eta) + - on_log(line, tag) + - on_status(msg) + - on_complete(success, output_path, error_msg) + """ + with self._lock: + if self._running: + return False + self._running = True + self._cancelled = False + self._current_file = None + + thread = threading.Thread(target=self._worker, args=(cmd_args, callbacks), daemon=True) + thread.start() + return True + + def _worker(self, cmd_args, cb): + rc = -1 + error_message = None + last_destination = None + + try: + env = os.environ.copy() + env["PYTHONIOENCODING"] = "utf-8" + from core.config import get_bin_dir + b_dir = get_bin_dir() + if b_dir and b_dir not in env.get("PATH", ""): + env["PATH"] = f"{b_dir};{env.get('PATH', '')}" + + flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0 + self._proc = subprocess.Popen( + cmd_args, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + creationflags=flags, + bufsize=1, + env=env + ) + + for line in iter(self._proc.stdout.readline, ''): + line = line.rstrip() + if not line: + continue + + # 1. Dosya yolu yakalama + m_dest = self._DEST_RE.search(line) + if m_dest: + dest = m_dest.group("path").strip().strip('"') + if not dest.endswith((".part", ".ytdl")): + last_destination = dest + self._current_file = dest + + # 2. İlerleme ayrıştırma + parsed = self._parse_progress(line, cb.get("on_progress")) + + # 3. Akıllı Hata Teşhisi + diag = diagnose(line) + if diag: + if cb.get("on_log"): + cb["on_log"](f"💡 {diag['title']}: {diag['solution']}", "accent") + + # 4. Log etiketi belirleme + tag = "info" + if "ERROR:" in line: + tag = "error" + error_message = line + elif "WARNING:" in line: + tag = "warn" + elif "[download] 100%" in line or "100% of" in line: + tag = "success" + + if cb.get("on_log"): + cb["on_log"](line, tag) + + self._proc.wait() + rc = self._proc.returncode + + except Exception as ex: + error_message = str(ex) + if cb.get("on_log"): + cb["on_log"](f"❌ Kritik Hata: {ex}", "error") + + finally: + with self._lock: + self._running = False + self._proc = None + + success = (rc == 0 and not self._cancelled) + if cb.get("on_complete"): + cb["on_complete"](success, last_destination or self._current_file, error_message, self._cancelled) + + def _parse_progress(self, line, on_progress): + if not on_progress: + return False + + # Özel template kontrolü + m = self._PROGRESS_RE.search(line) + if m: + try: + pct = float(m.group("pct").strip()) + speed = m.group("speed").strip() + total = m.group("total").strip() + eta = m.group("eta").strip() + + speed = "—" if not speed or any(x in speed.lower() for x in ["unknown", "na", "—"]) else speed + total = "—" if not total or any(x in total.lower() for x in ["unknown", "na", "—"]) else total + eta = "—" if not eta or any(x in eta.lower() for x in ["unknown", "na", "—"]) else eta + + on_progress(pct, speed, total, eta) + return True + except Exception: + pass + + # Standart yt-dlp ilerleme satırı + m = self._DL_RE.search(line) + if m: + try: + pct = float(m.group("pct")) + total = m.group("total") + speed = m.group("speed").strip() + eta = m.group("eta").strip() + on_progress(pct, speed, total, eta) + return True + except Exception: + pass + + return False + + +def build_command(url, output_dir, options): + """ + yt-dlp için tüm seçenekleri birleştirip komut listesini üretir. + options alanları: + - mode: "single" veya "playlist" + - media_type: "video" veya "audio" + - format: "mp4", "mkv", "webm", "mp3", "m4a", "flac", "wav" vb. + - quality: "Best Quality (En İyi)" veya "1080p", "720p" / "320 kbps" + - cookies_args: list + - embed_subtitles: bool + - subtitle_lang: str + - embed_thumbnail: bool + - add_metadata: bool + - concurrent_fragments: int + - playlist_start: str + - playlist_end: str + - ignore_errors: bool + - speed_limit: str + - proxy: str + """ + ytdlp_exe = find_executable("yt-dlp") or "yt-dlp" + cmd = [ytdlp_exe, "--newline"] + + # Yerel FFmpeg kontrolü + ffmpeg_dir = get_ffmpeg_dir() + if ffmpeg_dir: + cmd += ["--ffmpeg-location", ffmpeg_dir] + + # Çerezler + cookies_args = options.get("cookies_args") or [] + cmd.extend(cookies_args) + + media_type = options.get("media_type", "video") + out_format = options.get("format", "mp4" if media_type == "video" else "mp3").lower() + quality = options.get("quality", "Best Quality (En İyi)") + + # Video / Ses Formatı Seçimi + if media_type == "video": + if "Best" in quality: + if out_format == "mp4": + cmd += ["-f", "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv+ba/b", "--merge-output-format", "mp4"] + elif out_format == "mkv": + cmd += ["-f", "bv*+ba/b", "--merge-output-format", "mkv"] + elif out_format == "webm": + cmd += ["-f", "bv*[ext=webm]+ba[ext=webm]/b[ext=webm]/bv+ba/b", "--merge-output-format", "webm"] + else: + cmd += ["-f", "bv*+ba/b", "--merge-output-format", out_format] + else: + height = re.search(r"\d+", quality) + num_h = height.group(0) if height else "1080" + if out_format == "mp4": + cmd += [ + "-f", f"bestvideo[height<={num_h}][ext=mp4]+bestaudio[ext=m4a]/best[height<={num_h}]", + "--merge-output-format", "mp4" + ] + else: + cmd += [ + "-f", f"bestvideo[height<={num_h}]+bestaudio/best[height<={num_h}]", + "--merge-output-format", out_format + ] + else: + # Audio indirme + cmd += ["-x", "--audio-format", out_format] + if "Best" in quality: + cmd += ["--audio-quality", "0"] + else: + bitrate = re.search(r"\d+", quality) + num_b = bitrate.group(0) if bitrate else "320" + cmd += ["--audio-quality", f"{num_b}k"] + + # Gelişmiş Seçenekler + if options.get("embed_thumbnail", True): + cmd.append("--embed-thumbnail") + + if options.get("add_metadata", True): + cmd.append("--add-metadata") + + if options.get("embed_subtitles"): + langs = options.get("subtitle_lang", "tr,en") + cmd += ["--write-subs", "--write-auto-subs", "--sub-langs", langs, "--embed-subs"] + + try: + concurrency = int(options.get("concurrent_fragments", 4)) + except (TypeError, ValueError) as ex: + raise ValueError("Parça sayısı 1 ile 16 arasında bir tam sayı olmalıdır.") from ex + if not 1 <= concurrency <= 16: + raise ValueError("Parça sayısı 1 ile 16 arasında olmalıdır.") + if concurrency > 1: + cmd += ["--concurrent-fragments", str(concurrency)] + + if options.get("mode") == "playlist" and options.get("ignore_errors", True): + cmd.append("--ignore-errors") + + speed_limit = options.get("speed_limit") + if speed_limit: + cmd += ["--limit-rate", speed_limit] + + proxy = options.get("proxy") + if proxy: + cmd += ["--proxy", proxy] + + # Playlist aralığı + if options.get("mode") == "playlist": + playlist_range = playlist_items_range( + options.get("playlist_start"), + options.get("playlist_end") + ) + if playlist_range: + cmd += ["--playlist-items", playlist_range] + cmd.append("--yes-playlist") + cmd += ["-o", os.path.join(output_dir, "%(playlist_title)s", "%(playlist_index)s - %(title)s.%(ext)s")] + else: + cmd.append("--no-playlist") + cmd += ["-o", os.path.join(output_dir, "%(title)s.%(ext)s")] + + # Kararlı ilerleme şablonu + cmd += [ + "--progress-template", + "download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s" + ] + + cmd.append(url) + return cmd + +engine = DownloadEngine() + + +def playlist_items_range(start, end): + """Validate playlist indexes and return yt-dlp's playlist-items value.""" + start = str(start or "").strip() + end = str(end or "").strip() + if start and not start.isdigit(): + raise ValueError("Başlangıç sırası pozitif bir tam sayı olmalıdır.") + if end and not end.isdigit(): + raise ValueError("Bitiş sırası pozitif bir tam sayı olmalıdır.") + if start and int(start) < 1: + raise ValueError("Başlangıç sırası en az 1 olmalıdır.") + if end and int(end) < 1: + raise ValueError("Bitiş sırası en az 1 olmalıdır.") + if start and end and int(end) < int(start): + raise ValueError("Bitiş sırası başlangıç sırasından küçük olamaz.") + if start or end: + return f"{start or '1'}:{end}" + return None diff --git a/core/history.py b/core/history.py new file mode 100644 index 0000000..22e6999 --- /dev/null +++ b/core/history.py @@ -0,0 +1,125 @@ +import os +import sys +import json +import logging +import subprocess +from datetime import datetime +from uuid import uuid4 +from core.config import get_data_dir + +logger = logging.getLogger(__name__) + + +class HistoryManager: + def __init__(self): + self.history_file = os.path.join(get_data_dir(), "history.json") + self.items = [] + self.load() + + def load(self): + if os.path.exists(self.history_file): + try: + with open(self.history_file, "r", encoding="utf-8") as f: + items = json.load(f) + if not isinstance(items, list): + raise ValueError("History file must contain a JSON list.") + self.items = items + except (OSError, json.JSONDecodeError, ValueError): + logger.exception("Could not load download history from %s", self.history_file) + self.items = [] + else: + self.items = [] + + def save(self): + temp_path = self.history_file + ".tmp" + try: + with open(temp_path, "w", encoding="utf-8") as f: + json.dump(self.items, f, indent=2, ensure_ascii=False) + f.flush() + os.fsync(f.fileno()) + os.replace(temp_path, self.history_file) + except (OSError, TypeError): + logger.exception("Could not save download history to %s", self.history_file) + try: + os.remove(temp_path) + except OSError: + logger.debug("Could not remove temporary history file %s", temp_path, exc_info=True) + + def add(self, title, url, file_path, fmt_info, status="completed"): + size_str = "—" + if file_path and os.path.exists(file_path): + try: + bytes_size = os.path.getsize(file_path) + if bytes_size >= 1024 * 1024 * 1024: + size_str = f"{bytes_size / (1024*1024*1024):.2f} GB" + elif bytes_size >= 1024 * 1024: + size_str = f"{bytes_size / (1024*1024):.2f} MB" + else: + size_str = f"{bytes_size / 1024:.1f} KB" + except Exception: + pass + + item = { + "id": uuid4().hex, + "title": title or os.path.basename(file_path or url), + "url": url, + "path": file_path, + "format": fmt_info, + "size": size_str, + "date": datetime.now().strftime("%Y-%m-%d %H:%M"), + "status": status + } + # En yeni en üstte + self.items.insert(0, item) + # Maksimum 200 geçmiş kaydı sakla + if len(self.items) > 200: + self.items = self.items[:200] + self.save() + return item + + def get_all(self): + return self.items + + def remove(self, item_id): + self.items = [i for i in self.items if i.get("id") != item_id] + self.save() + + def clear(self): + self.items = [] + self.save() + + @staticmethod + def show_in_folder(file_path): + """Dosyayı Windows Explorer'da seçili olarak gösterir.""" + if not file_path: + return False + + path = os.path.normpath(file_path) + if os.path.exists(path): + if sys.platform == "win32": + subprocess.Popen(f'explorer /select,"{path}"') + return True + else: + subprocess.Popen(["xdg-open", os.path.dirname(path)]) + return True + elif os.path.isdir(os.path.dirname(path)): + if sys.platform == "win32": + subprocess.Popen(f'explorer "{os.path.dirname(path)}"') + return True + return False + + @staticmethod + def play_file(file_path): + """Dosyayı varsayılan medya oynatıcıda açar.""" + if not file_path or not os.path.exists(file_path): + return False + try: + if sys.platform == "win32": + os.startfile(file_path) + else: + subprocess.Popen(["xdg-open", file_path]) + return True + except Exception: + return False + +history = HistoryManager() diff --git a/core/metadata.py b/core/metadata.py new file mode 100644 index 0000000..96b7fab --- /dev/null +++ b/core/metadata.py @@ -0,0 +1,119 @@ +import os +import io +import threading +import requests +from PIL import Image, ImageTk +from core.dependencies import find_executable + +def format_duration(seconds): + """Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür.""" + if not seconds: + return "—" + try: + s = int(seconds) + hours = s // 3600 + minutes = (s % 3600) // 60 + secs = s % 60 + if hours > 0: + return f"{hours:02d}:{minutes:02d}:{secs:02d}" + return f"{minutes:02d}:{secs:02d}" + except Exception: + return "—" + + +def extract_resolutions(info_dict): + """Videonun format listesinden gerçek çözünürlükleri çıkarır.""" + formats = info_dict.get("formats") or [] + heights = set() + for f in formats: + # Sadece video içeren formatlar + if f.get("vcodec") != "none" and f.get("height"): + heights.add(int(f["height"])) + + sorted_heights = sorted(list(heights), reverse=True) + res_list = ["Best Quality (En İyi)"] + for h in sorted_heights: + label = f"{h}p" + if h >= 2160: + label += " (4K)" + elif h >= 1440: + label += " (2K)" + elif h >= 1080: + label += " (FHD)" + elif h >= 720: + label += " (HD)" + res_list.append(label) + + return res_list + + +def fetch_thumbnail_image(url, size=(160, 90)): + """Thumbnail URL'sinden resmi çeker ve belirtilen boyutta PIL Image döndürür.""" + if not url: + return None + try: + resp = requests.get(url, timeout=10) + if resp.status_code == 200: + img_data = resp.content + img = Image.open(io.BytesIO(img_data)) + img = img.convert("RGBA") + img = img.resize(size, Image.Resampling.LANCZOS) + return img + except Exception: + pass + return None + + +def fetch_video_metadata(url: str, cookies_args: list = None, callback=None, error_callback=None): + """Videonun temel bilgilerini arka planda çeker.""" + def _worker(): + try: + import yt_dlp + ydl_opts = { + 'quiet': True, + 'no_warnings': True, + 'extract_flat': False, + 'skip_download': True, + } + if cookies_args: + # Cookies args parse (örnek: --cookies-from-browser firefox veya --cookies file) + for i, arg in enumerate(cookies_args): + if arg == "--cookies-from-browser" and i + 1 < len(cookies_args): + ydl_opts['cookiesfrombrowser'] = (cookies_args[i+1],) + elif arg == "--cookies" and i + 1 < len(cookies_args): + ydl_opts['cookiefile'] = cookies_args[i+1] + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + + # Eğer playlist ise ilk videoyu al veya genel bilgi oluştur + is_playlist = 'entries' in info + first_entry = info['entries'][0] if is_playlist and info.get('entries') else info + + title = first_entry.get("title") or info.get("title", "Bilinmeyen Başlık") + uploader = first_entry.get("uploader") or info.get("uploader", "Bilinmeyen Kanal") + duration = format_duration(first_entry.get("duration")) + thumbnail_url = first_entry.get("thumbnail") or info.get("thumbnail") + resolutions = extract_resolutions(first_entry) + + thumb_img = fetch_thumbnail_image(thumbnail_url) + + metadata = { + "is_playlist": is_playlist, + "title": title, + "uploader": uploader, + "duration": duration, + "thumbnail_url": thumbnail_url, + "thumbnail_img": thumb_img, + "resolutions": resolutions, + "raw_info": first_entry + } + + if callback: + callback(metadata) + + except Exception as ex: + if error_callback: + error_callback(str(ex)) + + threading.Thread(target=_worker, daemon=True).start() diff --git a/logo.ico b/logo.ico new file mode 100644 index 0000000..10051d3 Binary files /dev/null and b/logo.ico differ diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..f8652bc Binary files /dev/null and b/logo.png differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..55e9e35 --- /dev/null +++ b/main.py @@ -0,0 +1,13 @@ +"""LDownloader Main Entry Point""" +import os +import sys + +# Proje kök dizinini Python yoluna ekle +current_dir = os.path.dirname(os.path.abspath(__file__)) +if current_dir not in sys.path: + sys.path.insert(0, current_dir) + +from ui.app import main + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..809d396 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +yt-dlp[default]>=2024.8.0 +yt-dlp-ejs>=0.8.0 +pillow>=10.0.0 +requests>=2.28.0 +pyinstaller>=6.0.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_downloader.py b/tests/test_downloader.py new file mode 100644 index 0000000..57c043e --- /dev/null +++ b/tests/test_downloader.py @@ -0,0 +1,100 @@ +import unittest +from unittest.mock import patch + +from core.dependencies import resolve_cookies_args +from core.downloader import build_command, playlist_items_range + + +class PlaylistItemsRangeTests(unittest.TestCase): + def test_empty_range_is_unrestricted(self): + self.assertIsNone(playlist_items_range("", "")) + + def test_start_and_end_are_normalized(self): + self.assertEqual(playlist_items_range("2", "8"), "2:8") + + def test_end_without_start_starts_at_first_item(self): + self.assertEqual(playlist_items_range("", "8"), "1:8") + + def test_rejects_non_numeric_or_reversed_ranges(self): + for start, end in (("x", ""), ("1", "x"), ("0", ""), ("8", "2")): + with self.subTest(start=start, end=end): + with self.assertRaises(ValueError): + playlist_items_range(start, end) + + +class BuildCommandTests(unittest.TestCase): + @patch("core.downloader.find_executable", return_value="yt-dlp") + @patch("core.downloader.get_ffmpeg_dir", return_value=None) + def test_playlist_range_and_configured_options_are_applied(self, *_mocks): + command = build_command( + "https://example.com/playlist", + "C:\\Downloads", + { + "mode": "playlist", + "media_type": "video", + "format": "mp4", + "quality": "Best Quality (En İyi)", + "playlist_start": "2", + "playlist_end": "5", + "concurrent_fragments": 8, + "speed_limit": "2M", + "proxy": "http://127.0.0.1:8080", + }, + ) + + self.assertIn("2:5", command) + self.assertIn("8", command) + self.assertIn("2M", command) + self.assertIn("http://127.0.0.1:8080", command) + self.assertIn("--yes-playlist", command) + + @patch("core.downloader.find_executable", return_value="yt-dlp") + @patch("core.downloader.get_ffmpeg_dir", return_value=None) + def test_rejects_out_of_range_fragment_count(self, *_mocks): + with self.assertRaises(ValueError): + build_command( + "https://example.com/video", + "C:\\Downloads", + {"concurrent_fragments": 17}, + ) + + @patch("core.downloader.find_executable", return_value="yt-dlp") + @patch("core.downloader.get_ffmpeg_dir", return_value=None) + def test_rejects_invalid_playlist_range(self, *_mocks): + with self.assertRaises(ValueError): + build_command( + "https://example.com/playlist", + "C:\\Downloads", + { + "mode": "playlist", + "playlist_start": "5", + "playlist_end": "2", + }, + ) + + @patch("core.downloader.find_executable", return_value="yt-dlp") + @patch("core.downloader.get_ffmpeg_dir", return_value=None) + def test_ignore_errors_is_only_enabled_for_playlists(self, *_mocks): + single_command = build_command( + "https://example.com/video", + "C:\\Downloads", + {"mode": "single", "ignore_errors": True}, + ) + playlist_command = build_command( + "https://example.com/playlist", + "C:\\Downloads", + {"mode": "playlist", "ignore_errors": True}, + ) + + self.assertNotIn("--ignore-errors", single_command) + self.assertIn("--ignore-errors", playlist_command) + + +class CookieResolutionTests(unittest.TestCase): + def test_missing_cookie_file_is_reported(self): + with self.assertRaises(FileNotFoundError): + resolve_cookies_args("file", cookies_file="missing-cookies.txt") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_persistence.py b/tests/test_persistence.py new file mode 100644 index 0000000..0945412 --- /dev/null +++ b/tests/test_persistence.py @@ -0,0 +1,41 @@ +import json +import os +import tempfile +import unittest +from unittest.mock import patch + +from core.config import ConfigManager +from core.history import HistoryManager + + +class PersistenceTests(unittest.TestCase): + def test_config_save_is_atomic_and_invalid_fragment_count_uses_default(self): + with tempfile.TemporaryDirectory() as data_dir: + config_path = os.path.join(data_dir, "config.json") + with open(config_path, "w", encoding="utf-8") as config_file: + json.dump({"concurrent_fragments": "invalid"}, config_file) + + with patch("core.config.get_data_dir", return_value=data_dir): + manager = ConfigManager() + self.assertEqual(manager.get("concurrent_fragments"), 4) + manager.set("proxy", "http://127.0.0.1:8080") + + with open(config_path, "r", encoding="utf-8") as config_file: + saved = json.load(config_file) + self.assertEqual(saved["proxy"], "http://127.0.0.1:8080") + self.assertFalse(os.path.exists(config_path + ".tmp")) + + def test_history_save_is_atomic_and_ids_are_unique(self): + with tempfile.TemporaryDirectory() as data_dir: + with patch("core.history.get_data_dir", return_value=data_dir): + history = HistoryManager() + first = history.add("First", "https://example.com/1", None, "mp4") + second = history.add("Second", "https://example.com/2", None, "mp4") + + self.assertNotEqual(first["id"], second["id"]) + self.assertTrue(os.path.isfile(history.history_file)) + self.assertFalse(os.path.exists(history.history_file + ".tmp")) + + +if __name__ == "__main__": + unittest.main() diff --git a/ui/__init__.py b/ui/__init__.py new file mode 100644 index 0000000..a9cde54 --- /dev/null +++ b/ui/__init__.py @@ -0,0 +1 @@ +"""LDownloader UI Modules""" diff --git a/ui/app.py b/ui/app.py new file mode 100644 index 0000000..d1b7d99 --- /dev/null +++ b/ui/app.py @@ -0,0 +1,615 @@ +import os +import sys +import ctypes +import threading +import tkinter as tk +from tkinter import messagebox + +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, + ACCENT, ACCENT_LIGHT, ACCENT_MUTED, TEXT, SUBTEXT, MUTED, SUCCESS, WARNING, ERROR, + TAB_BG, + FONT_HERO, FONT_TITLE, FONT_SUBTITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD, + apply_theme +) +from ui.components import TabButton, PillButton, ContextualDownloadDrawer +from ui.tabs.single_tab import SingleTab +from ui.tabs.playlist_tab import PlaylistTab +from ui.tabs.batch_tab import BatchTab +from ui.tabs.history_tab import HistoryTab +from ui.tabs.settings_tab import SettingsTab + +from core.config import config, get_app_dir +from core.downloader import engine, build_command +from core.history import history +from core.dependencies import get_ytdlp_status, get_ffmpeg_status, get_js_status + +class LDownloaderApp(tk.Tk): + def __init__(self): + super().__init__() + self.title("LDownloader v2.0") + self.geometry("1080x800") + self.minsize(900, 680) + self.configure(bg=BG) + + # Windows AppUserModelID + if sys.platform == "win32": + try: + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("ldownloader.modern.gui.2") + except Exception: + pass + + # Ekranı ortala + self.update_idletasks() + sw = self.winfo_screenwidth() + sh = self.winfo_screenheight() + width = min(1080, sw - 80) + height = min(800, sh - 100) + x = max(0, (sw - width) // 2) + y = max(0, (sh - height) // 2) + self.geometry(f"{width}x{height}+{x}+{y}") + + # İkon ve Logo + self._load_icons() + + # Tema ve stiller + apply_theme(self, config.get("theme", "dark")) + + # Durum değişkenleri + self.active_tab_name = "single" + self.current_download_file = None + self._batch_running = False + + # Ana Düzen + self._build_layout() + + self.protocol("WM_DELETE_WINDOW", self._on_close) + + # Sistem durumunu arka planda kontrol et + self._update_system_status() + + def _load_icons(self): + app_dir = get_app_dir() + ico_path = os.path.join(app_dir, "logo.ico") + if os.path.isfile(ico_path): + try: + self.iconbitmap(ico_path) + except Exception: + pass + + self.logo_img = None + self.window_icon_img = None + png_path = os.path.join(app_dir, "logo.png") + if os.path.isfile(png_path): + try: + raw = tk.PhotoImage(file=png_path) + self.window_icon_img = raw + self.iconphoto(True, raw) + factor = max(1, raw.width() // 28) + self.logo_img = raw.subsample(factor, factor) + except Exception: + pass + + def _build_layout(self): + # ── Üst Başlık Çubuğu (Top Bar) ───────────────────────────── + top_bar = tk.Frame(self, bg=TAB_BG, padx=24, pady=14) + top_bar.pack(fill="x") + + # Sol: Logo + Başlık + brand_frame = tk.Frame(top_bar, bg=TAB_BG) + brand_frame.pack(side="left") + + if self.logo_img: + tk.Label(brand_frame, image=self.logo_img, bg=TAB_BG).pack(side="left", padx=(0, 8)) + + tk.Label(brand_frame, text="LDownloader", font=FONT_TITLE, bg=TAB_BG, fg=TEXT).pack(side="left") + badge = tk.Label( + brand_frame, text="2.0", font=FONT_SMALL_BOLD, bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + padx=8, pady=3 + ) + badge.pack(side="left", padx=(10, 0)) + + # Sağ: Sistem durumu + self.lbl_sys_status = tk.Label( + top_bar, text="● Sistem kontrol ediliyor", bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + font=FONT_SMALL_BOLD, anchor="e", padx=12, pady=6 + ) + self.lbl_sys_status.pack(side="right") + self.btn_theme = PillButton( + top_bar, + text="Açık tema" if config.get("theme", "dark") == "dark" else "Koyu tema", + command=self._toggle_theme, + small=True, + style="secondary", + ) + self.btn_theme.pack(side="right", padx=(0, 10)) + + # ── Tab Navigasyon Çubuğu ──────────────────────────────────── + tab_bar = tk.Frame(self, bg=TAB_BG) + tab_bar.pack(fill="x") + + # Ince ayraç + tk.Frame(tab_bar, bg=BORDER, height=1).pack(fill="x", side="top") + + tab_inner = tk.Frame(tab_bar, bg=TAB_BG, padx=20, pady=8) + tab_inner.pack(fill="x") + + self.nav_buttons = {} + nav_items = [ + ("single", "▶", "Tekli indirme"), + ("playlist", "≡", "Oynatma listesi"), + ("batch", "+", "Toplu indirme"), + ("history", "↺", "Geçmiş"), + ("settings", "⚙", "Ayarlar") + ] + + for key, icon, label in nav_items: + btn = TabButton( + tab_inner, + icon=icon, + text=label, + command=lambda k=key: self.switch_tab(k), + is_active=(key == "single") + ) + btn.pack(side="left", padx=(0, 2)) + self.nav_buttons[key] = btn + + # Alttaki ince ayraç + tk.Frame(self, bg=BORDER, height=1).pack(fill="x") + + # ── Ana İçerik Alanı ───────────────────────────────────────── + self.main_area = tk.Frame(self, bg=BG) + self.main_area.pack(fill="both", expand=True) + + # İçerik Kapsayıcısı (Scrollable alan) + self.content_container = tk.Frame(self.main_area, bg=BG) + self.content_container.pack(fill="both", expand=True) + + # Alt İndirme Çekmecesi + self.drawer = ContextualDownloadDrawer( + self.main_area, + on_cancel=self._on_cancel_download, + on_open_file=self._open_downloaded_file + ) + + # Sekmeleri Başlat + self.tabs = { + "single": SingleTab(self.content_container, on_download_requested=self.start_single_download), + "playlist": PlaylistTab(self.content_container, on_download_requested=self.start_playlist_download), + "batch": BatchTab(self.content_container, on_batch_requested=self.start_batch_download), + "history": HistoryTab(self.content_container), + "settings": SettingsTab(self.content_container, on_dependency_updated=self._on_deps_updated) + } + + self.switch_tab("single") + + def _capture_layout_state(self): + state = {"active_tab": self.active_tab_name} + single = self.tabs.get("single") + if single: + state["single"] = { + "url": single.url_entry.get_clean_text(), + "dir": single.dir_var.get(), + "media": single.media_seg.get(), + "video_format": single.video_ext_var.get(), + "video_quality": single.res_var.get(), + "audio_format": single.audio_ext_var.get(), + "audio_quality": single.audio_qual_var.get(), + "subtitles": single.chip_sub.get(), + "thumbnail": single.chip_thumb.get(), + "turbo": single.chip_turbo.get(), + "metadata": single.current_metadata, + } + + playlist = self.tabs.get("playlist") + if playlist: + state["playlist"] = { + "url": playlist.url_entry.get_clean_text(), + "dir": playlist.dir_var.get(), + "media": playlist.media_seg.get(), + "video_quality": playlist.res_var.get(), + "audio_quality": playlist.audio_qual_var.get(), + "start": playlist.start_var.get(), + "end": playlist.end_var.get(), + "ignore_errors": playlist.chip_ignore.get(), + "turbo": playlist.chip_turbo.get(), + } + + batch = self.tabs.get("batch") + if batch: + state["batch"] = { + "input": batch.text_input.get("1.0", "end-1c"), + "media": batch.media_seg.get(), + "queue": [dict(item) for item in batch.queue], + } + + history_tab = self.tabs.get("history") + if history_tab: + state["history_search"] = history_tab.search_var.get() + + state["drawer"] = { + "visible": bool(self.drawer.winfo_manager()), + "title": self.drawer.lbl_title.cget("text"), + "progress": self.drawer.pbar["value"], + "logs": self.drawer.log_text.get("1.0", "end-1c"), + "console_open": self.drawer.console_open, + "completed": bool(self.drawer.btn_open.winfo_manager()), + "cancelled": self.drawer.lbl_title.cget("text").startswith("⛔"), + "failed": self.drawer.lbl_title.cget("text").startswith("❌"), + } + return state + + def _restore_layout_state(self, state): + single_state = state.get("single", {}) + single = self.tabs["single"] + single.dir_var.set(single_state.get("dir", single.dir_var.get())) + single.media_seg.select(single_state.get("media", "video")) + single.video_ext_var.set(single_state.get("video_format", single.video_ext_var.get())) + single.res_var.set(single_state.get("video_quality", single.res_var.get())) + single.audio_ext_var.set(single_state.get("audio_format", single.audio_ext_var.get())) + single.audio_qual_var.set(single_state.get("audio_quality", single.audio_qual_var.get())) + single.chip_sub.set(single_state.get("subtitles", single.chip_sub.get())) + single.chip_thumb.set(single_state.get("thumbnail", single.chip_thumb.get())) + single.chip_turbo.set(single_state.get("turbo", single.chip_turbo.get())) + single.url_var.set(single_state.get("url", "")) + if single_state.get("url"): + single.url_entry.has_placeholder = False + single.url_entry.config(fg=TEXT) + single.current_metadata = None + + playlist_state = state.get("playlist", {}) + playlist = self.tabs["playlist"] + playlist.dir_var.set(playlist_state.get("dir", playlist.dir_var.get())) + playlist.media_seg.select(playlist_state.get("media", "video")) + playlist.res_var.set(playlist_state.get("video_quality", playlist.res_var.get())) + playlist.audio_qual_var.set(playlist_state.get("audio_quality", playlist.audio_qual_var.get())) + playlist.start_var.set(playlist_state.get("start", "")) + playlist.end_var.set(playlist_state.get("end", "")) + playlist.chip_ignore.set(playlist_state.get("ignore_errors", True)) + playlist.chip_turbo.set(playlist_state.get("turbo", True)) + playlist.url_var.set(playlist_state.get("url", "")) + if playlist_state.get("url"): + playlist.url_entry.has_placeholder = False + playlist.url_entry.config(fg=TEXT) + + batch_state = state.get("batch", {}) + batch = self.tabs["batch"] + batch.media_seg.select(batch_state.get("media", "video")) + batch.text_input.insert("1.0", batch_state.get("input", "")) + batch.queue = [dict(item) for item in batch_state.get("queue", [])] + for item in batch.queue: + batch.tree.insert( + "", "end", iid=str(item["idx"]), + values=(item["idx"], item["url"], item["status"]) + ) + batch.lbl_queue_count.config(text=f"Kuyruk · {len(batch.queue)} öğe") + + self.switch_tab(state.get("active_tab", "single")) + if single_state.get("metadata") and single_state.get("url"): + single._metadata_url = single_state["url"] + single.current_metadata = single_state["metadata"] + single.preview_card.update_metadata(single_state["metadata"]) + single.preview_card.pack( + fill="x", padx=32, pady=(0, 16), before=single.format_card + ) + resolutions = single_state["metadata"].get("resolutions") + if resolutions: + single.res_cb.config(values=resolutions) + single.res_var.set(single_state.get("video_quality", resolutions[0])) + + history_state = state.get("history_search") + if history_state is not None: + history_tab = self.tabs["history"] + history_tab.search_var.set(history_state) + history_tab.search_query = history_state.lower().strip() + history_tab.refresh() + + drawer_state = state.get("drawer", {}) + if drawer_state.get("visible"): + title = drawer_state.get("title", "İndirme") + if title.startswith("⏳ "): + title = title[2:] + self.drawer.show(title) + self.drawer.pbar["value"] = drawer_state.get("progress", 0) + self.drawer.pct_var.set(f"{float(drawer_state.get('progress', 0)):.1f}%") + self.drawer.log_text.config(state="normal") + self.drawer.log_text.insert("end", drawer_state.get("logs", "")) + self.drawer.log_text.config(state="disabled") + if engine.is_running or self._batch_running: + if drawer_state.get("console_open"): + self.drawer._toggle_console() + elif drawer_state.get("completed"): + self.drawer.on_complete_status(True, self.current_download_file) + elif drawer_state.get("cancelled"): + self.drawer.on_complete_status(False, cancelled=True) + elif drawer_state.get("failed"): + self.drawer.on_complete_status(False, error_msg=title) + + def _toggle_theme(self): + state = self._capture_layout_state() + next_theme = "light" if config.get("theme", "dark") == "dark" else "dark" + config.set("theme", next_theme) + apply_theme(self, next_theme) + for child in self.winfo_children(): + child.destroy() + self._build_layout() + self.btn_theme.config(text="Açık tema" if next_theme == "dark" else "Koyu tema") + self._restore_layout_state(state) + self._update_system_status() + + def switch_tab(self, key): + self.active_tab_name = key + for k, btn in self.nav_buttons.items(): + btn.set_active(k == key) + + for k, frame in self.tabs.items(): + if k == key: + frame.pack(fill="both", expand=True) + if hasattr(frame, "refresh"): + frame.refresh() + else: + frame.pack_forget() + + def _update_system_status(self): + def _worker(): + yt_ok, _, _ = get_ytdlp_status() + ff_ok, _, _ = get_ffmpeg_status() + js_ok, _, _ = get_js_status() + + def _apply(): + if yt_ok and ff_ok and js_ok: + self.lbl_sys_status.config(text="● Motorlar Aktif (Deno + FFmpeg)", fg=SUCCESS) + elif yt_ok and ff_ok: + self.lbl_sys_status.config(text="● Motorlar Aktif", fg=SUCCESS) + elif yt_ok and not ff_ok: + self.lbl_sys_status.config(text="● FFmpeg Eksik", fg=WARNING) + else: + self.lbl_sys_status.config(text="● yt-dlp Eksik", fg=ERROR) + + self.after(0, _apply) + + threading.Thread(target=_worker, daemon=True).start() + + def _on_deps_updated(self): + self._update_system_status() + self.drawer.log_line("✅ Bağımlılıklar güncellendi ve hazır.", "success") + + # ── İndirme İşlemleri ─────────────────────────────────────────── + def start_single_download(self, url, out_dir, options): + if engine.is_running: + messagebox.showinfo("Bilgi", "Zaten devam eden bir indirme işlemi var.", parent=self) + return + + cookies_args = self._get_download_cookies_args() + if cookies_args is None: + return + + if not self._ensure_output_dir(out_dir): + return + + options["cookies_args"] = cookies_args + options["proxy"] = config.get("proxy") + + try: + cmd = build_command(url, out_dir, options) + except ValueError as e: + messagebox.showwarning("İndirme Ayarları", str(e), parent=self) + return + title = options.get("title") or url + fmt_desc = f"{options['format']} ({options['quality']})" + + self.drawer.show(title=title) + self.drawer.log_line(f"▶ Başlatıldı: {url}", "accent") + + self._start_engine(cmd, title=title, url=url, fmt_desc=fmt_desc) + + def start_playlist_download(self, url, out_dir, options): + if engine.is_running: + messagebox.showinfo("Bilgi", "Zaten devam eden bir indirme işlemi var.", parent=self) + return + + cookies_args = self._get_download_cookies_args() + if cookies_args is None: + return + + if not self._ensure_output_dir(out_dir): + return + + options["cookies_args"] = cookies_args + options["proxy"] = config.get("proxy") + + try: + cmd = build_command(url, out_dir, options) + except ValueError as e: + messagebox.showwarning("İndirme Ayarları", str(e), parent=self) + return + + self.drawer.show(title="Playlist İndiriliyor...") + self.drawer.log_line(f"▶ Playlist Başlatıldı: {url}", "accent") + + self._start_engine(cmd, title="Playlist", url=url, fmt_desc=f"{options['format']} ({options['quality']})") + + def _get_download_cookies_args(self): + try: + return self.tabs["settings"].get_cookies_args() + except (OSError, ValueError) as e: + messagebox.showerror("Çerez Ayarı Hatası", str(e), parent=self) + return None + + def _ensure_output_dir(self, out_dir): + try: + os.makedirs(out_dir, exist_ok=True) + if not os.path.isdir(out_dir): + raise NotADirectoryError(f"Seçilen kayıt yolu bir klasör değil: {out_dir}") + return True + except OSError as e: + messagebox.showerror("Hata", f"Hedef klasör kullanılamıyor:\n{e}", parent=self) + return False + + def start_batch_download(self, urls, out_dir, options, status_cb): + if engine.is_running or self._batch_running: + messagebox.showinfo("Bilgi", "Zaten devam eden bir indirme var.", parent=self) + return + + cookies_args = self._get_download_cookies_args() + if cookies_args is None: + return + + if not self._ensure_output_dir(out_dir): + return + + options = dict(options) + options["cookies_args"] = cookies_args + options["proxy"] = config.get("proxy") + options["speed_limit"] = config.get("speed_limit") + options["ignore_errors"] = config.get("ignore_errors", True) + options["add_metadata"] = config.get("add_metadata", True) + options["embed_subtitles"] = config.get("embed_subtitles", False) + options["subtitle_lang"] = config.get("subtitle_lang", "tr,en") + options["concurrent_fragments"] = config.get("concurrent_fragments", 4) + + self._batch_running = True + self.drawer.show(title=f"Toplu İndirme (0/{len(urls)})") + + def _batch_worker(): + successes = 0 + failures = 0 + cancelled = False + last_processed = 0 + for idx, u in enumerate(urls, 1): + if not self._batch_running: + cancelled = True + break + + last_processed = idx + self.after(0, lambda i=idx: status_cb(i, "⏳ İndiriliyor...")) + self.after(0, lambda i=idx: self.drawer.lbl_title.config(text=f"Toplu İndirme [{i}/{len(urls)}]")) + + single_opts = dict(options) + event = threading.Event() + batch_success = False + batch_dest = None + batch_cancelled = False + batch_error = None + + def _on_done(success, output_path, err, cancelled): + nonlocal batch_success, batch_dest, batch_cancelled, batch_error + batch_success = success + batch_dest = output_path + batch_cancelled = cancelled + batch_error = err + event.set() + + try: + cmd = build_command(u, out_dir, single_opts) + except ValueError as e: + failures += 1 + self.after(0, lambda i=idx: status_cb(i, "❌ Hatalı ayar")) + self.after(0, lambda error=str(e): self.drawer.log_line(error, "error")) + continue + + def _start_item(): + if not self._batch_running: + _on_done(False, None, None, True) + return + if not self._start_engine_raw(cmd, done_callback=_on_done): + _on_done(False, None, "İndirme motoru başka bir işlemle meşgul.", False) + + self.after(0, _start_item) + event.wait() + + if batch_success: + successes += 1 + self.after(0, lambda i=idx: status_cb(i, "✅ Tamamlandı")) + history.add(os.path.basename(batch_dest or u), u, batch_dest, single_opts["format"]) + elif batch_cancelled: + cancelled = True + self.after(0, lambda i=idx: status_cb(i, "⛔ İptal edildi")) + break + else: + failures += 1 + self.after(0, lambda i=idx: status_cb(i, "❌ Hata")) + if batch_error: + self.after(0, lambda error=batch_error: self.drawer.log_line(error, "error")) + + if cancelled: + for idx in range(last_processed + 1, len(urls) + 1): + self.after(0, lambda i=idx: status_cb(i, "⏭ Atlandı")) + self._batch_running = False + overall_success = successes == len(urls) and not cancelled + self.after( + 0, + lambda: self.drawer.on_complete_status( + overall_success, + error_msg=f"{successes} başarılı, {failures} hatalı." if failures else None, + cancelled=cancelled + ) + ) + + threading.Thread(target=_batch_worker, daemon=True).start() + + def _start_engine(self, cmd, title, url, fmt_desc): + def _on_progress(pct, speed, total, eta): + self.after(0, lambda: self.drawer.update_stats(pct, speed, total, eta)) + + def _on_log(line, tag): + self.after(0, lambda: self.drawer.log_line(line, tag)) + + def _on_complete(success, output_path, err, cancelled): + self.current_download_file = output_path + self.after(0, lambda: self.drawer.on_complete_status(success, output_path, err, cancelled)) + if success: + history.add(title, url, output_path, fmt_desc, status="completed") + if "history" in self.tabs: + self.after(0, self.tabs["history"].refresh) + + callbacks = { + "on_progress": _on_progress, + "on_log": _on_log, + "on_complete": _on_complete + } + engine.start_download(cmd, callbacks) + + def _start_engine_raw(self, cmd, done_callback): + def _on_progress(pct, speed, total, eta): + self.after(0, lambda: self.drawer.update_stats(pct, speed, total, eta)) + + def _on_log(line, tag): + self.after(0, lambda: self.drawer.log_line(line, tag)) + + def _on_complete(success, output_path, err, cancelled): + if done_callback: + done_callback(success, output_path, err, cancelled) + + callbacks = { + "on_progress": _on_progress, + "on_log": _on_log, + "on_complete": _on_complete + } + return engine.start_download(cmd, callbacks) + + def _on_cancel_download(self): + if engine.is_running: + self.drawer.log_line("⛔ İptal ediliyor...", "warn") + engine.cancel() + self._batch_running = False + + def _open_downloaded_file(self): + if self.current_download_file: + history.show_in_folder(self.current_download_file) + + def _on_close(self): + if engine.is_running or self._batch_running: + if messagebox.askokcancel("Çıkış", "Devam eden bir indirme işlemi var. İptal edip çıkmak istiyor musunuz?", parent=self): + engine.cancel() + self._batch_running = False + self.destroy() + else: + self.destroy() + +def main(): + app = LDownloaderApp() + app.mainloop() + +if __name__ == "__main__": + main() diff --git a/ui/components.py b/ui/components.py new file mode 100644 index 0000000..57c1469 --- /dev/null +++ b/ui/components.py @@ -0,0 +1,604 @@ +import tkinter as tk +from tkinter import ttk +from PIL import Image, ImageTk +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, SURFACE_HOVER, ENTRY_BG, BORDER, BORDER_FOCUS, + ACCENT, ACCENT_LIGHT, ACCENT_HOVER, ACCENT_MUTED, ACCENT_GRADIENT, + TAB_BG, TAB_ACTIVE, TAB_HOVER, + TEXT, SUBTEXT, MUTED, + SUCCESS, SUCCESS_HOVER, WARNING, ERROR, DANGER_HOVER, + FONT_HERO, FONT_TITLE, FONT_SUBTITLE, FONT_REGULAR, FONT_BOLD, + FONT_SMALL, FONT_SMALL_BOLD, FONT_STAT, FONT_MONO +) + + +class Card(tk.Frame): + """Quiet surface container with a thin, low-contrast edge.""" + def __init__(self, parent, padx=20, pady=16, **kwargs): + super().__init__( + parent, + bg=SURFACE, + highlightthickness=1, + highlightbackground=BORDER, + padx=padx, + pady=pady, + **kwargs + ) + + +class PillButton(tk.Frame): + """Flat, high-contrast button with a clear hover and disabled state.""" + def __init__(self, parent, text="", command=None, style="secondary", small=False, **kwargs): + self.style_type = style + self._disabled = False + self.normal_bg, self.hover_bg, self.normal_fg, self.border_col = self._get_colors(style) + + font = FONT_SMALL_BOLD if small else FONT_BOLD + padx = 13 if small else (20 if style in ("primary", "accent", "danger") else 16) + pady = 7 if small else (11 if style in ("primary", "accent", "danger") else 9) + + super().__init__( + parent, + bg=self.normal_bg, + highlightthickness=0, + **kwargs + ) + self.command = command + + self.inner = tk.Label( + self, + text=text, + bg=self.normal_bg, + fg=self.normal_fg, + font=font, + padx=padx, + pady=pady, + cursor="hand2" + ) + self.inner.pack(fill="both", expand=True) + + self.inner.bind("", self._on_click) + self.inner.bind("", self._on_enter) + self.inner.bind("", self._on_leave) + + def _get_colors(self, style): + if style in ("primary", "accent"): + return ACCENT, ACCENT_HOVER, "#ffffff", ACCENT_LIGHT + elif style == "danger": + return ERROR, DANGER_HOVER, "#ffffff", ERROR + elif style == "success": + return SUCCESS, SUCCESS_HOVER, "#ffffff", SUCCESS + elif style == "ghost": + return SURFACE, SURFACE_HOVER, SUBTEXT, SURFACE + else: # secondary + return SURFACE_LIGHT, SURFACE_HOVER, TEXT, SURFACE_LIGHT + + def _on_click(self, event=None): + if not self._disabled and self.command: + self.command() + + def _on_enter(self, event=None): + if not self._disabled: + self.inner.config(bg=self.hover_bg) + self.config(bg=self.hover_bg) + + def _on_leave(self, event=None): + if not self._disabled: + self.inner.config(bg=self.normal_bg) + self.config(bg=self.normal_bg) + + def config(self, **kw): + if "text" in kw: + self.inner.config(text=kw.pop("text")) + if "state" in kw: + state = kw.pop("state") + self._disabled = (state == "disabled") + if self._disabled: + self.inner.config(fg=MUTED, cursor="") + else: + self.inner.config(fg=self.normal_fg, cursor="hand2") + if "style" in kw: + self.set_style(kw.pop("style")) + if "command" in kw: + self.command = kw.pop("command") + if kw: + super().config(**kw) + + def configure(self, **kw): + self.config(**kw) + + def set_style(self, style): + self.style_type = style + self.normal_bg, self.hover_bg, self.normal_fg, self.border_col = self._get_colors(style) + self.config(bg=self.normal_bg, highlightbackground=self.border_col) + self.inner.config(bg=self.normal_bg, fg=self.normal_fg) + + +class PillChip(tk.Frame): + """Modern tıklanabilir aç/kapa ayar etiketi (çip).""" + def __init__(self, parent, text, initial_value=False, on_toggle=None, **kwargs): + super().__init__(parent, bg=SURFACE_LIGHT, padx=12, pady=7, cursor="hand2", **kwargs) + self.text = text + self.value = initial_value + self.on_toggle = on_toggle + + bg_col = ACCENT_MUTED if self.value else SURFACE_LIGHT + + self.config( + highlightthickness=0, + bg=bg_col + ) + + self.label = tk.Label( + self, + text=f"{'✓ ' if self.value else ''}{self.text}", + bg=bg_col, + fg=(ACCENT_LIGHT if self.value else SUBTEXT), + font=FONT_SMALL_BOLD, + cursor="hand2" + ) + self.label.pack() + + for w in (self, self.label): + w.bind("", self._toggle) + w.bind("", self._on_enter) + w.bind("", self._on_leave) + + def _toggle(self, event=None): + self.value = not self.value + self._update_state() + if self.on_toggle: + self.on_toggle(self.value) + + def _update_state(self): + bg_col = ACCENT_MUTED if self.value else SURFACE_LIGHT + fg_col = ACCENT_LIGHT if self.value else SUBTEXT + prefix = "✓ " if self.value else "" + + self.config(bg=bg_col) + self.label.config(bg=bg_col, fg=fg_col, text=f"{prefix}{self.text}") + + def _on_enter(self, event=None): + if not self.value: + self.config(bg=SURFACE_HOVER) + self.label.config(bg=SURFACE_HOVER, fg=TEXT) + + def _on_leave(self, event=None): + if not self.value: + self.config(bg=SURFACE_LIGHT) + self.label.config(bg=SURFACE_LIGHT, fg=SUBTEXT) + + def get(self): + return self.value + + def set(self, val): + self.value = bool(val) + self._update_state() + + +class ModernEntry(tk.Entry): + """Zarif gömülü derinlik ve odaklanma çerçevesine sahip girdi alanı.""" + def __init__(self, parent, textvariable=None, placeholder=None, on_change=None, **kwargs): + self.placeholder = placeholder + self.has_placeholder = False + self.on_change = on_change + + kwargs.setdefault("bg", ENTRY_BG) + kwargs.setdefault("fg", TEXT) + kwargs.setdefault("insertbackground", ACCENT_LIGHT) + kwargs.setdefault("selectbackground", ACCENT) + kwargs.setdefault("selectforeground", "#ffffff") + kwargs.setdefault("relief", "flat") + kwargs.setdefault("bd", 0) + kwargs.setdefault("font", FONT_REGULAR) + kwargs.setdefault("highlightthickness", 1) + kwargs.setdefault("highlightbackground", BORDER) + kwargs.setdefault("highlightcolor", BORDER_FOCUS) + + super().__init__(parent, textvariable=textvariable, **kwargs) + + if placeholder: + self._apply_placeholder() + self.bind("", self._on_focus_in) + self.bind("", self._on_focus_out) + + if on_change: + self.bind("", lambda e: on_change(self.get_clean_text())) + + def _apply_placeholder(self): + val = self.get() + if not val or val == self.placeholder: + self.delete(0, "end") + self.insert(0, self.placeholder) + self.config(fg=MUTED) + self.has_placeholder = True + + def _on_focus_in(self, event): + if self.has_placeholder: + self.delete(0, "end") + self.config(fg=TEXT) + self.has_placeholder = False + + def _on_focus_out(self, event): + if not self.get().strip(): + self._apply_placeholder() + + def get_clean_text(self): + val = self.get().strip() + if self.has_placeholder or val == self.placeholder: + return "" + return val + + def set_text(self, text): + self.delete(0, "end") + self.insert(0, text) + self.config(fg=TEXT) + self.has_placeholder = False + if self.on_change: + self.on_change(text) + + +class TabButton(tk.Frame): + """Rounded-feel navigation item using a soft active-state surface.""" + def __init__(self, parent, icon, text, command=None, is_active=False): + super().__init__(parent, bg=TAB_BG, cursor="hand2") + self.command = command + self.is_active = is_active + + active_bg = TAB_ACTIVE if is_active else TAB_BG + active_fg = ACCENT_LIGHT if is_active else SUBTEXT + + self.content = tk.Frame(self, bg=active_bg, padx=15, pady=10) + self.content.pack(fill="both", expand=True) + + self.lbl_icon = tk.Label( + self.content, text=icon, font=("Segoe UI", 11), + bg=active_bg, fg=active_fg + ) + self.lbl_icon.pack(side="left", padx=(0, 6)) + + self.lbl_text = tk.Label( + self.content, text=text, + font=FONT_BOLD if is_active else FONT_REGULAR, + bg=active_bg, + fg=(TEXT if is_active else SUBTEXT) + ) + self.lbl_text.pack(side="left") + + self.indicator = tk.Frame(self, bg=TAB_BG, height=2) + self.indicator.pack(fill="x", side="bottom") + + for w in (self, self.content, self.lbl_icon, self.lbl_text): + w.bind("", lambda e: self._click()) + w.bind("", lambda e: self._enter()) + w.bind("", lambda e: self._leave()) + + def _click(self): + if self.command: + self.command() + + def set_active(self, active): + self.is_active = active + bg_col = TAB_ACTIVE if active else TAB_BG + fg_col = TEXT if active else SUBTEXT + icon_col = ACCENT_LIGHT if active else SUBTEXT + ind_col = TAB_BG + font = FONT_BOLD if active else FONT_REGULAR + + self.config(bg=TAB_BG) + self.content.config(bg=bg_col) + self.lbl_icon.config(bg=bg_col, fg=icon_col) + self.lbl_text.config(bg=bg_col, fg=fg_col, font=font) + self.indicator.config(bg=ind_col) + + def _enter(self): + if not self.is_active: + self.content.config(bg=TAB_HOVER) + self.lbl_icon.config(bg=TAB_HOVER, fg=ACCENT_LIGHT) + self.lbl_text.config(bg=TAB_HOVER, fg=TEXT) + + def _leave(self): + if not self.is_active: + self.content.config(bg=TAB_BG) + self.lbl_icon.config(bg=TAB_BG, fg=SUBTEXT) + self.lbl_text.config(bg=TAB_BG, fg=SUBTEXT) + + +# Geriye dönük uyumluluk +SidebarButton = TabButton + + +class SegmentedPill(tk.Frame): + """Modern segmented buton denetleyicisi.""" + def __init__(self, parent, items, default_val=None, on_change=None, **kwargs): + super().__init__( + parent, + bg=SURFACE_LIGHT, + padx=3, + pady=3, + highlightthickness=0, + **kwargs + ) + self.items = items + self.on_change = on_change + self.selected_key = default_val if default_val else items[0][0] + self.buttons = {} + + for key, label in self.items: + btn = tk.Label( + self, + text=label, + font=FONT_SMALL_BOLD, + padx=14, + pady=7, + cursor="hand2" + ) + btn.pack(side="left", padx=1) + btn.bind("", lambda e, k=key: self.select(k)) + btn.bind("", lambda e, k=key: self._hover_on(k)) + btn.bind("", lambda e, k=key: self._hover_off(k)) + self.buttons[key] = btn + + self._update_ui() + + def select(self, key): + if self.selected_key != key: + self.selected_key = key + self._update_ui() + if self.on_change: + self.on_change(key) + + def _update_ui(self): + for k, btn in self.buttons.items(): + if k == self.selected_key: + btn.config(bg=ACCENT, fg="#ffffff") + else: + btn.config(bg=SURFACE_LIGHT, fg=SUBTEXT) + + def _hover_on(self, key): + if key != self.selected_key: + self.buttons[key].config(bg=SURFACE_HOVER, fg=TEXT) + + def _hover_off(self, key): + if key != self.selected_key: + self.buttons[key].config(bg=SURFACE_LIGHT, fg=SUBTEXT) + + def get(self): + return self.selected_key + + +class VideoPreviewCard(Card): + """Video önizleme kartı (Küçük resim, Başlık, Kanal, Süre).""" + def __init__(self, parent, **kwargs): + super().__init__(parent, padx=14, pady=10, **kwargs) + self.thumb_photo = None + + # Sol: Thumbnail + self.thumb_label = tk.Label( + self, + bg=SURFACE_LIGHT, + width=160, + height=90, + highlightthickness=1, + highlightbackground=BORDER + ) + self.thumb_label.pack(side="left", padx=(0, 14)) + + # Sağ: Bilgiler + info_frame = tk.Frame(self, bg=SURFACE) + info_frame.pack(side="left", fill="both", expand=True) + + self.title_label = tk.Label( + info_frame, text="", bg=SURFACE, fg=TEXT, font=FONT_BOLD, + anchor="w", justify="left", wraplength=440 + ) + self.title_label.pack(fill="x", anchor="w") + + self.uploader_label = tk.Label( + info_frame, text="", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL, anchor="w" + ) + self.uploader_label.pack(fill="x", anchor="w", pady=(3, 6)) + + badge_row = tk.Frame(info_frame, bg=SURFACE) + badge_row.pack(fill="x", anchor="w") + + self.duration_badge = tk.Label( + badge_row, text="", bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + font=FONT_SMALL_BOLD, padx=8, pady=2, + highlightthickness=1, highlightbackground=BORDER + ) + self.duration_badge.pack(side="left") + + self.res_count_badge = tk.Label( + badge_row, text="", bg=ACCENT_MUTED, fg=SUCCESS, + font=FONT_SMALL, padx=8, pady=2, + highlightthickness=1, highlightbackground=BORDER + ) + self.res_count_badge.pack(side="left", padx=(8, 0)) + + def update_metadata(self, metadata): + self.title_label.config(text=metadata.get("title", "—")) + self.uploader_label.config(text=f"👤 {metadata.get('uploader', '—')}") + self.duration_badge.config(text=f"⏱ {metadata.get('duration', '—')}") + + resolutions = metadata.get("resolutions", []) + if resolutions and len(resolutions) > 1: + self.res_count_badge.config(text=f"🎬 {len(resolutions)-1} Çözünürlük") + self.res_count_badge.pack(side="left", padx=(8, 0)) + else: + self.res_count_badge.pack_forget() + + thumb_img = metadata.get("thumbnail_img") + if thumb_img: + self.thumb_photo = ImageTk.PhotoImage(thumb_img) + self.thumb_label.config(image=self.thumb_photo, width=160, height=90) + else: + self.thumb_label.config(image="", text="Görsel Yok", fg=SUBTEXT, width=20, height=5) + + +class ContextualDownloadDrawer(tk.Frame): + """ + Akıllı alt indirme çekmecesi — sadece indirme sırasında görünür. + Konsol akordeon şeklinde açılıp kapanabilir. + """ + def __init__(self, parent, on_cancel=None, on_open_file=None, **kwargs): + super().__init__( + parent, + bg=SURFACE, + highlightthickness=1, + highlightbackground=BORDER, + padx=16, + pady=10, + **kwargs + ) + self.on_cancel = on_cancel + self.on_open_file = on_open_file + self.console_open = False + + # Üst Bilgi Satırı + top_row = tk.Frame(self, bg=SURFACE) + top_row.pack(fill="x", pady=(0, 4)) + + self.lbl_title = tk.Label(top_row, text="İndirme Başlatılıyor...", bg=SURFACE, fg=TEXT, font=FONT_BOLD, anchor="w") + self.lbl_title.pack(side="left", fill="x", expand=True) + + self.pct_var = tk.StringVar(value="0%") + self.lbl_pct = tk.Label(top_row, textvariable=self.pct_var, bg=SURFACE, fg=ACCENT_LIGHT, font=FONT_STAT) + self.lbl_pct.pack(side="right", padx=(8, 0)) + + # İlerleme Çubuğu + self.pbar = ttk.Progressbar(self, style="Custom.Horizontal.TProgressbar", mode="determinate", maximum=100) + self.pbar.pack(fill="x", pady=(3, 6)) + + # İstatistikler ve Butonlar + bot_row = tk.Frame(self, bg=SURFACE) + bot_row.pack(fill="x") + + stat_frame = tk.Frame(bot_row, bg=SURFACE) + stat_frame.pack(side="left") + + self.speed_var = tk.StringVar(value="⚡ —") + self.lbl_speed = tk.Label( + stat_frame, textvariable=self.speed_var, bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + font=FONT_SMALL, padx=8, pady=3, + highlightthickness=1, highlightbackground=BORDER + ) + self.lbl_speed.pack(side="left", padx=(0, 6)) + + self.dl_var = tk.StringVar(value="📥 —") + self.lbl_dl = tk.Label( + stat_frame, textvariable=self.dl_var, bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + font=FONT_SMALL, padx=8, pady=3, + highlightthickness=1, highlightbackground=BORDER + ) + self.lbl_dl.pack(side="left", padx=(0, 6)) + + self.eta_var = tk.StringVar(value="⏱ —") + self.lbl_eta = tk.Label( + stat_frame, textvariable=self.eta_var, bg=ACCENT_MUTED, fg=ACCENT_LIGHT, + font=FONT_SMALL, padx=8, pady=3, + highlightthickness=1, highlightbackground=BORDER + ) + self.lbl_eta.pack(side="left") + + # Sağ Butonlar + action_frame = tk.Frame(bot_row, bg=SURFACE) + action_frame.pack(side="right") + + self.btn_open = PillButton(action_frame, text="📁 Klasörde Göster", command=self._open_file_click, small=True, style="success") + self.btn_cancel = PillButton(action_frame, text="⛔ İptal Et", command=self._cancel_click, small=True, style="danger") + self.btn_cancel.pack(side="left", padx=(0, 6)) + + self.btn_console_toggle = PillButton(action_frame, text="▲ Konsol", command=self._toggle_console, small=True, style="secondary") + self.btn_console_toggle.pack(side="left") + + self.btn_close = PillButton(action_frame, text="✕", command=self.hide, small=True, style="ghost") + + # Konsol Çekmecesi (Başlangıçta Gizli) + self.console_frame = tk.Frame(self, bg=ENTRY_BG, highlightthickness=1, highlightbackground=BORDER) + + csb = ttk.Scrollbar(self.console_frame, style="Vertical.TScrollbar") + csb.pack(side="right", fill="y") + + self.log_text = tk.Text( + self.console_frame, bg=ENTRY_BG, fg=TEXT, font=FONT_MONO, + insertbackground=TEXT, selectbackground=ACCENT, relief="flat", bd=0, + wrap="word", height=6, yscrollcommand=csb.set, state="disabled" + ) + self.log_text.pack(fill="both", expand=True, padx=6, pady=6) + csb.config(command=self.log_text.yview) + + self.log_text.tag_config("info", foreground=TEXT) + self.log_text.tag_config("success", foreground=SUCCESS) + self.log_text.tag_config("warn", foreground=WARNING) + self.log_text.tag_config("error", foreground=ERROR) + self.log_text.tag_config("accent", foreground=ACCENT_LIGHT) + + def show(self, title="İndirme"): + self.lbl_title.config(text=f"⏳ {title}") + self.pbar["value"] = 0 + self.pct_var.set("0%") + self.speed_var.set("⚡ —") + self.dl_var.set("📥 —") + self.eta_var.set("⏱ —") + self.btn_open.pack_forget() + self.btn_cancel.pack(side="left", padx=(0, 6)) + self.btn_close.pack_forget() + self.pack(fill="x", side="bottom") + + def hide(self): + self.pack_forget() + if self.console_open: + self._toggle_console() + + def update_stats(self, pct, speed, total, eta): + self.pbar["value"] = pct + self.pct_var.set(f"{pct:.1f}%") + self.speed_var.set(f"⚡ {speed}") + self.dl_var.set(f"📥 {pct:.1f}% / {total}") + self.eta_var.set(f"⏱ {eta}") + + def on_complete_status(self, success, output_path=None, error_msg=None, cancelled=False): + self.btn_cancel.pack_forget() + if cancelled: + self.lbl_title.config(text="⛔ İndirme kullanıcı tarafından iptal edildi.") + self.btn_close.pack(side="left", padx=(6, 0)) + elif success: + self.pbar["value"] = 100 + self.pct_var.set("100%") + self.lbl_title.config(text="✅ İndirme başarıyla tamamlandı!") + self.btn_open.pack(side="left", padx=(0, 6)) + self.btn_close.pack(side="left") + else: + self.lbl_title.config(text=f"❌ Hata: {error_msg or 'İndirme başarısız oldu'}") + self.btn_close.pack(side="left", padx=(6, 0)) + + def log_line(self, line, tag="info"): + self.log_text.config(state="normal") + self.log_text.insert("end", line + "\n", tag) + try: + num = int(self.log_text.index("end-1c").split(".")[0]) + if num > 1000: + self.log_text.delete("1.0", f"{num - 1000}.0") + except Exception: + pass + self.log_text.see("end") + self.log_text.config(state="disabled") + + def _toggle_console(self): + if self.console_open: + self.console_frame.pack_forget() + self.btn_console_toggle.config(text="▲ Konsol") + self.console_open = False + else: + self.console_frame.pack(fill="x", pady=(8, 0)) + self.btn_console_toggle.config(text="▼ Konsol") + self.console_open = True + + def _cancel_click(self): + if self.on_cancel: + self.on_cancel() + + def _open_file_click(self): + if self.on_open_file: + self.on_open_file() diff --git a/ui/tabs/__init__.py b/ui/tabs/__init__.py new file mode 100644 index 0000000..75b6f88 --- /dev/null +++ b/ui/tabs/__init__.py @@ -0,0 +1 @@ +"""LDownloader Tabs""" diff --git a/ui/tabs/batch_tab.py b/ui/tabs/batch_tab.py new file mode 100644 index 0000000..20b9fb0 --- /dev/null +++ b/ui/tabs/batch_tab.py @@ -0,0 +1,169 @@ +import tkinter as tk +from tkinter import ttk, messagebox +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, ACCENT, ACCENT_LIGHT, TEXT, SUBTEXT, SUCCESS, ERROR, WARNING, + FONT_HERO, FONT_TITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD +) +from ui.components import Card, PillButton, SegmentedPill +from core.config import config + +class BatchTab(tk.Frame): + def __init__(self, parent, on_batch_requested=None, **kwargs): + super().__init__(parent, bg=BG, **kwargs) + self.on_batch_requested = on_batch_requested + self.queue = [] + self._build_ui() + + def _build_ui(self): + # ── Başlık ─────────────────────────────────────────────────── + hdr = tk.Frame(self, bg=BG) + hdr.pack(fill="x", padx=32, pady=(28, 22)) + + tk.Label(hdr, text="Toplu indirme", bg=BG, fg=TEXT, font=FONT_HERO).pack(anchor="w") + tk.Label(hdr, text="Bağlantıları ekleyin; uygulama sırayla indirsin.", + bg=BG, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 0)) + + # ── 1. URL Giriş Kartı ────────────────────────────────────── + c_input = Card(self) + c_input.pack(fill="x", padx=32, pady=(0, 16)) + + top = tk.Frame(c_input, bg=SURFACE) + top.pack(fill="x") + + tk.Label(top, text="BAĞLANTILAR", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(side="left") + + PillButton(top, text="Temizle", command=self._clear_input, small=True, style="ghost").pack(side="right") + PillButton(top, text="Panodan ekle", command=self._paste_clipboard, small=True, style="secondary").pack(side="right", padx=(0, 8)) + + self.text_input = tk.Text( + c_input, bg=ENTRY_BG, fg=TEXT, insertbackground=ACCENT_LIGHT, selectbackground=ACCENT, + relief="flat", bd=0, font=("Consolas", 10), height=5, + highlightthickness=1, highlightbackground=BORDER, highlightcolor=ACCENT + ) + self.text_input.pack(fill="x", pady=(10, 0)) + + # ── 2. Format ve Ekle Çubuğu ──────────────────────────────── + c_act = Card(self) + c_act.pack(fill="x", padx=32, pady=(0, 16)) + + arow = tk.Frame(c_act, bg=SURFACE) + arow.pack(fill="x") + + tk.Label(arow, text="Format:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.media_seg = SegmentedPill( + arow, + items=[("video", "Video"), ("audio", "Ses")], + default_val="video" + ) + self.media_seg.pack(side="left", padx=(10, 20)) + + PillButton(arow, text="➕ Kuyruğa Ekle", command=self._add_to_queue, style="secondary").pack(side="right") + + # ── 3. Kuyruk Listesi ──────────────────────────────────────── + c_queue = Card(self) + c_queue.pack(fill="both", expand=True, padx=32, pady=(0, 18)) + + q_top = tk.Frame(c_queue, bg=SURFACE) + q_top.pack(fill="x", pady=(0, 8)) + self.lbl_queue_count = tk.Label(q_top, text="Kuyruk · 0 öğe", bg=SURFACE, fg=TEXT, font=FONT_BOLD) + self.lbl_queue_count.pack(side="left") + + PillButton(q_top, text="Kuyruğu temizle", command=self._clear_queue, small=True, style="ghost").pack(side="right") + + tree_frame = tk.Frame(c_queue, bg=SURFACE) + tree_frame.pack(fill="both", expand=True) + + columns = ("no", "url", "status") + self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", height=5) + self.tree.heading("no", text="#") + self.tree.heading("url", text="Bağlantı URL'si") + self.tree.heading("status", text="Durum") + + self.tree.column("no", width=40, anchor="center") + self.tree.column("url", width=480, anchor="w") + self.tree.column("status", width=120, anchor="center") + + sb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview, style="Vertical.TScrollbar") + self.tree.configure(yscrollcommand=sb.set) + + self.tree.pack(side="left", fill="both", expand=True) + sb.pack(side="right", fill="y") + + # ── 4. Başlat Butonu ───────────────────────────────────────── + PillButton( + self, + text="Tümünü indirmeye başla", + command=self._on_start_batch, + style="primary" + ).pack(fill="x", padx=32, pady=(0, 24), ipady=3) + + def _paste_clipboard(self): + try: + clip = self.clipboard_get().strip() + if clip: + self.text_input.insert("end", clip + "\n") + except Exception: + pass + + def _clear_input(self): + self.text_input.delete("1.0", "end") + + def _add_to_queue(self): + raw = self.text_input.get("1.0", "end").strip() + if not raw: + return + lines = [line.strip() for line in raw.splitlines() if line.strip() and line.strip().startswith("http")] + if not lines: + messagebox.showinfo("Bilgi", "Geçerli bir http/https bağlantısı bulunamadı.", parent=self) + return + + for u in lines: + idx = len(self.queue) + 1 + item = {"idx": idx, "url": u, "status": "⏳ Bekliyor"} + self.queue.append(item) + self.tree.insert("", "end", iid=str(idx), values=(idx, u, "⏳ Bekliyor")) + + self.lbl_queue_count.config(text=f"Kuyruk · {len(self.queue)} öğe") + self.text_input.delete("1.0", "end") + + def _clear_queue(self): + self.queue.clear() + for i in self.tree.get_children(): + self.tree.delete(i) + self.lbl_queue_count.config(text="Kuyruk · 0 öğe") + + def update_item_status(self, idx, status_text): + for item in self.queue: + if item["idx"] == idx: + item["status"] = status_text + try: + self.tree.item(str(idx), values=(idx, item["url"], status_text)) + except Exception: + pass + break + + def _on_start_batch(self): + if not self.queue: + self._add_to_queue() + if not self.queue: + messagebox.showwarning("Uyarı", "Kuyrukta indirilecek geçerli bağlantı yok!", parent=self) + return + + urls = [item["url"] for item in self.queue] + media_type = self.media_seg.get() + options = { + "mode": "batch", + "media_type": media_type, + "format": config.get("video_format", "mp4") if media_type == "video" else config.get("audio_format", "mp3"), + "quality": config.get("video_quality", "Best Quality (En İyi)") if media_type == "video" else config.get("audio_quality", "Best Quality (En İyi)"), + "embed_thumbnail": config.get("embed_thumbnail", True), + "embed_subtitles": config.get("embed_subtitles", False), + "subtitle_lang": config.get("subtitle_lang", "tr,en"), + "add_metadata": config.get("add_metadata", True), + "concurrent_fragments": config.get("concurrent_fragments", 4), + "speed_limit": config.get("speed_limit", ""), + "ignore_errors": config.get("ignore_errors", True) + } + + if self.on_batch_requested: + self.on_batch_requested(urls, config.get("download_dir"), options, self.update_item_status) diff --git a/ui/tabs/history_tab.py b/ui/tabs/history_tab.py new file mode 100644 index 0000000..1476700 --- /dev/null +++ b/ui/tabs/history_tab.py @@ -0,0 +1,143 @@ +import tkinter as tk +from tkinter import ttk, messagebox +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, ACCENT, ACCENT_LIGHT, TEXT, SUBTEXT, MUTED, SUCCESS, ERROR, + FONT_HERO, FONT_TITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD +) +from ui.components import Card, PillButton, ModernEntry +from core.history import history + +class HistoryTab(tk.Frame): + def __init__(self, parent, **kwargs): + super().__init__(parent, bg=BG, **kwargs) + self.search_query = "" + self._build_ui() + self.refresh() + + def _build_ui(self): + # ── Başlık ─────────────────────────────────────────────────── + hdr = tk.Frame(self, bg=BG) + hdr.pack(fill="x", padx=32, pady=(28, 22)) + + tk.Label(hdr, text="İndirme geçmişi", bg=BG, fg=TEXT, font=FONT_HERO).pack(anchor="w") + tk.Label(hdr, text="İndirdiklerinizi bulun, açın veya kayıt konumuna gidin.", + bg=BG, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 0)) + + # ── Arama Kartı ────────────────────────────────────────────── + c_search = Card(self) + c_search.pack(fill="x", padx=32, pady=(0, 16)) + + s_row = tk.Frame(c_search, bg=SURFACE) + s_row.pack(fill="x") + + self.search_var = tk.StringVar() + self.search_entry = ModernEntry( + s_row, textvariable=self.search_var, + placeholder="Başlık veya formata göre ara", + on_change=self._on_search_typed + ) + self.search_entry.pack(side="left", fill="x", expand=True) + + PillButton(s_row, text="Yenile", command=self.refresh, small=True, style="secondary").pack(side="left", padx=(10, 0)) + PillButton(s_row, text="Tümünü sil", command=self._clear_all, small=True, style="danger").pack(side="left", padx=(8, 0)) + + # ── Tablo Kartı ────────────────────────────────────────────── + c_table = Card(self) + c_table.pack(fill="both", expand=True, padx=32, pady=(0, 18)) + + t_top = tk.Frame(c_table, bg=SURFACE) + t_top.pack(fill="x", pady=(0, 8)) + + self.lbl_count = tk.Label(t_top, text="Kayıtlar (0)", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD) + self.lbl_count.pack(side="left") + + tree_frame = tk.Frame(c_table, bg=SURFACE) + tree_frame.pack(fill="both", expand=True) + + columns = ("date", "title", "format", "size", "status") + self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", selectmode="browse") + self.tree.heading("date", text="Tarih") + self.tree.heading("title", text="Dosya / Video Başlığı") + self.tree.heading("format", text="Format") + self.tree.heading("size", text="Boyut") + self.tree.heading("status", text="Durum") + + self.tree.column("date", width=120, anchor="center") + self.tree.column("title", width=380, anchor="w") + self.tree.column("format", width=100, anchor="center") + self.tree.column("size", width=80, anchor="center") + self.tree.column("status", width=90, anchor="center") + + sb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview, style="Vertical.TScrollbar") + self.tree.configure(yscrollcommand=sb.set) + + self.tree.pack(side="left", fill="both", expand=True) + sb.pack(side="right", fill="y") + + self.tree.bind("", lambda e: self._play_selected()) + + # ── Alt Eylem Çubuğu ───────────────────────────────────────── + act_bar = tk.Frame(self, bg=BG) + act_bar.pack(fill="x", padx=32, pady=(0, 24)) + + PillButton(act_bar, text="Dosyayı aç", command=self._play_selected, style="primary").pack(side="left", padx=(0, 10)) + PillButton(act_bar, text="Klasörde göster", command=self._open_folder_selected, style="secondary").pack(side="left", padx=(0, 10)) + PillButton(act_bar, text="Listeden kaldır", command=self._remove_selected, style="ghost").pack(side="left") + + def _on_search_typed(self, text): + self.search_query = text.lower().strip() + self.refresh() + + def refresh(self): + for item in self.tree.get_children(): + self.tree.delete(item) + + items = history.get_all() + if self.search_query: + items = [i for i in items if self.search_query in i.get("title", "").lower() or self.search_query in i.get("format", "").lower()] + + self.lbl_count.config(text=f"Kayıtlar ({len(items)})") + + for it in items: + status_text = "✅ Başarılı" if it.get("status") == "completed" else "❌ Hata" + self.tree.insert("", "end", iid=it["id"], values=( + it.get("date", "—"), + it.get("title", "—"), + it.get("format", "—"), + it.get("size", "—"), + status_text + )) + + def _get_selected_item(self): + sel = self.tree.selection() + if not sel: + messagebox.showinfo("Bilgi", "Lütfen listeden bir kayıt seçin.", parent=self) + return None + item_id = sel[0] + for it in history.get_all(): + if it.get("id") == item_id: + return it + return None + + def _play_selected(self): + it = self._get_selected_item() + if it: + if not history.play_file(it.get("path")): + messagebox.showerror("Hata", f"Dosya bulunamadı veya açılamadı:\n{it.get('path')}", parent=self) + + def _open_folder_selected(self): + it = self._get_selected_item() + if it: + if not history.show_in_folder(it.get("path")): + messagebox.showerror("Hata", f"Hedef klasör açılamadı:\n{it.get('path')}", parent=self) + + def _remove_selected(self): + sel = self.tree.selection() + if sel: + history.remove(sel[0]) + self.refresh() + + def _clear_all(self): + if messagebox.askyesno("Onay", "Tüm indirme geçmişini silmek istediğinize emin misiniz?", parent=self): + history.clear() + self.refresh() diff --git a/ui/tabs/playlist_tab.py b/ui/tabs/playlist_tab.py new file mode 100644 index 0000000..1f06ddc --- /dev/null +++ b/ui/tabs/playlist_tab.py @@ -0,0 +1,178 @@ +import tkinter as tk +from tkinter import ttk, filedialog, messagebox +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, ACCENT, ACCENT_LIGHT, TEXT, SUBTEXT, + FONT_HERO, FONT_TITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD +) +from ui.components import Card, PillButton, PillChip, ModernEntry, SegmentedPill +from core.config import config + +class PlaylistTab(tk.Frame): + def __init__(self, parent, on_download_requested=None, **kwargs): + super().__init__(parent, bg=BG, **kwargs) + self.on_download_requested = on_download_requested + self._build_ui() + + def _build_ui(self): + # ── Başlık ─────────────────────────────────────────────────── + hdr = tk.Frame(self, bg=BG) + hdr.pack(fill="x", padx=32, pady=(28, 22)) + + tk.Label(hdr, text="Oynatma listesi", bg=BG, fg=TEXT, font=FONT_HERO).pack(anchor="w") + tk.Label(hdr, text="İndirmek istediğiniz aralığı seçin; videolar liste düzeninde kaydedilsin.", + bg=BG, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 0)) + + # ── 1. Playlist URL ───────────────────────────────────────── + c_url = Card(self) + c_url.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_url, text="OYNATMA LİSTESİ BAĞLANTISI", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + + row = tk.Frame(c_url, bg=SURFACE) + row.pack(fill="x", pady=(8, 0)) + + self.url_var = tk.StringVar() + self.url_entry = ModernEntry(row, textvariable=self.url_var, placeholder="https://youtube.com/playlist?list=...") + self.url_entry.pack(side="left", fill="x", expand=True) + + PillButton(row, text="Yapıştır", command=self._paste_clipboard, small=True, style="secondary").pack(side="left", padx=(10, 0)) + PillButton(row, text="Temizle", command=self._clear_url, small=True, style="ghost").pack(side="left", padx=(6, 0)) + + # ── 2. Format ve Kalite ───────────────────────────────────── + c_fmt = Card(self) + c_fmt.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_fmt, text="FORMAT VE KALİTE", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + + frow = tk.Frame(c_fmt, bg=SURFACE) + frow.pack(fill="x", pady=(10, 0)) + + self.media_seg = SegmentedPill( + frow, + items=[("video", "Video"), ("audio", "Ses")], + default_val="video", + on_change=self._on_media_type_changed + ) + self.media_seg.pack(side="left") + + self.video_opts_frame = tk.Frame(frow, bg=SURFACE) + self.video_opts_frame.pack(side="left", padx=(20, 0)) + + tk.Label(self.video_opts_frame, text="Çözünürlük:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.res_var = tk.StringVar(value=config.get("video_quality", "Best Quality (En İyi)")) + self.res_cb = ttk.Combobox( + self.video_opts_frame, textvariable=self.res_var, + values=["Best Quality (En İyi)", "4320p (8K)", "2160p (4K)", "1440p (2K)", "1080p (FHD)", "720p (HD)", "480p", "360p"], + state="readonly", width=20, font=FONT_REGULAR + ) + self.res_cb.pack(side="left", padx=(6, 0)) + self.res_cb.bind("<>", lambda e: config.set("video_quality", self.res_var.get())) + + self.audio_opts_frame = tk.Frame(frow, bg=SURFACE) + tk.Label(self.audio_opts_frame, text="Kalite:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.audio_qual_var = tk.StringVar(value=config.get("audio_quality", "Best Quality (En İyi)")) + self.audio_qual_cb = ttk.Combobox( + self.audio_opts_frame, textvariable=self.audio_qual_var, + values=["Best Quality (En İyi)", "320 kbps", "256 kbps", "192 kbps", "128 kbps"], + state="readonly", width=20, font=FONT_REGULAR + ) + self.audio_qual_cb.pack(side="left", padx=(6, 0)) + self.audio_qual_cb.bind("<>", lambda e: config.set("audio_quality", self.audio_qual_var.get())) + + # ── 3. Aralık ve Seçenekler ───────────────────────────────── + c_range = Card(self) + c_range.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_range, text="İNDİRME ARALIĞI VE SEÇENEKLER", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + + rrow = tk.Frame(c_range, bg=SURFACE) + rrow.pack(fill="x", pady=(10, 0)) + + tk.Label(rrow, text="Başlangıç:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.start_var = tk.StringVar() + ModernEntry(rrow, textvariable=self.start_var, width=5, placeholder="1").pack(side="left", padx=(6, 20)) + + tk.Label(rrow, text="Bitiş:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.end_var = tk.StringVar() + ModernEntry(rrow, textvariable=self.end_var, width=5, placeholder="Son").pack(side="left", padx=(6, 24)) + + self.chip_ignore = PillChip(rrow, text="Hatalı öğeleri atla", initial_value=True) + self.chip_ignore.pack(side="left", padx=(0, 10)) + + self.chip_turbo = PillChip(rrow, text="Çok parçalı indirme", initial_value=True) + self.chip_turbo.pack(side="left") + + # ── 4. Kayıt Klasörü ──────────────────────────────────────── + c_dir = Card(self) + c_dir.pack(fill="x", padx=32, pady=(0, 18)) + + tk.Label(c_dir, text="KAYIT KLASÖRÜ · LİSTE ADIYLA ALT KLASÖR OLUŞTURULUR", + bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + drow = tk.Frame(c_dir, bg=SURFACE) + drow.pack(fill="x", pady=(8, 0)) + + self.dir_var = tk.StringVar(value=config.get("download_dir")) + ModernEntry(drow, textvariable=self.dir_var).pack(side="left", fill="x", expand=True) + + PillButton(drow, text="Klasör seç", command=self._choose_dir, small=True).pack(side="left", padx=(10, 0)) + + # ── 5. İndirme Butonu ──────────────────────────────────────── + PillButton( + self, + text="Listeyi indirmeye başla", + command=self._on_start_click, + style="primary" + ).pack(fill="x", padx=32, pady=(0, 24), ipady=3) + + def _on_media_type_changed(self, media_type): + if media_type == "video": + self.audio_opts_frame.pack_forget() + self.video_opts_frame.pack(side="left", padx=(20, 0)) + else: + self.video_opts_frame.pack_forget() + self.audio_opts_frame.pack(side="left", padx=(20, 0)) + + def _paste_clipboard(self): + try: + clip = self.clipboard_get().strip() + if clip: + self.url_entry.set_text(clip) + except Exception: + pass + + def _clear_url(self): + self.url_entry.delete(0, "end") + self.url_entry._apply_placeholder() + + def _choose_dir(self): + d = filedialog.askdirectory(initialdir=self.dir_var.get() or config.get("download_dir")) + if d: + self.dir_var.set(d) + + def _on_start_click(self): + url = self.url_entry.get_clean_text() + if not url: + messagebox.showwarning("Uyarı", "Lütfen geçerli bir playlist URL'si girin.", parent=self) + return + + out_dir = self.dir_var.get().strip() or config.get("download_dir") + media_type = self.media_seg.get() + + options = { + "mode": "playlist", + "media_type": media_type, + "format": config.get("video_format", "mp4") if media_type == "video" else config.get("audio_format", "mp3"), + "quality": self.res_var.get() if media_type == "video" else self.audio_qual_var.get(), + "playlist_start": self.start_var.get().strip(), + "playlist_end": self.end_var.get().strip(), + "ignore_errors": self.chip_ignore.get(), + "embed_thumbnail": config.get("embed_thumbnail", True), + "embed_subtitles": config.get("embed_subtitles", False), + "subtitle_lang": config.get("subtitle_lang", "tr,en"), + "add_metadata": config.get("add_metadata", True), + "speed_limit": config.get("speed_limit", ""), + "concurrent_fragments": config.get("concurrent_fragments", 4) if self.chip_turbo.get() else 1 + } + + if self.on_download_requested: + self.on_download_requested(url, out_dir, options) diff --git a/ui/tabs/settings_tab.py b/ui/tabs/settings_tab.py new file mode 100644 index 0000000..9fdec47 --- /dev/null +++ b/ui/tabs/settings_tab.py @@ -0,0 +1,298 @@ +import tkinter as tk +from tkinter import ttk, filedialog, messagebox +import threading +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, ACCENT, ACCENT_LIGHT, TEXT, SUBTEXT, SUCCESS, WARNING, ERROR, + FONT_HERO, FONT_TITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD +) +from ui.components import Card, PillButton, PillChip, ModernEntry, SegmentedPill +from core.config import config +from core.dependencies import ( + get_ytdlp_status, get_ffmpeg_status, get_js_status, + install_ytdlp, install_ffmpeg, install_deno, + resolve_cookies_args, test_browser_cookies +) + +class SettingsTab(tk.Frame): + def __init__(self, parent, on_dependency_updated=None, **kwargs): + super().__init__(parent, bg=BG, **kwargs) + self.on_dependency_updated = on_dependency_updated + self._build_ui() + self.check_dependencies() + + def _build_ui(self): + # ── Başlık ─────────────────────────────────────────────────── + hdr = tk.Frame(self, bg=BG) + hdr.pack(fill="x", padx=32, pady=(28, 22)) + + tk.Label(hdr, text="Ayarlar", bg=BG, fg=TEXT, font=FONT_HERO).pack(anchor="w") + tk.Label(hdr, text="İndirme tercihlerini, bağlantı ve sistem araçlarını yönetin.", + bg=BG, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 0)) + + # ── 1. Sistem Araçları Kartı ───────────────────────────────── + c_deps = Card(self) + c_deps.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_deps, text="SİSTEM ARAÇLARI", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w", pady=(0, 12)) + + # yt-dlp + r_yt = tk.Frame(c_deps, bg=SURFACE) + r_yt.pack(fill="x", pady=6) + tk.Label(r_yt, text="yt-dlp Çekirdeği:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR, width=16, anchor="w").pack(side="left") + self.lbl_ytdlp_status = tk.Label(r_yt, text="Kontrol ediliyor...", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR) + self.lbl_ytdlp_status.pack(side="left") + + self.btn_install_ytdlp = PillButton(r_yt, text="Güncelle", command=self._start_install_ytdlp, small=True, style="secondary") + self.btn_install_ytdlp.pack(side="right") + + # FFmpeg + r_ff = tk.Frame(c_deps, bg=SURFACE) + r_ff.pack(fill="x", pady=6) + tk.Label(r_ff, text="FFmpeg Medya:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR, width=16, anchor="w").pack(side="left") + self.lbl_ffmpeg_status = tk.Label(r_ff, text="Kontrol ediliyor...", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR) + self.lbl_ffmpeg_status.pack(side="left") + + self.btn_install_ffmpeg = PillButton(r_ff, text="FFmpeg kur", command=self._start_install_ffmpeg, small=True, style="primary") + self.btn_install_ffmpeg.pack(side="right") + + # JavaScript EJS (Deno) + r_js = tk.Frame(c_deps, bg=SURFACE) + r_js.pack(fill="x", pady=6) + tk.Label(r_js, text="JS Motoru (EJS):", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR, width=16, anchor="w").pack(side="left") + self.lbl_js_status = tk.Label(r_js, text="Kontrol ediliyor...", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR) + self.lbl_js_status.pack(side="left") + + self.btn_install_js = PillButton(r_js, text="Deno kur", command=self._start_install_deno, small=True, style="secondary") + self.btn_install_js.pack(side="right") + + self.lbl_install_progress = tk.Label(c_deps, text="", bg=SURFACE, fg=ACCENT_LIGHT, font=FONT_SMALL) + self.lbl_install_progress.pack(fill="x", pady=(6, 0)) + + # ── 2. Çerez Kartı ────────────────────────────────────────── + c_ck = Card(self) + c_ck.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_ck, text="TARAYICI ÇEREZLERİ", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + tk.Label(c_ck, text="Yalnızca erişim gerektiren içeriklerde kullanın. Çerezler hesabınıza erişim sağlayabilir.", + bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 14)) + + ck_row = tk.Frame(c_ck, bg=SURFACE) + ck_row.pack(fill="x") + + self.ck_seg = SegmentedPill( + ck_row, + items=[ + ("none", "Kapalı"), + ("browser", "Tarayıcı"), + ("file", "cookies.txt") + ], + default_val=config.get("cookies_mode", "none"), + on_change=self._on_ck_mode_changed + ) + self.ck_seg.pack(side="left") + + # Tarayıcı alanı + self.browser_frame = tk.Frame(c_ck, bg=SURFACE) + + b_sel_row = tk.Frame(self.browser_frame, bg=SURFACE) + b_sel_row.pack(fill="x", pady=(12, 4)) + + tk.Label(b_sel_row, text="Tarayıcı:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.browser_var = tk.StringVar(value=config.get("cookies_browser", "brave")) + browsers = ["zen", "brave", "chrome", "edge", "firefox", "opera", "vivaldi", "chromium"] + self.browser_cb = ttk.Combobox( + b_sel_row, textvariable=self.browser_var, values=browsers, + state="readonly", width=12, font=FONT_REGULAR + ) + self.browser_cb.pack(side="left", padx=(8, 14)) + self.browser_cb.bind("<>", lambda e: config.set("cookies_browser", self.browser_var.get())) + + self.btn_test_cookies = PillButton(b_sel_row, text="Çerezleri test et", command=self._test_cookies_click, small=True, style="secondary") + self.btn_test_cookies.pack(side="left") + + self.lbl_cookie_test = tk.Label( + self.browser_frame, + text="Çoğu içerik için çerez gerekmez. Çerez dosyalarını kimseyle paylaşmayın.", + bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL, anchor="w", wraplength=540, justify="left" + ) + self.lbl_cookie_test.pack(fill="x", pady=(4, 0)) + + # Dosya alanı + self.file_frame = tk.Frame(c_ck, bg=SURFACE) + self.ck_file_var = tk.StringVar(value=config.get("cookies_path") or "Seçilmedi") + self.lbl_ck_file = tk.Label( + self.file_frame, textvariable=self.ck_file_var, bg=ENTRY_BG, fg=SUBTEXT, + font=FONT_REGULAR, anchor="w", padx=10, pady=6, highlightthickness=1, highlightbackground=BORDER + ) + self.lbl_ck_file.pack(side="left", fill="x", expand=True) + PillButton(self.file_frame, text="📂 Seç", command=self._choose_ck_file, small=True).pack(side="left", padx=(8, 0)) + PillButton(self.file_frame, text="✕", command=self._clear_ck_file, small=True, style="ghost").pack(side="left", padx=(4, 0)) + + # Başlangıçta görünürlük + current_mode = config.get("cookies_mode", "none") + if current_mode == "browser": + self.browser_frame.pack(fill="x") + elif current_mode == "file": + self.file_frame.pack(fill="x", pady=(12, 0)) + + # ── 3. Ağ ve Performans Kartı ──────────────────────────────── + c_net = Card(self) + c_net.pack(fill="x", padx=32, pady=(0, 24)) + + tk.Label(c_net, text="AĞ VE PERFORMANS", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w", pady=(0, 12)) + + nrow = tk.Frame(c_net, bg=SURFACE) + nrow.pack(fill="x") + + tk.Label(nrow, text="Eşzamanlı parça sayısı:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.frag_var = tk.StringVar(value=str(config.get("concurrent_fragments", 4))) + self.frag_cb = ttk.Combobox( + nrow, textvariable=self.frag_var, values=["1", "2", "4", "8", "16"], + state="readonly", width=5, font=FONT_REGULAR + ) + self.frag_cb.pack(side="left", padx=(6, 28)) + self.frag_cb.bind("<>", lambda e: config.set("concurrent_fragments", int(self.frag_var.get()))) + + tk.Label(nrow, text="Proxy:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.proxy_var = tk.StringVar(value=config.get("proxy", "")) + self.proxy_entry = ModernEntry(nrow, textvariable=self.proxy_var, placeholder="http://127.0.0.1:7890", width=22) + self.proxy_entry.pack(side="left", padx=(6, 10)) + PillButton(nrow, text="Kaydet", command=lambda: config.set("proxy", self.proxy_entry.get_clean_text()), small=True).pack(side="left") + + def _on_ck_mode_changed(self, mode): + config.set("cookies_mode", mode) + if mode == "browser": + self.file_frame.pack_forget() + self.browser_frame.pack(fill="x") + elif mode == "file": + self.browser_frame.pack_forget() + self.file_frame.pack(fill="x", pady=(12, 0)) + else: + self.browser_frame.pack_forget() + self.file_frame.pack_forget() + + def _test_cookies_click(self): + b = self.browser_var.get() + self.btn_test_cookies.config(state="disabled") + self.lbl_cookie_test.config(text=f"⏳ {b.capitalize()} çerezleri test ediliyor...", fg=ACCENT_LIGHT) + + def _worker(): + success, msg = test_browser_cookies(b) + def _apply(): + self.btn_test_cookies.config(state="normal") + self.lbl_cookie_test.config(text=msg, fg=(SUCCESS if success else WARNING)) + self.after(0, _apply) + + threading.Thread(target=_worker, daemon=True).start() + + def _choose_ck_file(self): + f = filedialog.askopenfilename( + title="cookies.txt Dosyası Seçin", + filetypes=[("Metin Dosyası", "*.txt"), ("Tüm Dosyalar", "*.*")] + ) + if f: + self.ck_file_var.set(f) + config.set("cookies_path", f) + + def _clear_ck_file(self): + self.ck_file_var.set("Seçilmedi") + config.set("cookies_path", "") + + def check_dependencies(self): + def _check(): + yt_ok, yt_ver, _ = get_ytdlp_status() + ff_ok, ff_ver, _ = get_ffmpeg_status() + js_ok, js_ver, _ = get_js_status() + + def _update(): + if yt_ok: + self.lbl_ytdlp_status.config(text=f"✅ Hazır ({yt_ver})", fg=SUCCESS) + else: + self.lbl_ytdlp_status.config(text="❌ Bulunamadı", fg=ERROR) + + if ff_ok: + self.lbl_ffmpeg_status.config(text=f"✅ Hazır ({ff_ver})", fg=SUCCESS) + self.btn_install_ffmpeg.config(text="✓ Kurulu", style="secondary") + else: + self.lbl_ffmpeg_status.config(text="⚠️ Bulunamadı (MP3 için gerekli)", fg=WARNING) + self.btn_install_ffmpeg.config(text="⚡ 1-Tıkla FFmpeg Kur", style="primary") + + if js_ok: + self.lbl_js_status.config(text=f"✅ {js_ver}", fg=SUCCESS) + self.btn_install_js.config(text="✓ Hazır", style="secondary") + else: + self.lbl_js_status.config(text="⚠️ Bulunamadı (YouTube EJS için)", fg=WARNING) + self.btn_install_js.config(text="⚡ Deno Kur", style="primary") + + self.after(0, _update) + + threading.Thread(target=_check, daemon=True).start() + + def _start_install_ytdlp(self): + self.btn_install_ytdlp.config(state="disabled") + self.lbl_install_progress.config(text="yt-dlp indiriliyor...", fg=ACCENT_LIGHT) + + def _prog(pct, dl, tot): + self.after(0, lambda: self.lbl_install_progress.config(text=f"yt-dlp indiriliyor: %{pct:.1f}")) + + def _worker(): + try: + install_ytdlp(progress_callback=_prog) + self.after(0, lambda: self.lbl_install_progress.config(text="✅ yt-dlp başarıyla güncellendi!", fg=SUCCESS)) + self.check_dependencies() + if self.on_dependency_updated: + self.on_dependency_updated() + except Exception as ex: + self.after(0, lambda: self.lbl_install_progress.config(text=f"❌ Hata: {ex}", fg=ERROR)) + finally: + self.after(0, lambda: self.btn_install_ytdlp.config(state="normal")) + + threading.Thread(target=_worker, daemon=True).start() + + def _start_install_ffmpeg(self): + self.btn_install_ffmpeg.config(state="disabled") + self.lbl_install_progress.config(text="FFmpeg indiriliyor ve ayıklanıyor...", fg=ACCENT_LIGHT) + + def _prog(pct, dl, tot): + self.after(0, lambda: self.lbl_install_progress.config(text=f"FFmpeg indiriliyor: %{pct:.1f}")) + + def _worker(): + try: + install_ffmpeg(progress_callback=_prog) + self.after(0, lambda: self.lbl_install_progress.config(text="✅ FFmpeg başarıyla kuruldu!", fg=SUCCESS)) + self.check_dependencies() + if self.on_dependency_updated: + self.on_dependency_updated() + except Exception as ex: + self.after(0, lambda: self.lbl_install_progress.config(text=f"❌ Kurulum Hatası: {ex}", fg=ERROR)) + finally: + self.after(0, lambda: self.btn_install_ffmpeg.config(state="normal")) + + threading.Thread(target=_worker, daemon=True).start() + + def _start_install_deno(self): + self.btn_install_js.config(state="disabled") + self.lbl_install_progress.config(text="Deno JavaScript motoru indiriliyor...", fg=ACCENT_LIGHT) + + def _prog(pct, dl, tot): + self.after(0, lambda: self.lbl_install_progress.config(text=f"Deno indiriliyor: %{pct:.1f}")) + + def _worker(): + try: + install_deno(progress_callback=_prog) + self.after(0, lambda: self.lbl_install_progress.config(text="✅ Deno motoru başarıyla kuruldu!", fg=SUCCESS)) + self.check_dependencies() + if self.on_dependency_updated: + self.on_dependency_updated() + except Exception as ex: + self.after(0, lambda: self.lbl_install_progress.config(text=f"❌ Deno Kurulum Hatası: {ex}", fg=ERROR)) + finally: + self.after(0, lambda: self.btn_install_js.config(state="normal")) + + threading.Thread(target=_worker, daemon=True).start() + + def get_cookies_args(self): + mode = self.ck_seg.get() + b = self.browser_var.get() + p = self.ck_file_var.get() + return resolve_cookies_args(mode, b, p) diff --git a/ui/tabs/single_tab.py b/ui/tabs/single_tab.py new file mode 100644 index 0000000..9fe831c --- /dev/null +++ b/ui/tabs/single_tab.py @@ -0,0 +1,291 @@ +import tkinter as tk +from tkinter import ttk, filedialog, messagebox +from ui.theme import ( + BG, SURFACE, SURFACE_LIGHT, ENTRY_BG, BORDER, ACCENT, ACCENT_LIGHT, TEXT, SUBTEXT, MUTED, + FONT_HERO, FONT_TITLE, FONT_SUBTITLE, FONT_REGULAR, FONT_BOLD, FONT_SMALL, FONT_SMALL_BOLD +) +from ui.components import Card, PillButton, PillChip, ModernEntry, SegmentedPill, VideoPreviewCard +from core.config import config +from core.metadata import fetch_video_metadata + +class SingleTab(tk.Frame): + def __init__(self, parent, on_download_requested=None, **kwargs): + super().__init__(parent, bg=BG, **kwargs) + self.on_download_requested = on_download_requested + self.current_metadata = None + self._metadata_url = "" + self._metadata_request_id = 0 + self._metadata_after_id = None + self._build_ui() + + def _build_ui(self): + # Scrollable alan + scroll_frame = tk.Frame(self, bg=BG) + scroll_frame.pack(fill="both", expand=True) + + # ── Başlık Alanı ───────────────────────────────────────────── + hdr = tk.Frame(scroll_frame, bg=BG) + hdr.pack(fill="x", padx=32, pady=(28, 22)) + + tk.Label(hdr, text="Medya indir", bg=BG, fg=TEXT, font=FONT_HERO).pack(anchor="w") + tk.Label(hdr, text="Bir bağlantı yapıştırın; video veya ses olarak kaydedin.", + bg=BG, fg=SUBTEXT, font=FONT_REGULAR).pack(anchor="w", pady=(6, 0)) + + # ── 1. URL Giriş Kartı ────────────────────────────────────── + c_url = Card(scroll_frame) + c_url.pack(fill="x", padx=32, pady=(0, 16)) + + tk.Label(c_url, text="MEDYA BAĞLANTISI", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + + row = tk.Frame(c_url, bg=SURFACE) + row.pack(fill="x", pady=(8, 0)) + + self.url_var = tk.StringVar() + self.url_entry = ModernEntry( + row, textvariable=self.url_var, + placeholder="https://youtube.com/watch?v=... veya desteklenen bir link", + on_change=self._on_url_typed + ) + self.url_entry.pack(side="left", fill="x", expand=True) + + PillButton(row, text="Yapıştır", command=self._paste_clipboard, small=True, style="secondary").pack(side="left", padx=(10, 0)) + PillButton(row, text="Temizle", command=self._clear_url, small=True, style="ghost").pack(side="left", padx=(6, 0)) + + # ── 2. Video Önizleme (Başlangıçta Gizli) ─────────────────── + self.preview_card = VideoPreviewCard(scroll_frame) + + # ── 3. Format ve Kalite ────────────────────────────────────── + c_fmt = Card(scroll_frame) + c_fmt.pack(fill="x", padx=32, pady=(0, 16)) + self.format_card = c_fmt + + tk.Label(c_fmt, text="FORMAT VE KALİTE", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + + fmt_controls = tk.Frame(c_fmt, bg=SURFACE) + fmt_controls.pack(fill="x", pady=(10, 0)) + + # Medya Tipi + self.media_seg = SegmentedPill( + fmt_controls, + items=[("video", "Video"), ("audio", "Ses")], + default_val="video", + on_change=self._on_media_type_changed + ) + self.media_seg.pack(side="left") + + # Video Seçenekleri + self.video_opts_frame = tk.Frame(fmt_controls, bg=SURFACE) + self.video_opts_frame.pack(side="left", padx=(20, 0)) + + tk.Label(self.video_opts_frame, text="Format:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.video_ext_var = tk.StringVar(value=config.get("video_format", "mp4")) + self.video_ext_cb = ttk.Combobox( + self.video_opts_frame, textvariable=self.video_ext_var, + values=["mp4", "mkv", "webm"], state="readonly", width=7, font=FONT_REGULAR + ) + self.video_ext_cb.pack(side="left", padx=(6, 16)) + self.video_ext_cb.bind( + "<>", + lambda e: config.set("video_format", self.video_ext_var.get()) + ) + + tk.Label(self.video_opts_frame, text="Çözünürlük:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.res_var = tk.StringVar(value=config.get("video_quality", "Best Quality (En İyi)")) + self.res_cb = ttk.Combobox( + self.video_opts_frame, textvariable=self.res_var, + values=["Best Quality (En İyi)", "4320p (8K)", "2160p (4K)", "1440p (2K)", "1080p (FHD)", "720p (HD)", "480p", "360p"], + state="readonly", width=20, font=FONT_REGULAR + ) + self.res_cb.pack(side="left", padx=(6, 0)) + self.res_cb.bind( + "<>", + lambda e: config.set("video_quality", self.res_var.get()) + ) + + # Ses Seçenekleri (Başlangıçta Gizli) + self.audio_opts_frame = tk.Frame(fmt_controls, bg=SURFACE) + tk.Label(self.audio_opts_frame, text="Format:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.audio_ext_var = tk.StringVar(value=config.get("audio_format", "mp3")) + self.audio_ext_cb = ttk.Combobox( + self.audio_opts_frame, textvariable=self.audio_ext_var, + values=["mp3", "m4a", "flac", "wav", "opus"], state="readonly", width=7, font=FONT_REGULAR + ) + self.audio_ext_cb.pack(side="left", padx=(6, 16)) + self.audio_ext_cb.bind( + "<>", + lambda e: config.set("audio_format", self.audio_ext_var.get()) + ) + + tk.Label(self.audio_opts_frame, text="Kalite:", bg=SURFACE, fg=SUBTEXT, font=FONT_REGULAR).pack(side="left") + self.audio_qual_var = tk.StringVar(value=config.get("audio_quality", "Best Quality (En İyi)")) + self.audio_qual_cb = ttk.Combobox( + self.audio_opts_frame, textvariable=self.audio_qual_var, + values=["Best Quality (En İyi)", "320 kbps", "256 kbps", "192 kbps", "128 kbps"], + state="readonly", width=20, font=FONT_REGULAR + ) + self.audio_qual_cb.pack(side="left", padx=(6, 0)) + self.audio_qual_cb.bind( + "<>", + lambda e: config.set("audio_quality", self.audio_qual_var.get()) + ) + + # Ayar Çipleri + chips_row = tk.Frame(c_fmt, bg=SURFACE) + chips_row.pack(fill="x", pady=(14, 2)) + + self.chip_sub = PillChip(chips_row, text="Altyazıyı ekle", initial_value=config.get("embed_subtitles", False)) + self.chip_sub.pack(side="left", padx=(0, 10)) + + self.chip_thumb = PillChip(chips_row, text="Kapak görseli", initial_value=config.get("embed_thumbnail", True)) + self.chip_thumb.pack(side="left", padx=(0, 10)) + + self.chip_turbo = PillChip(chips_row, text="Çok parçalı indirme", initial_value=(config.get("concurrent_fragments", 4) > 1)) + self.chip_turbo.pack(side="left") + + # ── 4. Kayıt Klasörü ──────────────────────────────────────── + c_dir = Card(scroll_frame) + c_dir.pack(fill="x", padx=32, pady=(0, 18)) + + tk.Label(c_dir, text="KAYIT KLASÖRÜ", bg=SURFACE, fg=SUBTEXT, font=FONT_SMALL_BOLD).pack(anchor="w") + drow = tk.Frame(c_dir, bg=SURFACE) + drow.pack(fill="x", pady=(8, 0)) + + self.dir_var = tk.StringVar(value=config.get("download_dir")) + ModernEntry(drow, textvariable=self.dir_var).pack(side="left", fill="x", expand=True) + PillButton(drow, text="Klasör seç", command=self._choose_dir, small=True).pack(side="left", padx=(10, 0)) + + # ── 5. İndirme Butonu ──────────────────────────────────────── + self.btn_download = PillButton( + scroll_frame, + text="İndirmeyi başlat", + command=self._on_start_click, + style="primary" + ) + self.btn_download.pack(fill="x", padx=32, pady=(0, 24), ipady=3) + + def _on_media_type_changed(self, media_type): + if media_type == "video": + self.audio_opts_frame.pack_forget() + self.video_opts_frame.pack(side="left", padx=(20, 0)) + self.btn_download.config(text="İndirmeyi başlat") + else: + self.video_opts_frame.pack_forget() + self.audio_opts_frame.pack(side="left", padx=(20, 0)) + self.btn_download.config(text="İndirmeyi başlat") + + def _paste_clipboard(self): + try: + clip = self.clipboard_get().strip() + if clip and clip.startswith("http"): + self.url_entry.set_text(clip) + except Exception: + pass + + def _on_url_typed(self, text): + if text == self._metadata_url: + return + + self._metadata_url = text + self._metadata_request_id += 1 + request_id = self._metadata_request_id + self.current_metadata = None + self.preview_card.pack_forget() + self.res_cb.config(values=[ + "Best Quality (En İyi)", "4320p (8K)", "2160p (4K)", + "1440p (2K)", "1080p (FHD)", "720p (HD)", "480p", "360p" + ]) + self.res_var.set("Best Quality (En İyi)") + self._set_download_button_ready() + + if self._metadata_after_id: + self.after_cancel(self._metadata_after_id) + self._metadata_after_id = None + + if ( + config.get("auto_fetch_metadata", True) + and len(text) > 15 + and (text.startswith("http://") or text.startswith("https://")) + ): + self._metadata_after_id = self.after( + 500, self._auto_fetch_metadata, text, request_id + ) + + def _auto_fetch_metadata(self, url, request_id): + self._metadata_after_id = None + self.btn_download.config(state="disabled", text="⏳ Video Bilgileri Alınıyor...") + fetch_video_metadata( + url, + callback=lambda metadata: self._on_metadata_loaded(metadata, request_id, url), + error_callback=lambda err: self._on_metadata_error(err, request_id, url) + ) + + def _on_metadata_loaded(self, metadata, request_id, url): + self.after(0, self._apply_metadata, metadata, request_id, url) + + def _apply_metadata(self, metadata, request_id, url): + if request_id != self._metadata_request_id or url != self.url_entry.get_clean_text(): + return + self.current_metadata = metadata + self.preview_card.update_metadata(metadata) + self.preview_card.pack(fill="x", padx=32, pady=(0, 16), before=self.format_card) + + if metadata.get("resolutions"): + self.res_cb.config(values=metadata["resolutions"]) + self.res_var.set(metadata["resolutions"][0]) + + self._set_download_button_ready() + + def _on_metadata_error(self, err, request_id, url): + self.after(0, self._restore_download_button, request_id, url) + + def _restore_download_button(self, request_id, url): + if request_id == self._metadata_request_id and url == self.url_entry.get_clean_text(): + self._set_download_button_ready() + + def _set_download_button_ready(self): + self.btn_download.config(state="normal", text="İndirmeyi başlat") + + def _clear_url(self): + self.url_entry.delete(0, "end") + self.url_entry._apply_placeholder() + self.preview_card.pack_forget() + self.current_metadata = None + self._metadata_url = "" + self._metadata_request_id += 1 + self._set_download_button_ready() + if self._metadata_after_id: + self.after_cancel(self._metadata_after_id) + self._metadata_after_id = None + + def _choose_dir(self): + d = filedialog.askdirectory(initialdir=self.dir_var.get() or config.get("download_dir")) + if d: + self.dir_var.set(d) + config.set("download_dir", d) + + def _on_start_click(self): + url = self.url_entry.get_clean_text() + if not url: + messagebox.showwarning("Uyarı", "Lütfen geçerli bir video veya ses URL'si girin.", parent=self) + return + + out_dir = self.dir_var.get().strip() or config.get("download_dir") + media_type = self.media_seg.get() + + options = { + "mode": "single", + "media_type": media_type, + "format": self.video_ext_var.get() if media_type == "video" else self.audio_ext_var.get(), + "quality": self.res_var.get() if media_type == "video" else self.audio_qual_var.get(), + "embed_subtitles": self.chip_sub.get(), + "embed_thumbnail": self.chip_thumb.get(), + "concurrent_fragments": config.get("concurrent_fragments", 4) if self.chip_turbo.get() else 1, + "add_metadata": config.get("add_metadata", True), + "subtitle_lang": config.get("subtitle_lang", "tr,en"), + "speed_limit": config.get("speed_limit", ""), + "ignore_errors": config.get("ignore_errors", True), + "title": self.current_metadata.get("title") if self.current_metadata else None + } + + if self.on_download_requested: + self.on_download_requested(url, out_dir, options) diff --git a/ui/theme.py b/ui/theme.py new file mode 100644 index 0000000..9b57bad --- /dev/null +++ b/ui/theme.py @@ -0,0 +1,159 @@ +import sys +from tkinter import ttk + +_PALETTES = { + "dark": { + "BG": "#11141C", + "SURFACE": "#191E29", + "SURFACE_LIGHT": "#242B39", + "SURFACE_HOVER": "#30394A", + "ENTRY_BG": "#141923", + "BORDER": "#2B3444", + "BORDER_FOCUS": "#9B8CFF", + "ACCENT": "#7967F2", + "ACCENT_LIGHT": "#B6A9FF", + "ACCENT_HOVER": "#6857D8", + "ACCENT_MUTED": "#302A4A", + "ACCENT_GRADIENT": "#9B8CFF", + "TEXT": "#F1F3F8", + "SUBTEXT": "#A1AABD", + "MUTED": "#727D90", + "SUCCESS": "#42C99A", + "SUCCESS_HOVER": "#2DAB7F", + "WARNING": "#F2B861", + "ERROR": "#F07883", + "DANGER_HOVER": "#D45C69", + "TAB_BG": "#151923", + "TAB_ACTIVE": "#302A4A", + "TAB_HOVER": "#222837", + }, + "light": { + "BG": "#F4F6FA", + "SURFACE": "#FFFFFF", + "SURFACE_LIGHT": "#F1F4F9", + "SURFACE_HOVER": "#E8EDF5", + "ENTRY_BG": "#F8FAFC", + "BORDER": "#E2E7EF", + "BORDER_FOCUS": "#7774E8", + "ACCENT": "#5B59D6", + "ACCENT_LIGHT": "#514FC7", + "ACCENT_HOVER": "#4846B8", + "ACCENT_MUTED": "#EFEEFF", + "ACCENT_GRADIENT": "#7774E8", + "TEXT": "#202938", + "SUBTEXT": "#667085", + "MUTED": "#98A2B3", + "SUCCESS": "#16835D", + "SUCCESS_HOVER": "#116B4B", + "WARNING": "#A96C12", + "ERROR": "#D04452", + "DANGER_HOVER": "#B83240", + "TAB_BG": "#FFFFFF", + "TAB_ACTIVE": "#EFEEFF", + "TAB_HOVER": "#F5F5FF", + }, +} + +_PALETTE_NAMES = tuple(_PALETTES["dark"]) +for _name, _value in _PALETTES["dark"].items(): + globals()[_name] = _value + +FONT_HERO = ("Segoe UI", 22, "bold") +FONT_TITLE = ("Segoe UI", 15, "bold") +FONT_SUBTITLE = ("Segoe UI", 12, "bold") +FONT_REGULAR = ("Segoe UI", 10) +FONT_BOLD = ("Segoe UI", 10, "bold") +FONT_SMALL = ("Segoe UI", 9) +FONT_SMALL_BOLD = ("Segoe UI", 9, "bold") +FONT_STAT = ("Segoe UI", 11, "bold") +FONT_MONO = ("Consolas", 9) + + +def apply_theme(root, mode="dark"): + """Apply a palette to custom Tk widgets and native ttk controls.""" + if mode not in _PALETTES: + mode = "dark" + palette = _PALETTES[mode] + globals().update(palette) + for module_name, module in tuple(sys.modules.items()): + if module_name == "ui" or module_name.startswith("ui."): + namespace = getattr(module, "__dict__", {}) + for name, value in palette.items(): + if name in namespace: + namespace[name] = value + root.configure(bg=palette["BG"]) + + style = ttk.Style(root) + style.theme_use("clam") + + style.configure("TFrame", background=BG) + style.configure("TLabel", background=BG, foreground=TEXT, font=FONT_REGULAR) + + style.configure( + "Custom.Horizontal.TProgressbar", + troughcolor=SURFACE_LIGHT, + background=ACCENT, + thickness=8, + borderwidth=0, + ) + style.configure( + "Vertical.TScrollbar", + background=SURFACE_LIGHT, + troughcolor=BG, + arrowcolor=SUBTEXT, + borderwidth=0, + relief="flat", + ) + style.map( + "Vertical.TScrollbar", + background=[("active", SURFACE_HOVER), ("pressed", ACCENT)], + ) + + style.configure( + "TCombobox", + fieldbackground=ENTRY_BG, + background=SURFACE_LIGHT, + foreground=TEXT, + bordercolor=BORDER, + lightcolor=BORDER, + darkcolor=BORDER, + arrowcolor=ACCENT, + padding=(9, 7), + relief="flat", + ) + style.map( + "TCombobox", + fieldbackground=[("readonly", ENTRY_BG), ("disabled", SURFACE_LIGHT)], + foreground=[("readonly", TEXT), ("disabled", MUTED)], + selectbackground=[("readonly", ENTRY_BG)], + selectforeground=[("readonly", TEXT)], + ) + root.option_add("*TCombobox*Listbox.background", SURFACE) + root.option_add("*TCombobox*Listbox.foreground", TEXT) + root.option_add("*TCombobox*Listbox.selectBackground", ACCENT_MUTED) + root.option_add("*TCombobox*Listbox.selectForeground", ACCENT_LIGHT) + root.option_add("*TCombobox*Listbox.font", FONT_REGULAR) + + style.configure( + "Treeview", + background=SURFACE, + foreground=TEXT, + fieldbackground=SURFACE, + bordercolor=BORDER, + borderwidth=0, + font=FONT_REGULAR, + rowheight=38, + ) + style.configure( + "Treeview.Heading", + background=SURFACE_LIGHT, + foreground=SUBTEXT, + borderwidth=0, + font=FONT_SMALL_BOLD, + padding=(10, 9), + ) + style.map( + "Treeview", + background=[("selected", ACCENT_MUTED)], + foreground=[("selected", ACCENT_LIGHT)], + ) diff --git a/ytdlp_gui.pyw b/ytdlp_gui.pyw new file mode 100644 index 0000000..783f5ef --- /dev/null +++ b/ytdlp_gui.pyw @@ -0,0 +1,33 @@ +""" +LDownloader - Video & Ses İndirici (GUI) +Giriş noktası / Windows .pyw Başlatıcısı +""" +import os +import sys + +# PyInstaller paketli ortamında veya kaynak koddan çalışırken kök dizini ekle +root_dir = os.path.dirname(os.path.abspath(__file__)) +if root_dir not in sys.path: + sys.path.insert(0, root_dir) + +if __name__ == "__main__": + try: + from ui.app import main + main() + except Exception as ex: + import traceback + try: + exe_dir = os.path.dirname(sys.executable) + with open(os.path.join(exe_dir, "crash.log"), "w", encoding="utf-8") as f: + traceback.print_exc(file=f) + except Exception: + pass + import tkinter as tk + from tkinter import messagebox + root = tk.Tk() + root.withdraw() + messagebox.showerror( + "LDownloader Başlatma Hatası", + f"Uygulama başlatılırken bir hata oluştu:\n\n{ex}\n\nDetaylar: crash.log" + ) + sys.exit(1) diff --git a/ytdlp_indirici.spec b/ytdlp_indirici.spec new file mode 100644 index 0000000..5454e27 --- /dev/null +++ b/ytdlp_indirici.spec @@ -0,0 +1,71 @@ +# -*- mode: python ; coding: utf-8 -*- + +a = Analysis( + ['ytdlp_gui.pyw'], + pathex=['.'], + binaries=[], + datas=[ + ('logo.png', '.'), + ('logo.ico', '.') + ], + hiddenimports=[ + 'yt_dlp', + 'yt_dlp_ejs', + 'yt_dlp.default_addons', + 'mutagen', + 'pycryptodomex', + 'websockets', + 'brotli', + 'PIL', + 'PIL.Image', + 'PIL.ImageTk', + 'requests', + 'urllib3', + 'core', + 'core.config', + 'core.dependencies', + 'core.diagnostics', + 'core.downloader', + 'core.history', + 'core.metadata', + 'ui', + 'ui.theme', + 'ui.components', + 'ui.app', + 'ui.tabs', + 'ui.tabs.single_tab', + 'ui.tabs.playlist_tab', + 'ui.tabs.batch_tab', + 'ui.tabs.history_tab', + 'ui.tabs.settings_tab' + ], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name='LDownloader', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + upx_exclude=[], + runtime_tmpdir=None, + console=False, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, + icon=['logo.ico'], +)