-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
751 lines (641 loc) · 28.4 KB
/
Copy pathmain.py
File metadata and controls
751 lines (641 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
"""
YT Grabber - a simple Windows GUI front-end for yt-dlp.
Downloads YouTube videos/playlists as MP3 (audio) or MP4 (video),
using the bundled yt-dlp.exe as the actual download engine (unmodified,
official binary) with bundled ffmpeg for remuxing/extraction and a
bundled Deno runtime available on PATH for yt-dlp's JS interpreter needs.
This script is packaged into a standalone .exe with PyInstaller. At
runtime it looks for yt-dlp.exe / ffmpeg.exe / ffprobe.exe / deno.exe
next to the running executable (same folder), so the whole folder is
portable - copy it to any Windows PC and run YTGrabber.exe, no install
required.
"""
import os
import re
import sys
import json
import queue
import random
import shutil
import subprocess
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
APP_TITLE = "YTWin"
THREADS = 10 # parallel connections for max download speed
def app_dir():
"""Directory containing the running exe (or this script during dev)."""
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
def tool_path(name):
if getattr(sys, "frozen", False):
return os.path.join(app_dir(), "engine", name)
return os.path.join(app_dir(), name)
def ensure_desktop_shortcut():
"""Create a Desktop shortcut to this exe on first run, if one doesn't exist."""
if not getattr(sys, "frozen", False):
return
try:
desktop = os.path.join(os.path.expanduser("~"), "Desktop")
shortcut_path = os.path.join(desktop, f"{APP_TITLE}.lnk")
if os.path.exists(shortcut_path):
return
exe_path = sys.executable
ps_script = (
f'$s = (New-Object -COM WScript.Shell).CreateShortcut("{shortcut_path}"); '
f'$s.TargetPath = "{exe_path}"; '
f'$s.WorkingDirectory = "{os.path.dirname(exe_path)}"; '
f'$s.IconLocation = "{exe_path}"; '
f'$s.Save()'
)
subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps_script],
capture_output=True, timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
)
except Exception:
pass
def default_download_dir():
home = os.path.join(os.path.expanduser("~"), "Downloads", "YT Grabber")
os.makedirs(home, exist_ok=True)
return home
PROGRESS_RE = re.compile(
r"\[download\]\s+(?P<percent>[\d.]+)%\s+of\s+~?\s*(?P<size>\S+)"
r"(?:\s+at\s+(?P<speed>\S+))?"
r"(?:\s+ETA\s+(?P<eta>\S+))?"
)
# aria2c's own progress line, e.g:
# [#0e827e 12MiB/257MiB(4%) CN:10 DL:360KiB ETA:11m43s]
ARIA2_RE = re.compile(
r"\[#\S+\s+(?P<done>\S+)/(?P<total>\S+)\((?P<percent>\d+)%\)"
r"\s+CN:(?P<cn>\d+)\s+DL:(?P<speed>\S+)(?:\s+ETA:(?P<eta>\S+))?\]"
)
DEST_RE = re.compile(r"\[download\] Destination:\s*(.+)")
ALREADY_RE = re.compile(r"\[download\]\s+(.+)\s+has already been downloaded")
PLAYLIST_ITEM_RE = re.compile(r"\[download\] Downloading item (\d+) of (\d+)")
FINISHED_RE = re.compile(r"\[download\]\s+100%")
MERGE_RE = re.compile(r"\[Merger\]|\[ExtractAudio\]|\[ffmpeg\]")
ERROR_RE = re.compile(r"^ERROR:")
_SPEED_RE = re.compile(r"([\d.]+)\s*([KMG]i?B)/s", re.IGNORECASE)
_SPEED_UNITS = {"B": 1, "KB": 1000, "MB": 1000**2, "GB": 1000**3,
"KIB": 1024, "MIB": 1024**2, "GIB": 1024**3}
def _parse_speed_to_bytes(speed_str):
"""Parse a speed string like '8.6MiB/s' or '360KiB/s' into bytes/sec."""
if not speed_str:
return 0.0
m = _SPEED_RE.search(speed_str)
if not m:
return 0.0
value, unit = m.groups()
mult = _SPEED_UNITS.get(unit.upper(), 1)
try:
return float(value) * mult
except ValueError:
return 0.0
def _format_bytes_per_sec(total_bytes):
if total_bytes >= 1024**2:
return f"{total_bytes / 1024**2:.2f} MiB/s"
if total_bytes >= 1024:
return f"{total_bytes / 1024:.1f} KiB/s"
return f"{total_bytes:.0f} B/s"
RESOLUTIONS = ["Best available", "2160p (4K)", "1440p (2K)", "1080p", "720p", "480p", "360p"]
AUDIO_QUALITIES = ["Best (highest)", "High (~192kbps)", "Medium (~128kbps)", "Low (~64kbps)"]
_AUDIO_QUALITY_MAP = {
"Best (highest)": "0",
"High (~192kbps)": "5",
"Medium (~128kbps)": "7",
"Low (~64kbps)": "9",
}
def _video_format_selector(resolution):
if resolution == "Best available" or not resolution:
return "bestvideo*+bestaudio/best"
height = re.match(r"(\d+)p", resolution)
h = height.group(1)
return f"bestvideo*[height<={h}]+bestaudio/best/best[height<={h}]"
def _build_single_video_cmd(video_url, out_tmpl, mode, resolution, audio_quality,
cookies_file=None, cookies_browser=None):
yt_dlp = tool_path("yt-dlp.exe")
ffmpeg_dir = os.path.dirname(tool_path("ffmpeg.exe"))
aria2c = tool_path("aria2c.exe")
cmd = [
yt_dlp,
"--newline",
"--no-mtime",
"--ignore-errors",
"--ffmpeg-location", ffmpeg_dir,
"-o", out_tmpl,
# Real multi-connection parallel downloading for max speed.
"--external-downloader", aria2c,
"--external-downloader-args",
f"aria2c:-x {THREADS} -s {THREADS} -j {THREADS} -k 1M",
# Fragmented/live formats also download with multiple threads.
"--concurrent-fragments", str(THREADS),
# Small pause between metadata/API requests - reduces the chance
# of tripping YouTube's anti-bot rate limiting.
"--sleep-requests", "1",
]
if cookies_file:
cmd += ["--cookies", cookies_file]
elif cookies_browser:
cmd += ["--cookies-from-browser", cookies_browser]
if mode == "mp3":
quality = _AUDIO_QUALITY_MAP.get(audio_quality, "0")
cmd += [
"-f", "bestaudio/best",
"--extract-audio",
"--audio-format", "mp3",
"--audio-quality", quality,
]
else:
cmd += [
"-f", _video_format_selector(resolution),
"--merge-output-format", "mp4",
"--remux-video", "mp4",
]
cmd.append(video_url)
return cmd
class MultiDownloadManager:
"""Fetches all videos for a URL (a single video, or every item in a
playlist) and downloads up to `concurrency` of them at the same time,
each with its own 10-connection aria2c download."""
def __init__(self, url, mode, out_dir, on_event, resolution="Best available",
audio_quality="Best (highest)", concurrency=2, cookies_file=None):
self.url = url
self.mode = mode
self.out_dir = out_dir
self.on_event = on_event # callback(dict) -- called from worker threads
self.resolution = resolution
self.audio_quality = audio_quality
self.concurrency = concurrency
self.cookies_file = cookies_file
self.cancel_event = threading.Event()
self.active_procs = []
self.lock = threading.Lock()
def run(self):
yt_dlp = tool_path("yt-dlp.exe")
self.on_event({"type": "status", "message": "Reading video/playlist info..."})
info_cmd = [yt_dlp, "--flat-playlist", "-J"]
if self.cookies_file:
info_cmd += ["--cookies", self.cookies_file]
info_cmd.append(self.url)
try:
result = subprocess.run(
info_cmd,
capture_output=True, text=True, timeout=90,
creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
)
data = json.loads(result.stdout)
except Exception as e:
self.on_event({"type": "fatal", "message": f"Could not read that URL: {e}"})
return
entries = data.get("entries")
playlist_title = None
videos = []
if entries:
playlist_title = data.get("title")
for i, e in enumerate(entries):
if not e:
continue
videos.append({
"index": i + 1,
"id": e.get("id"),
"title": e.get("title") or e.get("id") or f"item {i + 1}",
})
else:
videos.append({"index": 1, "id": data.get("id"), "title": data.get("title") or self.url})
if not videos:
self.on_event({"type": "fatal", "message": "No downloadable videos found at that URL."})
return
self.on_event({"type": "queue_ready", "videos": videos, "playlist_title": playlist_title})
work_q = queue.Queue()
for v in videos:
work_q.put(v)
n_workers = max(1, min(self.concurrency, len(videos)))
threads = []
for i in range(n_workers):
# Stagger worker start slightly so we don't fire a burst of
# simultaneous requests at YouTube, which can trigger its
# anti-bot rate limiting (HTTP 429 / "confirm you're not a bot").
if i > 0 and not self.cancel_event.wait(1.5):
pass
t = threading.Thread(target=self._worker, args=(work_q, playlist_title), daemon=True)
t.start()
threads.append(t)
for t in threads:
t.join()
if self.cancel_event.is_set():
self.on_event({"type": "all_cancelled"})
else:
self.on_event({"type": "all_done"})
def _worker(self, work_q, playlist_title):
first = True
while not self.cancel_event.is_set():
try:
video = work_q.get_nowait()
except queue.Empty:
return
if not first:
# Keep spacing out requests for the whole run, not just at
# the start, so a long playlist doesn't keep re-creating
# request bursts that look like bot activity to YouTube.
if self.cancel_event.wait(random.uniform(1.0, 3.0)):
return
first = False
self._download_one(video, playlist_title)
def _download_one(self, video, playlist_title):
idx = video["index"]
vid = video["id"]
title = video["title"]
if self.cancel_event.is_set() or not vid:
return
video_url = f"https://www.youtube.com/watch?v={vid}"
prefix = f"{idx:02d} - " if playlist_title else ""
out_tmpl = os.path.join(self.out_dir, prefix + "%(title)s.%(ext)s")
# If the user didn't supply a cookies file, automatically try their
# browser's own YouTube login on retries - no user action needed.
# This is what fixes "Sign in to confirm you're not a bot" errors.
if self.cookies_file:
cookie_plan = [(self.cookies_file, None)] * 3
else:
cookie_plan = [(None, None), (None, "edge"), (None, "chrome")]
max_attempts = len(cookie_plan)
last_error = ""
for attempt in range(1, max_attempts + 1):
if self.cancel_event.is_set():
return
cookies_file, cookies_browser = cookie_plan[attempt - 1]
if attempt > 1:
self.on_event({
"type": "row_status", "idx": idx, "title": title,
"status": f"Retrying ({attempt}/{max_attempts})...",
})
# Back off in case it's YouTube rate-limiting us.
if self.cancel_event.wait(5 * attempt):
return
code, last_error = self._run_one_attempt(idx, title, video_url, out_tmpl, cookies_file, cookies_browser)
if self.cancel_event.is_set():
self.on_event({"type": "row_status", "idx": idx, "status": "Cancelled", "title": title})
return
if code == 0:
self.on_event({"type": "row_done", "idx": idx, "title": title})
return
self.on_event({
"type": "row_status", "idx": idx, "title": title,
"status": "Error", "detail": last_error,
})
def _run_one_attempt(self, idx, title, video_url, out_tmpl, cookies_file, cookies_browser):
cmd = _build_single_video_cmd(video_url, out_tmpl, self.mode, self.resolution,
self.audio_quality, cookies_file, cookies_browser)
env = os.environ.copy()
tools_dir = os.path.dirname(tool_path("deno.exe"))
env["PATH"] = tools_dir + os.pathsep + env.get("PATH", "")
self.on_event({"type": "row_status", "idx": idx, "status": "Starting...", "title": title})
try:
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
env=env, cwd=self.out_dir,
creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
)
except FileNotFoundError:
self.on_event({"type": "fatal", "message": "yt-dlp.exe not found next to the app."})
return 1, "yt-dlp.exe not found next to the app."
with self.lock:
self.active_procs.append(proc)
if self.cancel_event.is_set():
try:
proc.terminate()
except Exception:
pass
last_error_line = ""
for line in proc.stdout:
line = line.rstrip("\n")
if line:
err = self._parse_line(idx, title, line)
if err:
last_error_line = err
if self.cancel_event.is_set():
try:
proc.terminate()
except Exception:
pass
code = proc.wait()
with self.lock:
if proc in self.active_procs:
self.active_procs.remove(proc)
return code, last_error_line
def _parse_line(self, idx, title, line):
"""Returns the error text if this line was an ERROR line, else None."""
m = DEST_RE.search(line)
if m:
self.on_event({"type": "row_status", "idx": idx, "status": "Downloading", "title": title})
return None
m = ALREADY_RE.search(line)
if m:
self.on_event({"type": "row_progress", "idx": idx, "percent": 100.0, "speed": "", "eta": ""})
return None
m = PROGRESS_RE.search(line)
if m:
self.on_event({
"type": "row_progress", "idx": idx,
"percent": float(m.group("percent")),
"speed": m.group("speed") or "",
"eta": m.group("eta") or "",
})
return None
m = ARIA2_RE.search(line)
if m:
self.on_event({
"type": "row_progress", "idx": idx,
"percent": float(m.group("percent")),
"speed": (m.group("speed") + "/s") if m.group("speed") else "",
"eta": m.group("eta") or "",
})
return None
if MERGE_RE.search(line):
self.on_event({"type": "row_status", "idx": idx, "status": "Converting...", "title": title})
return None
if ERROR_RE.match(line):
return line
return None
def cancel(self):
self.cancel_event.set()
with self.lock:
for p in self.active_procs:
try:
p.terminate()
except Exception:
pass
class UpdateChecker(threading.Thread):
"""Runs `yt-dlp.exe --update-to nightly` once at startup, in the background."""
def __init__(self, status_cb):
super().__init__(daemon=True)
self.status_cb = status_cb
def run(self):
yt_dlp = tool_path("yt-dlp.exe")
if not os.path.exists(yt_dlp):
return
try:
self.status_cb("Checking for yt-dlp updates...")
result = subprocess.run(
[yt_dlp, "--update-to", "nightly"],
capture_output=True, text=True, timeout=60,
creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
)
out = (result.stdout or "") + (result.stderr or "")
if "Updated yt-dlp" in out:
self.status_cb("yt-dlp updated to the latest nightly build.")
elif "up to date" in out.lower() or "Latest version" in out:
self.status_cb("yt-dlp is up to date.")
else:
self.status_cb("Ready.")
except Exception:
self.status_cb("Ready.")
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title(APP_TITLE)
self.geometry("780x600")
self.resizable(True, True)
self.minsize(720, 520)
try:
icon_path = tool_path("ytwin_icon.ico")
if os.path.exists(icon_path):
self.iconbitmap(icon_path)
except Exception:
pass
self.mode_var = tk.StringVar(value="mp3")
self.resolution_var = tk.StringVar(value=RESOLUTIONS[0])
self.audio_quality_var = tk.StringVar(value=AUDIO_QUALITIES[0])
self.concurrency_var = tk.StringVar(value="2")
self.cookies_var = tk.StringVar(value="")
self.out_dir_var = tk.StringVar(value=default_download_dir())
self.status_var = tk.StringVar(value="Ready.")
self.playlist_var = tk.StringVar(value="")
self.credit_var = tk.StringVar(value="Developed by Engr. Maw. Khandaker Marsus")
self.job = None
self.total_videos = 0
self.completed_videos = 0
self.row_errors = {}
self.row_speeds = {}
self.total_speed_var = tk.StringVar(value="")
self.event_q = queue.Queue()
self._build_ui()
self.after(100, self._poll_queue)
UpdateChecker(self._thread_safe_status).start()
threading.Thread(target=ensure_desktop_shortcut, daemon=True).start()
# ---------------------------------------------------------- UI setup
def _build_ui(self):
pad = {"padx": 12, "pady": 6}
frm_url = ttk.LabelFrame(self, text="Video or Playlist URL")
frm_url.pack(fill="x", **pad)
self.url_entry = ttk.Entry(frm_url, font=("Segoe UI", 10))
self.url_entry.pack(fill="x", padx=8, pady=8)
frm_opts = ttk.Frame(self)
frm_opts.pack(fill="x", **pad)
frm_mode = ttk.LabelFrame(frm_opts, text="Format")
frm_mode.pack(side="left", fill="y")
ttk.Radiobutton(frm_mode, text="MP3 Audio", value="mp3", variable=self.mode_var, command=self._on_mode_change).pack(anchor="w", padx=10, pady=4)
ttk.Radiobutton(frm_mode, text="MP4 Video", value="mp4", variable=self.mode_var, command=self._on_mode_change).pack(anchor="w", padx=10, pady=4)
self.frm_quality = ttk.LabelFrame(frm_opts, text="Audio Quality")
self.frm_quality.pack(side="left", fill="y", padx=(10, 0))
self.quality_combo = ttk.Combobox(self.frm_quality, textvariable=self.audio_quality_var,
values=AUDIO_QUALITIES, state="readonly", width=15)
self.quality_combo.pack(padx=10, pady=10)
frm_parallel = ttk.LabelFrame(frm_opts, text="Parallel Videos")
frm_parallel.pack(side="left", fill="y", padx=(10, 0))
ttk.Combobox(frm_parallel, textvariable=self.concurrency_var, values=["1", "2"],
state="readonly", width=4).pack(padx=10, pady=10)
frm_folder = ttk.LabelFrame(self, text="Save Folder")
frm_folder.pack(fill="x", **pad)
row = ttk.Frame(frm_folder)
row.pack(fill="x", padx=8, pady=8)
ttk.Entry(row, textvariable=self.out_dir_var).pack(side="left", fill="x", expand=True)
ttk.Button(row, text="Browse...", command=self._browse_folder).pack(side="left", padx=(6, 0))
frm_cookies = ttk.LabelFrame(self, text="Advanced: manual cookies file (usually not needed - the app retries with your browser login automatically)")
frm_cookies.pack(fill="x", **pad)
row_c = ttk.Frame(frm_cookies)
row_c.pack(fill="x", padx=8, pady=8)
ttk.Entry(row_c, textvariable=self.cookies_var).pack(side="left", fill="x", expand=True)
ttk.Button(row_c, text="Browse...", command=self._browse_cookies).pack(side="left", padx=(6, 0))
ttk.Button(row_c, text="Clear", command=lambda: self.cookies_var.set("")).pack(side="left", padx=(6, 0))
self.download_btn = ttk.Button(self, text="Download", command=self._start_download)
self.download_btn.pack(pady=(4, 8))
status_bar = ttk.Frame(self)
status_bar.pack(fill="x", side="bottom")
ttk.Label(status_bar, textvariable=self.credit_var, anchor="center",
font=("Segoe UI", 8, "italic")).pack(fill="x", pady=(2, 4))
ttk.Label(status_bar, textvariable=self.status_var, anchor="w", relief="sunken").pack(fill="x", ipady=2)
frm_prog = ttk.LabelFrame(self, text="Progress")
frm_prog.pack(fill="both", expand=True, padx=12, pady=6)
top_info = ttk.Frame(frm_prog)
top_info.pack(fill="x", padx=8, pady=(6, 0))
ttk.Label(top_info, textvariable=self.playlist_var, font=("Segoe UI", 8)).pack(side="left")
ttk.Label(top_info, textvariable=self.total_speed_var, font=("Segoe UI", 9, "bold")).pack(side="right")
tree_frame = ttk.Frame(frm_prog)
tree_frame.pack(fill="both", expand=True, padx=8, pady=8)
columns = ("idx", "title", "percent", "speed", "eta", "status")
self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings", height=8)
for col, text, width, anchor in [
("idx", "#", 32, "center"),
("title", "Title", 300, "w"),
("percent", "%", 55, "center"),
("speed", "Speed", 90, "center"),
("eta", "ETA", 70, "center"),
("status", "Status", 100, "center"),
]:
self.tree.heading(col, text=text)
self.tree.column(col, width=width, anchor=anchor)
vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=vsb.set)
self.tree.pack(side="left", fill="both", expand=True)
vsb.pack(side="right", fill="y")
self.tree.bind("<Double-1>", self._on_row_double_click)
ttk.Label(frm_prog, text="Double-click a row for error details.",
font=("Segoe UI", 7), foreground="#666666").pack(anchor="w", padx=8, pady=(0, 4))
def _on_mode_change(self):
if self.mode_var.get() == "mp3":
self.frm_quality.config(text="Audio Quality")
self.quality_combo.config(textvariable=self.audio_quality_var, values=AUDIO_QUALITIES)
self.audio_quality_var.set(self.audio_quality_var.get() or AUDIO_QUALITIES[0])
else:
self.frm_quality.config(text="Resolution")
self.quality_combo.config(textvariable=self.resolution_var, values=RESOLUTIONS)
self.resolution_var.set(self.resolution_var.get() or RESOLUTIONS[0])
# ---------------------------------------------------------- actions
def _browse_folder(self):
d = filedialog.askdirectory(initialdir=self.out_dir_var.get() or os.path.expanduser("~"))
if d:
self.out_dir_var.set(d)
def _browse_cookies(self):
f = filedialog.askopenfilename(
title="Select cookies.txt",
filetypes=[("Cookies text file", "*.txt"), ("All files", "*.*")],
)
if f:
self.cookies_var.set(f)
def _on_row_double_click(self, event):
iid = self.tree.identify_row(event.y)
if not iid:
return
detail = self.row_errors.get(iid)
if detail:
vals = self.tree.item(iid, "values")
messagebox.showerror(APP_TITLE, f"{vals[1]}\n\n{detail}")
else:
messagebox.showinfo(APP_TITLE, "No error details for this item.")
def _start_download(self):
url = self.url_entry.get().strip()
if not url:
messagebox.showwarning(APP_TITLE, "Please paste a YouTube video or playlist link first.")
return
out_dir = self.out_dir_var.get().strip()
if not out_dir:
messagebox.showwarning(APP_TITLE, "Please choose a save folder.")
return
os.makedirs(out_dir, exist_ok=True)
self.download_btn.config(text="Cancel", command=self._cancel_download)
for row in self.tree.get_children():
self.tree.delete(row)
self.row_errors.clear()
self.row_speeds.clear()
self.total_speed_var.set("")
self.total_videos = 0
self.completed_videos = 0
self.playlist_var.set("")
self.status_var.set("Downloading...")
try:
concurrency = int(self.concurrency_var.get())
except ValueError:
concurrency = 2
cookies_file = self.cookies_var.get().strip() or None
self.job = MultiDownloadManager(
url, self.mode_var.get(), out_dir, self.event_q.put,
resolution=self.resolution_var.get(), audio_quality=self.audio_quality_var.get(),
concurrency=concurrency, cookies_file=cookies_file,
)
threading.Thread(target=self.job.run, daemon=True).start()
def _cancel_download(self):
if self.job:
self.job.cancel()
self.status_var.set("Cancelling...")
def _thread_safe_status(self, text):
self.event_q.put({"type": "status", "message": text})
# ---------------------------------------------------------- event loop
def _poll_queue(self):
try:
while True:
evt = self.event_q.get_nowait()
self._handle_event(evt)
except queue.Empty:
pass
self.after(100, self._poll_queue)
def _handle_event(self, evt):
t = evt["type"]
if t == "queue_ready":
videos = evt["videos"]
self.total_videos = len(videos)
self.completed_videos = 0
if evt.get("playlist_title"):
self.playlist_var.set(f"{evt['playlist_title']} - 0 / {self.total_videos} completed")
else:
self.playlist_var.set("")
for v in videos:
self.tree.insert("", "end", iid=str(v["index"]),
values=(v["index"], v["title"][:80], "", "", "", "Queued"))
elif t == "row_status":
iid = str(evt["idx"])
if evt.get("detail"):
self.row_errors[iid] = evt["detail"]
if self.tree.exists(iid):
vals = list(self.tree.item(iid, "values"))
vals[5] = evt["status"]
self.tree.item(iid, values=vals)
self.tree.see(iid)
elif t == "row_progress":
iid = str(evt["idx"])
if self.tree.exists(iid):
vals = list(self.tree.item(iid, "values"))
vals[2] = f"{evt['percent']:.0f}%"
if evt.get("speed"):
vals[3] = evt["speed"]
if evt.get("eta"):
vals[4] = evt["eta"]
vals[5] = "Downloading"
self.tree.item(iid, values=vals)
elif t == "row_done":
iid = str(evt["idx"])
if self.tree.exists(iid):
vals = list(self.tree.item(iid, "values"))
vals[2] = "100%"
vals[5] = "Done"
self.tree.item(iid, values=vals)
self.completed_videos += 1
self._update_playlist_label()
elif t == "status":
self.status_var.set(evt["message"])
elif t == "log_error":
self.status_var.set(evt["message"][:120])
elif t == "all_done":
self.status_var.set("Download complete.")
self._reset_button()
messagebox.showinfo(APP_TITLE, f"Download complete! ({self.completed_videos}/{self.total_videos} finished)")
elif t == "all_cancelled":
self.status_var.set("Cancelled.")
self._reset_button()
elif t == "fatal":
self.status_var.set("Error.")
self._reset_button()
messagebox.showerror(APP_TITLE, evt["message"])
def _update_playlist_label(self):
text = self.playlist_var.get()
if " - " in text and "completed" in text:
title = text.split(" - ")[0]
self.playlist_var.set(f"{title} - {self.completed_videos} / {self.total_videos} completed")
def _reset_button(self):
self.download_btn.config(text="Download", command=self._start_download)
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()