perf & hardening: system architecture, anti-freeze and fault-tolerance audit (v3.4.0)

This commit is contained in:
LilDosto 2026-10-29 02:58:19 +03:00
parent 658cc01640
commit 947feaa037
8 changed files with 153 additions and 82 deletions

View file

@ -1,4 +1,4 @@
# LDownloader v3.3.0 🎬🎵
# LDownloader v3.4.0 🎬🎵
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![GitHub Release](https://img.shields.io/github/v/release/LilDosto/LDownloader)](https://github.com/LilDosto/LDownloader/releases)
@ -114,7 +114,7 @@ LDownloader'ı iki farklı şekilde kullanabilirsiniz:
Uygulamayı ve kurulum sihirbazını yerel olarak derlemek için:
* `build_exe.bat` dosyasına çift tıklayın veya çalıştırın:
* Derleme sonucunda `dist/` klasöründe hem taşınabilir `LDownloader.exe` hem de `LDownloader-v3.3.0-Setup.exe` üretilecektir.
* Derleme sonucunda `dist/` klasöründe hem taşınabilir `LDownloader.exe` hem de `LDownloader-v3.4.0-Setup.exe` üretilecektir.
---

View file

@ -105,72 +105,81 @@ class DownloadEngine:
env=env
)
for line in iter(self._proc.stdout.readline, ''):
line = line.rstrip()
if not line:
continue
if self._proc and self._proc.stdout:
for line in iter(self._proc.stdout.readline, ''):
line = line.rstrip()
if not line:
continue
if line.startswith(self._FINAL_PATH_PREFIX):
final_p = line[len(self._FINAL_PATH_PREFIX):].strip().strip('"')
if final_p and final_p != "NA":
last_destination = final_p
self._current_file = final_p
continue
if line.startswith(self._FINAL_PATH_PREFIX):
final_p = line[len(self._FINAL_PATH_PREFIX):].strip().strip('"')
if final_p and final_p != "NA":
last_destination = final_p
self._current_file = final_p
continue
# 1. Dosya yolu yakalama
m_dest = self._DEST_RE.search(line) or self._ALREADY_RE.search(line)
if m_dest:
dest = m_dest.group("path").strip().strip('"')
if not dest.endswith((".part", ".ytdl", ".vtt", ".srt", ".ass", ".lrc")):
last_destination = dest
self._current_file = dest
# 1. Dosya yolu yakalama
m_dest = self._DEST_RE.search(line) or self._ALREADY_RE.search(line)
if m_dest:
dest = m_dest.group("path").strip().strip('"')
if not dest.endswith((".part", ".ytdl", ".vtt", ".srt", ".ass", ".lrc")):
last_destination = dest
self._current_file = dest
# Durum / Aşama güncellemesi
if line.startswith("[ExtractAudio]"):
if cb.get("on_status"):
cb["on_status"]("Ses dönüştürülüyor...")
elif line.startswith("[Merger]"):
if cb.get("on_status"):
cb["on_status"]("Formatlar birleştiriliyor...")
elif line.startswith(("[EmbedThumbnail]", "[ThumbnailsConvertor]")):
if cb.get("on_status"):
cb["on_status"]("Kapak resmi ekleniyor...")
elif line.startswith("[Metadata]"):
if cb.get("on_status"):
cb["on_status"]("Üstveri ekleniyor...")
elif line.startswith("[SponsorBlock]"):
if cb.get("on_status"):
cb["on_status"]("Sponsorlu bölümler kesiliyor...")
elif line.startswith("[download] Destination:"):
if cb.get("on_status"):
cb["on_status"]("İndiriliyor...")
# Durum / Aşama güncellemesi
if line.startswith("[ExtractAudio]"):
if cb.get("on_status"):
cb["on_status"]("Ses dönüştürülüyor...")
elif line.startswith("[Merger]"):
if cb.get("on_status"):
cb["on_status"]("Formatlar birleştiriliyor...")
elif line.startswith(("[EmbedThumbnail]", "[ThumbnailsConvertor]")):
if cb.get("on_status"):
cb["on_status"]("Kapak resmi ekleniyor...")
elif line.startswith("[Metadata]"):
if cb.get("on_status"):
cb["on_status"]("Üstveri ekleniyor...")
elif line.startswith("[SponsorBlock]"):
if cb.get("on_status"):
cb["on_status"]("Sponsorlu bölümler kesiliyor...")
elif line.startswith("[download] Destination:"):
if cb.get("on_status"):
cb["on_status"]("İndiriliyor...")
# 2. İlerleme ayrıştırma
parsed = self._parse_progress(line, cb.get("on_progress"))
# 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")
# 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"
# 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"
is_progress_line = line.startswith("[PROGRESS]") or (parsed and bool(self._DL_RE.search(line)))
if cb.get("on_log") and not is_progress_line:
cb["on_log"](line, tag)
is_progress_line = line.startswith("[PROGRESS]") or (parsed and bool(self._DL_RE.search(line)))
if cb.get("on_log") and not is_progress_line:
cb["on_log"](line, tag)
self._proc.wait()
rc = self._proc.returncode
if self._proc:
self._proc.wait()
rc = self._proc.returncode
except FileNotFoundError as fnf:
error_message = (
"yt-dlp veya FFmpeg sistemde bulunamadı. "
"Lütfen Ayarlar sekmesine giderek '⚡ Kur' butonu ile bileşenleri kurun."
)
if cb.get("on_log"):
cb["on_log"](f"❌ {error_message}", "error")
except Exception as ex:
error_message = str(ex)
if cb.get("on_log"):
@ -179,11 +188,17 @@ class DownloadEngine:
finally:
with self._lock:
self._running = False
cancelled = self._cancelled
if self._proc and self._proc.stdout:
try:
self._proc.stdout.close()
except Exception:
pass
self._proc = None
success = (rc == 0 and not self._cancelled)
success = (rc == 0 and not cancelled)
if cb.get("on_complete"):
cb["on_complete"](success, last_destination or self._current_file, error_message, self._cancelled)
cb["on_complete"](success, last_destination or self._current_file, error_message, cancelled)
def _parse_progress(self, line, on_progress):
if not on_progress:
@ -346,6 +361,8 @@ def build_command(url, output_dir, options):
if clip_section:
cmd += ["--download-sections", clip_section]
safe_output_dir = os.path.abspath(output_dir or os.getcwd())
# Playlist aralığı
if options.get("mode") == "playlist":
playlist_range = playlist_items_range(
@ -355,10 +372,10 @@ def build_command(url, output_dir, options):
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")]
cmd += ["-o", os.path.join(safe_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")]
cmd += ["-o", os.path.join(safe_output_dir, "%(title)s.%(ext)s")]
# Kararlı ilerleme şablonu ve nihai dosya yolu çıktısı
# NOT: yt-dlp'de --print bayrağı varsayılan olarak --quiet ve --no-progress modunu tetikler.

View file

@ -48,7 +48,18 @@ class HistoryManager:
size_str = "—"
if file_path and os.path.exists(file_path):
try:
bytes_size = os.path.getsize(file_path)
if os.path.isdir(file_path):
bytes_size = 0
for root, _, files in os.walk(file_path):
for f in files:
fp = os.path.join(root, f)
try:
bytes_size += os.path.getsize(fp)
except OSError:
pass
else:
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:

View file

@ -8,6 +8,7 @@ from core.dependencies import find_executable
_METADATA_CACHE = {}
_CACHE_LOCK = threading.Lock()
_MAX_CACHE_SIZE = 64
_IN_FLIGHT = {}
def format_duration(seconds):
"""Saniyeyi ss:dd veya saat:ss:dd formatına dönüştürür."""
@ -69,8 +70,13 @@ def fetch_thumbnail_image(url, size=(160, 90)):
def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None, callback=None, error_callback=None):
"""Videonun temel bilgilerini arka planda çeker (önbellek destekli)."""
"""Videonun temel bilgilerini arka planda çeker (önbellek ve istek tekilleştirme destekli)."""
clean_url = (url or "").strip()
if not clean_url:
if error_callback:
error_callback("Geçersiz URL")
return
with _CACHE_LOCK:
if clean_url in _METADATA_CACHE:
cached = _METADATA_CACHE[clean_url]
@ -79,6 +85,12 @@ def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None,
threading.Thread(target=lambda: callback(cached), daemon=True).start()
return
if clean_url in _IN_FLIGHT:
_IN_FLIGHT[clean_url].append((callback, error_callback))
return
_IN_FLIGHT[clean_url] = [(callback, error_callback)]
def _worker():
try:
import yt_dlp
@ -149,12 +161,24 @@ def fetch_video_metadata(url: str, cookies_args: list = None, proxy: str = None,
# En eski kaydı temizle
_METADATA_CACHE.pop(next(iter(_METADATA_CACHE)))
_METADATA_CACHE[clean_url] = metadata
listeners = _IN_FLIGHT.pop(clean_url, [])
if callback:
callback(metadata)
for cb, _ in listeners:
if cb:
try:
cb(metadata)
except Exception:
pass
except Exception as ex:
if error_callback:
error_callback(str(ex))
err_msg = str(ex)
with _CACHE_LOCK:
listeners = _IN_FLIGHT.pop(clean_url, [])
for _, err_cb in listeners:
if err_cb:
try:
err_cb(err_msg)
except Exception:
pass
threading.Thread(target=_worker, daemon=True).start()

View file

@ -1,6 +1,6 @@
; Inno Setup Kurulum Senaryosu - LDownloader
#define MyAppName "LDownloader"
#define MyAppVersion "3.3.0"
#define MyAppVersion "3.4.0"
#define MyAppPublisher "LilDosto"
#define MyAppURL "https://github.com/LilDosto/LDownloader"
#define MyAppExeName "LDownloader.exe"

View file

@ -27,7 +27,7 @@ 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 v3.3.0")
self.title("LDownloader v3.4.0")
self.geometry("980x660")
self.minsize(880, 580)
self.configure(bg=BG)
@ -110,7 +110,7 @@ class LDownloaderApp(tk.Tk):
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 v3.3.0", font=FONT_TITLE, bg=TAB_BG, fg=TEXT).pack(side="left")
tk.Label(brand_frame, text="LDownloader v3.4.0", font=FONT_TITLE, bg=TAB_BG, fg=TEXT).pack(side="left")
# Orta: Sekmeler
self.nav_buttons = {}
@ -606,23 +606,31 @@ class LDownloaderApp(tk.Tk):
threading.Thread(target=_batch_worker, daemon=True).start()
def _safe_after(self, fn):
"""Pencere kapatıldıysa TclError oluşmasını engeller."""
try:
if self.winfo_exists():
self.after(0, fn)
except Exception:
pass
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))
self._safe_after(lambda: self.drawer.update_stats(pct, speed, total, eta))
def _on_log(line, tag):
self.after(0, lambda: self.drawer.log_line(line, tag))
self._safe_after(lambda: self.drawer.log_line(line, tag))
def _on_status(msg):
self.after(0, lambda: self.drawer.set_phase(msg))
self._safe_after(lambda: self.drawer.set_phase(msg))
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))
self._safe_after(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)
self._safe_after(self.tabs["history"].refresh)
callbacks = {
"on_progress": _on_progress,
@ -634,13 +642,13 @@ class LDownloaderApp(tk.Tk):
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))
self._safe_after(lambda: self.drawer.update_stats(pct, speed, total, eta))
def _on_log(line, tag):
self.after(0, lambda: self.drawer.log_line(line, tag))
self._safe_after(lambda: self.drawer.log_line(line, tag))
def _on_status(msg):
self.after(0, lambda: self.drawer.set_phase(msg))
self._safe_after(lambda: self.drawer.set_phase(msg))
def _on_complete(success, output_path, err, cancelled):
if done_callback:

View file

@ -752,6 +752,13 @@ class ContextualDownloadDrawer(tk.Frame):
def update_stats(self, pct, speed, total, eta):
# 0% ve 100% gibi kritik sınırları hemen göster
if pct <= 0 or pct >= 100:
if self._stats_after_id:
try:
self.after_cancel(self._stats_after_id)
except Exception:
pass
self._stats_after_id = None
self._pending_stats = None
self._apply_stats(pct, speed, total, eta)
return

View file

@ -78,10 +78,14 @@ def apply_windows_titlebar(root, is_dark=True):
root.update_idletasks()
hwnd = ctypes.windll.user32.GetParent(root.winfo_id())
value = ctypes.c_int(1 if is_dark else 0)
# DWMWA_USE_IMMERSIVE_DARK_MODE = 20 (Windows 11 & Win10 20H1+)
ctypes.windll.dwmapi.DwmSetWindowAttribute(
# DWMWA_USE_IMMERSIVE_DARK_MODE = 20 (Windows 11 & Win10 20H1+), 19 (Win10 1809-1909)
hr = ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, 20, ctypes.byref(value), ctypes.sizeof(value)
)
if hr != 0:
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, 19, ctypes.byref(value), ctypes.sizeof(value)
)
except Exception:
pass