-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyoutube_downloader.py
More file actions
4405 lines (3689 loc) · 210 KB
/
Copy pathyoutube_downloader.py
File metadata and controls
4405 lines (3689 loc) · 210 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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import tkinter.font as tkFont
import threading
import json
import os
import sys
import subprocess
import time
import re
import tempfile
import atexit
import webbrowser
from queue import Queue
import yt_dlp
import logging
import concurrent.futures
from threading import Semaphore
# --- yt-dlp Logger Class ---
class YtDlpLogger:
"""Custom logger for yt-dlp that integrates with the application's logging system."""
def __init__(self, app_instance):
self.app = app_instance
def debug(self, msg):
"""Handle yt-dlp debug messages."""
self._queue_message(msg, "DEBUG")
def info(self, msg):
"""Handle yt-dlp info messages."""
self._queue_message(msg, "INFO")
def warning(self, msg):
"""Handle yt-dlp warning messages."""
self._queue_message(msg, "WARNING")
# Check for SABR indicators in real-time
self._check_sabr_indicators(msg)
def error(self, msg):
"""Handle yt-dlp error messages."""
self._queue_message(msg, "ERROR")
def _queue_message(self, msg, level):
"""Queue a message for thread-safe processing on the GUI thread."""
try:
# Check for stop request during any yt-dlp operation - be very aggressive
if self.app.stop_event.is_set():
elapsed_time = time.time() - getattr(self.app, '_stop_start_time', time.time())
self.app.log_message(f"LOGGER: Stop detected during yt-dlp operation after {elapsed_time:.1f}s, raising cancellation", "WARNING")
raise yt_dlp.utils.DownloadCancelled('User requested stop during extraction')
# Also check if we have a download cancellation flag
if hasattr(self.app, '_current_download_cancelled') and getattr(self.app, '_current_download_cancelled', False):
self.app.log_message("LOGGER: Download cancellation flag detected, raising cancellation", "WARNING")
raise yt_dlp.utils.DownloadCancelled('Download cancelled by monitor')
message_data = {
'message': f"[yt-dlp] {msg}",
'level': level,
'timestamp': time.time()
}
self.app.message_queue.put_nowait(message_data)
except yt_dlp.utils.DownloadCancelled:
# Re-raise cancellation exceptions
raise
except Exception:
# If queue is full or there's an error, silently ignore to prevent blocking
pass
def _check_sabr_indicators(self, msg):
"""Check if a yt-dlp message indicates SABR restrictions."""
try:
msg_lower = msg.lower()
sabr_indicators = [
'require a gvs po token',
'android client https formats require a gvs po token',
'ios client https formats require a gvs po token',
'android client sabr formats require',
'ios client sabr formats require',
'sabr formats require a gvs po token'
]
for indicator in sabr_indicators:
if indicator in msg_lower:
# SABR detected! Trigger detection if not already in SABR mode
if not self.app.sabr_mode_active:
print(f"SABR detected from yt-dlp warning: {indicator}")
# Schedule SABR activation on main thread
try:
self.app.root.after(0, self.app.activate_sabr_from_warning, msg)
except:
pass # Ignore if GUI not available
break
except:
pass # Ignore errors in SABR detection
# --- Configuration ---
SETTINGS_FILE = 'settings.json'
DEFAULT_DOWNLOAD_PATH = os.path.join(os.path.expanduser('~'), 'Downloads')
class YouTubeDownloaderApp:
"""
A GUI application for downloading YouTube videos and playlists using yt-dlp.
"""
def __init__(self, root):
self.root = root
self.root.title("YouTube Video Downloader")
self.root.geometry("800x700")
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# --- State Variables ---
self.download_queue = []
self.download_thread = None
self.is_downloading = False
self.stop_event = threading.Event()
self.progress_queue = Queue()
self.message_queue = Queue() # Queue for yt-dlp messages
self.is_updating_from_selection = False # Flag to prevent update loops
self.ydl_process = None # Store yt-dlp process for stopping
self.sort_column = None
self.sort_reverse = False
self.last_progress_time = 0 # Track last progress update time
self.stop_message_logged = False # Flag to prevent repeated stop messages
self._save_settings_after_id = None # For delayed save operations
# --- Caching Infrastructure ---
self.info_cache = {} # Cache extracted info
self.extraction_locks = {} # Prevent concurrent extractions of same URL
self.cache_expiry = {} # Track cache expiration times
# --- Batch Processing Infrastructure ---
self.extraction_semaphore = Semaphore(5) # Limit concurrent extractions
# --- SABR Bypass Mode Infrastructure ---
self.sabr_mode_active = False
self.sabr_detection_details = {}
self.last_sabr_check = None
self.sabr_indicator_frame = None
self.original_quality_options = ['Best', '2160p (4K)', '1440p (2K)', '1080p', '720p', '480p', '360p', '240p', '144p', 'Lowest']
self.original_audio_options = [
'default (Auto)',
'best (Highest Quality)',
'lowest (Smallest Size)',
'low_webm (~48kbps Opus)',
'medium_webm (~70kbps Opus)',
'standard_webm (~128kbps Opus)',
'standard_m4a (~128kbps AAC)',
'standard_mp3 (~192kbps MP3)',
'high_m4a (~160kbps AAC)'
]
self.sabr_quality_options = ['360p'] # Only 360p works under SABR restrictions
self.sabr_audio_options = ['standard_mp3 (~192kbps MP3)', 'high_m4a (~160kbps AAC)']
# --- Cookie Authentication State ---
self.cookie_browsers = ['chrome', 'firefox', 'edge', 'brave', 'opera', 'vivaldi', 'chromium', 'whale', 'safari']
# --- GUI Variables ---
self.download_path = tk.StringVar(value=DEFAULT_DOWNLOAD_PATH)
self.log_level_var = tk.StringVar(value='INFO')
self.yt_dlp_debug_var = tk.BooleanVar(value=False)
self.console_visible_var = tk.BooleanVar(value=True)
# Cookie GUI variables
self.cookie_mode = tk.StringVar(value='none')
self.cookie_browser = tk.StringVar(value='chrome')
self.cookie_browser_profile = tk.StringVar(value='')
self.cookie_file_path = tk.StringVar(value='')
# --- yt-dlp Logger ---
self.yt_dlp_logger = YtDlpLogger(self)
# --- GUI Setup ---
self.setup_gui()
self.load_settings()
self.process_progress_queue()
self.process_message_queue()
# Start periodic cache cleanup
self.root.after(300000, self.periodic_cleanup) # Start cleanup after 5 minutes
def setup_gui(self):
"""Creates and arranges all the GUI widgets."""
# --- Main Frames ---
top_frame = ttk.Frame(self.root, padding="10")
top_frame.pack(fill=tk.X, side=tk.TOP)
list_frame = ttk.Frame(self.root, padding="10")
list_frame.pack(fill=tk.BOTH, expand=True)
console_frame = ttk.Frame(self.root, padding="10")
console_frame.pack(fill=tk.X, side=tk.BOTTOM)
# --- Top Frame: URL Input and Controls ---
ttk.Label(top_frame, text="YouTube URL:").grid(row=0, column=0, padx=(0, 5), sticky='w')
self.url_entry = ttk.Entry(top_frame, width=60)
self.url_entry.grid(row=0, column=1, sticky='ew')
self.add_button = ttk.Button(top_frame, text="Add", command=self.add_url)
self.add_button.grid(row=0, column=2, padx=5)
top_frame.grid_columnconfigure(1, weight=1)
# --- Options Frame: Quality and Audio-Only ---
options_frame = ttk.Frame(top_frame)
options_frame.grid(row=1, column=1, sticky='w', pady=5)
ttk.Label(options_frame, text="Quality:").pack(side=tk.LEFT, padx=(0, 5))
self.quality_var = tk.StringVar(value='1080p')
quality_options = ['Best', '2160p (4K)', '1440p (2K)', '1080p', '720p', '480p', '360p', '240p', '144p', 'Lowest']
self.quality_menu = ttk.OptionMenu(options_frame, self.quality_var, quality_options[3], *quality_options) # Default to 1080p
self.quality_menu.pack(side=tk.LEFT, padx=(0, 20))
self.audio_only_var = tk.BooleanVar()
self.audio_only_check = ttk.Checkbutton(options_frame, text="Audio Only", variable=self.audio_only_var, command=self.on_audio_only_change)
self.audio_only_check.pack(side=tk.LEFT)
# Audio format dropdown (initially hidden)
self.audio_format_var = tk.StringVar(value='default')
self.audio_format_options = [
'default (Auto)',
'best (Highest Quality)',
'lowest (Smallest Size)',
'low_webm (~48kbps Opus)',
'medium_webm (~70kbps Opus)',
'standard_webm (~128kbps Opus)',
'standard_m4a (~128kbps AAC)',
'standard_mp3 (~192kbps MP3)',
'high_m4a (~160kbps AAC)'
]
self.audio_format_menu = ttk.OptionMenu(options_frame, self.audio_format_var, self.audio_format_options[0], *self.audio_format_options)
self.audio_format_menu.pack(side=tk.LEFT, padx=(5, 0))
self.audio_format_menu.pack_forget() # Hide initially
# Info text about settings applying to selected and new items
ttk.Label(options_frame, text="Works on selected as well as on new", font=("Arial", 8), foreground="gray").pack(side=tk.LEFT, padx=(20, 0))
# Check FFmpeg availability and update audio options
self.check_ffmpeg_availability()
self.quality_var.trace_add('write', self.on_setting_change)
self.audio_format_var.trace_add('write', self.on_setting_change)
# --- Download Path Frame ---
path_frame = ttk.Frame(top_frame)
path_frame.grid(row=2, column=0, columnspan=3, sticky='ew', pady=5)
ttk.Label(path_frame, text="Download Folder:").pack(side=tk.LEFT, padx=(0, 5))
self.path_entry = ttk.Entry(path_frame, textvariable=self.download_path, state='readonly')
self.path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.change_path_button = ttk.Button(path_frame, text="Change...", command=self.change_download_path)
self.change_path_button.pack(side=tk.LEFT, padx=5)
# --- Control Buttons Frame ---
control_frame = ttk.Frame(top_frame)
control_frame.grid(row=3, column=0, columnspan=3, sticky='w', pady=5)
# Start button with play icon (▶)
self.start_button = ttk.Button(control_frame, text="▶", command=self.start_download, width=3)
self.start_button.pack(side=tk.LEFT, padx=(0, 5))
# Stop button with stop icon (⏹)
self.stop_button = ttk.Button(control_frame, text="⏹", command=self.stop_download, state=tk.DISABLED, width=3)
self.stop_button.pack(side=tk.LEFT, padx=(0, 10))
# Divider
ttk.Label(control_frame, text="|", foreground="gray").pack(side=tk.LEFT, padx=(0, 10))
# Move Up button with up arrow (↑)
self.move_up_button = ttk.Button(control_frame, text="↑", command=self.move_up, width=3)
self.move_up_button.pack(side=tk.LEFT, padx=(0, 5))
# Move Down button with down arrow (↓)
self.move_down_button = ttk.Button(control_frame, text="↓", command=self.move_down, width=3)
self.move_down_button.pack(side=tk.LEFT, padx=(0, 5))
# Add To Top button with underline and up arrow (⎺↑)
self.add_to_top_button = ttk.Button(control_frame, text="⎺↑", command=self.move_to_top, width=3)
self.add_to_top_button.pack(side=tk.LEFT, padx=(0, 5))
# Add To Bottom button with overline and down arrow (⎽↓)
self.add_to_bottom_button = ttk.Button(control_frame, text="⎽↓", command=self.move_to_bottom, width=3)
self.add_to_bottom_button.pack(side=tk.LEFT, padx=(0, 10))
# Divider
ttk.Label(control_frame, text="|", foreground="gray").pack(side=tk.LEFT, padx=(0, 10))
# Reset button with circular arrow (↻)
self.reset_button = ttk.Button(control_frame, text="↻", command=self.reset_selected, state=tk.DISABLED, width=3)
self.reset_button.pack(side=tk.LEFT, padx=(0, 10))
# Divider
ttk.Label(control_frame, text="|", foreground="gray").pack(side=tk.LEFT, padx=(0, 10))
# Remove Selected button
self.remove_button = ttk.Button(control_frame, text="Remove Selected", command=self.remove_selected)
self.remove_button.pack(side=tk.LEFT, padx=(0, 5))
# Clear All button
self.clear_all_button = ttk.Button(control_frame, text="Clear All", command=self.clear_all)
self.clear_all_button.pack(side=tk.LEFT)
# --- SABR Control Frame (new line under control buttons) ---
sabr_control_frame = ttk.Frame(top_frame)
sabr_control_frame.grid(row=4, column=0, columnspan=3, sticky='w', pady=5)
# Manual SABR Check button
self.manual_sabr_button = ttk.Button(sabr_control_frame, text="Check SABR", command=self.manual_sabr_check)
self.manual_sabr_button.pack(side=tk.LEFT, padx=(0, 5))
# Force SABR Mode button
self.force_sabr_button = ttk.Button(sabr_control_frame, text="Force SABR", command=self.force_sabr_mode)
self.force_sabr_button.pack(side=tk.LEFT, padx=(0, 5))
# SABR indicator will be added here dynamically when active
self.sabr_control_frame = sabr_control_frame
# --- Cookie Authentication Frame (row 5 under SABR controls) ---
cookie_frame = ttk.Frame(top_frame)
cookie_frame.grid(row=5, column=0, columnspan=3, sticky='ew', pady=5)
ttk.Label(cookie_frame, text="🍪 Cookies:").pack(side=tk.LEFT, padx=(0, 2))
# Help button for cookie setup guidance
cookie_help_btn = tk.Button(cookie_frame, text="?", font=("Arial", 7, "bold"),
width=2, height=1, relief='groove', cursor='hand2',
command=self.show_cookie_help)
cookie_help_btn.pack(side=tk.LEFT, padx=(0, 5))
# Mode dropdown: None / From Browser / From File
cookie_modes = ['None', 'From Browser', 'From File']
self.cookie_mode_menu = ttk.OptionMenu(cookie_frame, self.cookie_mode, 'none',
*[m.lower().replace(' ', '_') for m in cookie_modes])
# Override with user-friendly labels
menu = self.cookie_mode_menu['menu']
menu.delete(0, 'end')
mode_map = [('none', 'None'), ('from_browser', 'From Browser'), ('from_file', 'From File')]
for val, label in mode_map:
menu.add_command(label=label, command=lambda v=val: self._set_cookie_mode(v))
self.cookie_mode_menu.pack(side=tk.LEFT, padx=(0, 10))
# --- Browser sub-widgets (shown when mode = from_browser) ---
self.cookie_browser_frame = ttk.Frame(cookie_frame)
ttk.Label(self.cookie_browser_frame, text="Browser:").pack(side=tk.LEFT, padx=(0, 3))
self.cookie_browser_menu = ttk.OptionMenu(self.cookie_browser_frame, self.cookie_browser,
'chrome', *self.cookie_browsers)
self.cookie_browser_menu.pack(side=tk.LEFT, padx=(0, 8))
ttk.Label(self.cookie_browser_frame, text="Profile:").pack(side=tk.LEFT, padx=(0, 3))
self.cookie_profile_entry = ttk.Entry(self.cookie_browser_frame, textvariable=self.cookie_browser_profile, width=14)
self.cookie_profile_entry.pack(side=tk.LEFT, padx=(0, 8))
self.cookie_browser_warning = tk.Label(self.cookie_browser_frame, text="⚠ Close browser first!",
font=("Arial", 8, "bold"), fg="orange")
self.cookie_browser_warning.pack(side=tk.LEFT, padx=(5, 0))
# Test Cookies button
self.cookie_test_button = ttk.Button(self.cookie_browser_frame, text="Test",
command=self.test_browser_cookies, width=5)
self.cookie_test_button.pack(side=tk.LEFT, padx=(8, 0))
# Hidden initially
# --- File sub-widgets (shown when mode = from_file) ---
self.cookie_file_frame = ttk.Frame(cookie_frame)
self.cookie_file_entry = ttk.Entry(self.cookie_file_frame, textvariable=self.cookie_file_path, width=40, state='readonly')
self.cookie_file_entry.pack(side=tk.LEFT, padx=(0, 5))
self.cookie_browse_button = ttk.Button(self.cookie_file_frame, text="Browse...", command=self.browse_cookie_file)
self.cookie_browse_button.pack(side=tk.LEFT, padx=(0, 8))
tk.Label(self.cookie_file_frame, text="Netscape cookies.txt", font=("Arial", 8), fg="gray").pack(side=tk.LEFT)
# Hidden initially
# Status label for cookie authentication
self.cookie_status_label = tk.Label(cookie_frame, text="", font=("Arial", 8), fg="green")
self.cookie_status_label.pack(side=tk.LEFT, padx=(10, 0))
# --- List Frame: Download Queue ---
# Status summary frame with colored labels (above the table)
status_summary_frame = ttk.Frame(list_frame)
status_summary_frame.pack(fill=tk.X, pady=(0, 5))
# Individual status labels with colors
self.total_label = tk.Label(status_summary_frame, text="Total: 0", font=("Arial", 9, "bold"), fg="black")
self.total_label.pack(side=tk.LEFT, padx=(5, 10))
self.done_label = tk.Label(status_summary_frame, text="Done: 0", font=("Arial", 9, "bold"), fg="green")
self.done_label.pack(side=tk.LEFT, padx=(0, 10))
self.pending_label = tk.Label(status_summary_frame, text="Pending: 0", font=("Arial", 9, "bold"), fg="black")
self.pending_label.pack(side=tk.LEFT, padx=(0, 10))
self.failed_label = tk.Label(status_summary_frame, text="Failed: 0", font=("Arial", 9, "bold"), fg="red")
self.failed_label.pack(side=tk.LEFT, padx=(0, 10))
self.skipped_label = tk.Label(status_summary_frame, text="Skipped: 0", font=("Arial", 9, "bold"), fg="purple")
self.skipped_label.pack(side=tk.LEFT, padx=(0, 10))
self.quality_blocked_label = tk.Label(status_summary_frame, text="QualityBlocked: 0", font=("Arial", 9, "bold"), fg="orange")
self.quality_blocked_label.pack(side=tk.LEFT, padx=(0, 10))
self.age_restricted_label = tk.Label(status_summary_frame, text="AgeRestricted: 0", font=("Arial", 9, "bold"), fg="brown")
self.age_restricted_label.pack(side=tk.LEFT, padx=(0, 10))
self.downloading_label = tk.Label(status_summary_frame, text="Downloading: 0", font=("Arial", 9, "bold"), fg="blue")
self.downloading_label.pack(side=tk.LEFT)
# Create a frame for the treeview with line numbers
tree_container = ttk.Frame(list_frame)
tree_container.pack(fill=tk.BOTH, expand=True)
# Create frames for line numbers and treeview
left_line_frame = ttk.Frame(tree_container, width=40)
left_line_frame.pack(side=tk.LEFT, fill=tk.Y)
left_line_frame.pack_propagate(False) # Maintain fixed width
tree_frame = ttk.Frame(tree_container)
tree_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
right_line_frame = ttk.Frame(tree_container, width=40)
right_line_frame.pack(side=tk.RIGHT, fill=tk.Y)
right_line_frame.pack_propagate(False) # Maintain fixed width
# Create line number labels containers
self.left_line_labels = []
self.right_line_labels = []
# Create scrollable frame for left line numbers
self.left_line_canvas = tk.Canvas(left_line_frame, width=40, bg='lightgray')
self.left_line_canvas.pack(fill=tk.BOTH, expand=True)
# Create scrollable frame for right line numbers
self.right_line_canvas = tk.Canvas(right_line_frame, width=40, bg='lightgray')
self.right_line_canvas.pack(fill=tk.BOTH, expand=True)
self.tree = ttk.Treeview(tree_frame, columns=('ID', 'Name', 'Quality', 'Duration', 'Status'), show='headings')
self.tree.heading('ID', text='Video ID', command=lambda: self.sort_treeview('ID'))
self.tree.heading('Name', text='Video Title', command=lambda: self.sort_treeview('Name'))
self.tree.heading('Quality', text='Format', command=lambda: self.sort_treeview('Quality'))
self.tree.heading('Duration', text='Duration', command=lambda: self.sort_treeview('Duration'))
self.tree.heading('Status', text='Status', command=lambda: self.sort_treeview('Status'))
self.tree.column('ID', width=120)
self.tree.column('Name', width=300)
self.tree.column('Quality', width=100, anchor='center')
self.tree.column('Duration', width=80, anchor='center')
self.tree.column('Status', width=100, anchor='center')
self.tree.bind('<<TreeviewSelect>>', self.on_video_select)
self.tree.bind('<Button-1>', self.on_tree_click) # Handle mouse clicks
self.tree.bind('<Button-3>', self.on_right_click) # Handle right-click for context menu
self.tree.bind('<Motion>', self.on_tree_motion) # Handle mouse motion for cursor changes
self.tree.bind('<Enter>', self.on_tree_enter) # Handle mouse enter
self.tree.bind('<Leave>', self.on_tree_leave) # Handle mouse leave
# Configure status colors
self.setup_status_colors()
# Scrollbar for the treeview with synchronized line numbers
tree_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.on_tree_scroll)
self.tree.configure(yscroll=self.on_tree_scrollbar_set)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
tree_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# --- Console Frame: Progress Output ---
console_header_frame = ttk.Frame(console_frame)
console_header_frame.pack(fill=tk.X, pady=(0, 5))
# Console visibility checkbox
self.console_check = ttk.Checkbutton(console_header_frame, text="Console",
variable=self.console_visible_var, command=self.on_console_visibility_change)
self.console_check.pack(side=tk.LEFT)
# Log level dropdown - moved to left side
log_level_frame = ttk.Frame(console_header_frame)
log_level_frame.pack(side=tk.LEFT, padx=(20, 0))
ttk.Label(log_level_frame, text="Log Level:").pack(side=tk.LEFT, padx=(0, 5))
log_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
self.log_level_menu = ttk.OptionMenu(log_level_frame, self.log_level_var, 'INFO', *log_levels, command=self.on_log_level_change)
self.log_level_menu.pack(side=tk.LEFT)
# yt-dlp debug checkbox
self.yt_dlp_debug_check = ttk.Checkbutton(console_header_frame, text="Show yt-dlp debug output",
variable=self.yt_dlp_debug_var, command=self.on_yt_dlp_debug_change)
self.yt_dlp_debug_check.pack(side=tk.LEFT, padx=(20, 0))
# Check Dependencies button
self.check_deps_button = ttk.Button(console_header_frame, text="Check Dependencies", command=self.check_dependencies)
self.check_deps_button.pack(side=tk.LEFT, padx=(20, 0))
# Clear Logs button
self.clear_logs_button = ttk.Button(console_header_frame, text="Clear Logs", command=self.clear_logs)
self.clear_logs_button.pack(side=tk.LEFT, padx=(10, 0))
self.console = scrolledtext.ScrolledText(console_frame, height=14, state=tk.DISABLED, bg='black', fg='white', font=("Courier", 9))
self.console.pack(fill=tk.X, expand=True)
def setup_status_colors(self):
"""Configure treeview tags for status colors."""
self.tree.tag_configure('pending', foreground='black')
self.tree.tag_configure('downloading', foreground='blue')
self.tree.tag_configure('done', foreground='green')
self.tree.tag_configure('failed', foreground='red')
self.tree.tag_configure('skipped', foreground='purple')
self.tree.tag_configure('qualityblocked', foreground='orange')
self.tree.tag_configure('agerestricted', foreground='brown')
self.tree.tag_configure('hover', background='lightgray')
self.tree.tag_configure('current_item', background='lightgreen')
# Track current hover item
self.current_hover_item = None
def update_line_numbers(self):
"""Updates line numbers and highlights currently downloading item."""
# Clear existing line numbers
self.left_line_canvas.delete("all")
self.right_line_canvas.delete("all")
# Get all items in the treeview
all_items = self.tree.get_children()
if not all_items:
# Handle empty queue state gracefully
self.left_line_canvas.configure(scrollregion=(0, 0, 0, 0))
self.right_line_canvas.configure(scrollregion=(0, 0, 0, 0))
return
# Calculate proper row height and header offset
try:
# Get the actual row height from treeview
sample_bbox = self.tree.bbox(all_items[0])
if sample_bbox:
row_height = sample_bbox[3] # Height of the row
header_height = sample_bbox[1] # Y position of first row (header offset)
else:
row_height = 20 # Fallback height
header_height = 20 # Fallback header height
except:
row_height = 20 # Fallback height
header_height = 20 # Fallback header height
# Find currently downloading item
downloading_item_index = -1
for i, item_id in enumerate(all_items):
current_values = self.tree.item(item_id, 'values')
if len(current_values) >= 5 and current_values[4] == '↓ Downloading':
downloading_item_index = i
break
# If no item is downloading, highlight the first pending item
if downloading_item_index == -1:
for i, item_id in enumerate(all_items):
current_values = self.tree.item(item_id, 'values')
if len(current_values) >= 5 and current_values[4] == 'Pending':
downloading_item_index = i
break
# Remove current_item tag from all items first
for item_id in all_items:
current_tags = list(self.tree.item(item_id, 'tags'))
if 'current_item' in current_tags:
current_tags.remove('current_item')
self.tree.item(item_id, tags=current_tags)
# Create line numbers for each item
for i, item_id in enumerate(all_items):
line_num = i + 1
y_pos = header_height + (i * row_height) + (row_height // 2) # Account for header and center in row
# Check if this is the current/downloading item
is_current = (i == downloading_item_index)
# Left line numbers
if is_current:
left_text = f"> {line_num}"
self.left_line_canvas.create_text(20, y_pos, text=left_text, anchor="center",
fill="darkgreen", font=("Arial", 9, "bold"))
else:
self.left_line_canvas.create_text(20, y_pos, text=str(line_num), anchor="center",
fill="gray", font=("Arial", 9))
# Right line numbers
if is_current:
right_text = f"{line_num} <"
self.right_line_canvas.create_text(20, y_pos, text=right_text, anchor="center",
fill="darkgreen", font=("Arial", 9, "bold"))
else:
self.right_line_canvas.create_text(20, y_pos, text=str(line_num), anchor="center",
fill="gray", font=("Arial", 9))
# Update canvas scroll region to match the content height
total_height = header_height + (len(all_items) * row_height)
self.left_line_canvas.configure(scrollregion=(0, 0, 40, total_height))
self.right_line_canvas.configure(scrollregion=(0, 0, 40, total_height))
# Highlight current item with light green background
if downloading_item_index >= 0 and downloading_item_index < len(all_items):
current_item = all_items[downloading_item_index]
current_tags = list(self.tree.item(current_item, 'tags'))
# Add current_item tag if not already present
if 'current_item' not in current_tags:
current_tags.append('current_item')
self.tree.item(current_item, tags=current_tags)
def on_tree_scroll(self, *args):
"""Handle treeview scrolling and synchronize line numbers."""
self.tree.yview(*args)
# Synchronize line number canvases
self.left_line_canvas.yview(*args)
self.right_line_canvas.yview(*args)
def on_tree_scrollbar_set(self, first, last):
"""Handle scrollbar updates and synchronize line numbers."""
# Update the scrollbar
tree_scrollbar = None
for child in self.tree.master.winfo_children():
if isinstance(child, ttk.Scrollbar):
tree_scrollbar = child
break
if tree_scrollbar:
tree_scrollbar.set(first, last)
# Synchronize line number canvases
self.left_line_canvas.yview_moveto(first)
self.right_line_canvas.yview_moveto(first)
def format_video_id_with_icon(self, video_id):
"""Format Video ID with link icon if it's clickable."""
if video_id and video_id != 'N/A' and self.is_valid_video_id(video_id):
return f"🔗 {video_id}"
else:
return video_id or 'N/A'
def is_valid_video_id(self, video_id):
"""Check if a Video ID appears to be valid for YouTube."""
if not video_id or video_id == 'N/A':
return False
# YouTube Video IDs are typically 11 characters long and contain alphanumeric characters, hyphens, and underscores
import re
return bool(re.match(r'^[a-zA-Z0-9_-]{11}$', video_id))
def open_video_in_browser(self, video_id):
"""Open a YouTube video in the default browser with enhanced error handling."""
if not video_id or video_id == 'N/A':
self.log_message("Cannot open video: Invalid Video ID", "WARNING")
return False
youtube_url = f"https://www.youtube.com/watch?v={video_id}"
try:
webbrowser.open(youtube_url)
self.log_message(f"Opened YouTube video: {video_id}")
return True
except Exception as e:
self.log_message(f"Failed to open browser for video {video_id}: {e}", "ERROR")
return False
def change_download_path(self):
"""Opens a dialog to choose a new download directory."""
new_path = filedialog.askdirectory(title="Select Download Folder", initialdir=self.download_path.get())
if new_path:
self.download_path.set(new_path)
self.log_message(f"Download path set to: {new_path}")
self.schedule_save_settings()
def on_video_select(self, event):
"""Updates quality controls when a video is selected in the list."""
if self.url_entry.get().strip(): # Do nothing if user is typing a new URL
return
selected_items = self.tree.selection()
if not selected_items:
return
item_id = selected_items[0] # Handle only the first selected item
video_info = None
for v in self.download_queue:
if v['item_id'] == item_id:
video_info = v
break
if video_info:
self.is_updating_from_selection = True # Set flag to prevent trace callback
quality = video_info['quality']
if quality.startswith('Audio-'):
self.audio_only_var.set(True)
audio_format = quality.split('-')[1] # Extract format key
# Map format keys to display names
format_display_map = {
'default': 'default (Auto)',
'best': 'best (Highest Quality)',
'lowest': 'lowest (Smallest Size)',
'low_webm': 'low_webm (~48kbps Opus)',
'medium_webm': 'medium_webm (~70kbps Opus)',
'standard_webm': 'standard_webm (~128kbps Opus)',
'standard_m4a': 'standard_m4a (~128kbps AAC)',
'standard_mp3': 'standard_mp3 (~192kbps MP3)',
'high_m4a': 'high_m4a (~160kbps AAC)'
}
display_name = format_display_map.get(audio_format, 'default (Auto)')
self.audio_format_var.set(display_name)
self.audio_format_menu.pack(side=tk.LEFT, padx=(5, 0), after=self.audio_only_check)
self.quality_menu.config(state=tk.DISABLED)
else:
self.audio_only_var.set(False)
self.audio_format_menu.pack_forget()
self.quality_var.set(quality)
self.quality_menu.config(state=tk.NORMAL)
self.is_updating_from_selection = False # Unset flag
# Update reset button state and status summary
self.update_reset_button_state()
self.update_status_summary()
def on_tree_click(self, event):
"""Handle mouse clicks on the treeview to detect Video ID column clicks."""
# Identify what was clicked
region = self.tree.identify_region(event.x, event.y)
if region == "cell":
# Get the column that was clicked
column = self.tree.identify_column(event.x)
# Column #1 is the Video ID column (columns are 1-indexed)
if column == '#1':
# Get the item that was clicked
item = self.tree.identify_row(event.y)
if item:
# Get the video ID from the item
values = self.tree.item(item, 'values')
if len(values) > 0:
video_id_display = values[0] # Video ID display value (may have icon) - back to index 0
# Only process clicks on items with the link icon (clickable Video IDs)
if video_id_display and video_id_display.startswith('🔗 '):
# Extract actual Video ID by removing the icon prefix
video_id = video_id_display.replace('🔗 ', '')
# Open video in browser using enhanced method
self.open_video_in_browser(video_id)
def on_tree_motion(self, event):
"""Handle mouse motion over treeview to change cursor for Video ID column and handle hover highlighting."""
# Handle hover highlighting
item = self.tree.identify_row(event.y)
if item and item != self.current_hover_item:
# Remove hover from previous item
if self.current_hover_item:
current_tags = list(self.tree.item(self.current_hover_item, 'tags'))
if 'hover' in current_tags:
current_tags.remove('hover')
self.tree.item(self.current_hover_item, tags=current_tags)
# Add hover to new item
if item:
current_tags = list(self.tree.item(item, 'tags'))
if 'hover' not in current_tags:
current_tags.append('hover')
self.tree.item(item, tags=current_tags)
self.current_hover_item = item
# Handle cursor changes for Video ID column
region = self.tree.identify_region(event.x, event.y)
if region == "cell":
column = self.tree.identify_column(event.x)
# Column #1 is the Video ID column
if column == '#1':
if item:
values = self.tree.item(item, 'values')
if len(values) > 0 and values[0] and values[0].startswith('🔗 '):
# Change cursor to hand pointer for clickable Video IDs (those with icons)
self.tree.config(cursor="hand2")
return
# Reset cursor to default for all other areas
self.tree.config(cursor="")
def on_tree_enter(self, event):
"""Handle mouse entering the treeview."""
pass # Motion handler will take care of hover highlighting
def on_right_click(self, event):
"""Handle right-click to show context menu for removing selected videos."""
# Select the item under the cursor if not already selected
item = self.tree.identify_row(event.y)
current_selection = self.tree.selection()
if item:
# If the clicked item is not in the current selection, replace selection with just this item
# If it's already selected, keep the current selection (supports multi-select)
if item not in current_selection:
self.tree.selection_set(item)
# Get updated selection (may include multiple items)
updated_selection = self.tree.selection()
num_selected = len(updated_selection)
# Create context menu
context_menu = tk.Menu(self.root, tearoff=0)
# Show appropriate label based on selection count
if num_selected == 1:
context_menu.add_command(label="Remove", command=self.remove_selected)
else:
context_menu.add_command(label=f"Remove {num_selected} Selected", command=self.remove_selected)
context_menu.add_separator()
context_menu.add_command(label="Remove All", command=self.clear_all)
# Show the context menu at the cursor position
try:
context_menu.tk_popup(event.x_root, event.y_root)
finally:
# Make sure to release the menu on release
context_menu.grab_release()
elif current_selection:
# Right-click on empty space but items are selected - show menu for selected items
num_selected = len(current_selection)
context_menu = tk.Menu(self.root, tearoff=0)
if num_selected == 1:
context_menu.add_command(label="Remove", command=self.remove_selected)
else:
context_menu.add_command(label=f"Remove {num_selected} Selected", command=self.remove_selected)
context_menu.add_separator()
context_menu.add_command(label="Remove All", command=self.clear_all)
try:
context_menu.tk_popup(event.x_root, event.y_root)
finally:
context_menu.grab_release()
# If no item and no selection, don't show menu (nothing to remove)
def on_tree_leave(self, event):
"""Handle mouse leaving the treeview."""
# Remove hover highlighting when mouse leaves
if self.current_hover_item:
current_tags = list(self.tree.item(self.current_hover_item, 'tags'))
if 'hover' in current_tags:
current_tags.remove('hover')
self.tree.item(self.current_hover_item, tags=current_tags)
self.current_hover_item = None
def on_audio_only_change(self):
"""Handles audio only checkbox changes and shows/hides audio format dropdown."""
if self.audio_only_var.get():
# Show audio format dropdown and disable quality dropdown
self.audio_format_menu.pack(side=tk.LEFT, padx=(5, 0), after=self.audio_only_check)
self.quality_menu.config(state=tk.DISABLED)
else:
# Hide audio format dropdown and enable quality dropdown
self.audio_format_menu.pack_forget()
self.quality_menu.config(state=tk.NORMAL)
self.on_setting_change()
def on_setting_change(self, *args):
"""Updates a selected video's settings when controls are changed."""
if self.is_updating_from_selection: # Do nothing if change was triggered by selection
return
selected_items = self.tree.selection()
if not selected_items:
return
if self.audio_only_var.get():
audio_format = self.audio_format_var.get()
# Extract the format key from the display name
format_key = audio_format.split()[0] # Extract 'default', 'best', 'standard_mp3', etc.
new_quality = f'Audio-{format_key}'
else:
new_quality = self.quality_var.get()
for item_id in selected_items:
# Update internal data
for video in self.download_queue:
if video['item_id'] == item_id:
video['quality'] = new_quality
break
# Update GUI
current_values = self.tree.item(item_id, 'values')
status = current_values[4] if len(current_values) > 4 else 'Pending'
self.tree.item(item_id, values=(current_values[0], current_values[1], new_quality, current_values[3] if len(current_values) > 3 else 'N/A', status))
self.log_message(f"Updated settings for {len(selected_items)} selected item(s).")
self.schedule_save_settings()
def on_log_level_change(self, selected_level):
"""Handles log level dropdown changes."""
self.log_message(f"Log level changed to: {selected_level}")
self.schedule_save_settings() # Save the new log level setting
def on_yt_dlp_debug_change(self):
"""Handles yt-dlp debug checkbox changes."""
if self.yt_dlp_debug_var.get():
self.log_message("yt-dlp debug output enabled")
else:
self.log_message("yt-dlp debug output disabled")
self.schedule_save_settings() # Save the new debug setting
def on_console_visibility_change(self):
"""Handles console visibility checkbox changes."""
if self.console_visible_var.get():
self.console.pack(fill=tk.X, expand=True)
self.log_message("Console shown")
else:
self.console.pack_forget()
self.schedule_save_settings() # Save the new console visibility setting
def clear_logs(self):
"""Clears all messages from the console."""
self.console.config(state=tk.NORMAL)
self.console.delete(1.0, tk.END)
self.console.config(state=tk.DISABLED)
# Don't log a message about clearing logs since we just cleared them
def configure_ydl_opts_with_logger(self, ydl_opts):
"""Configure ydl_opts with logger when debug is enabled."""
if self.yt_dlp_debug_var.get():
# Enable debug logging
ydl_opts['logger'] = self.yt_dlp_logger
ydl_opts['quiet'] = False
ydl_opts['no_warnings'] = False
else:
# Keep quiet mode when debug is disabled
ydl_opts['quiet'] = True
ydl_opts['no_warnings'] = True
# Add common performance optimizations
ydl_opts.update({
'ignoreerrors': True,
'writeinfojson': False,
'writethumbnail': False,
'writesubtitles': False,
'writeautomaticsub': False,
'nocheckcertificate': True,
'prefer_insecure': False
})
return ydl_opts
def build_extractor_args(self):
"""Build unified extractor arguments for consistent YouTube handling.
When cookies are active, android/ios clients are skipped by yt-dlp
(they don't support cookies). Use cookie-compatible clients instead.
"""
cookie_mode = getattr(self, 'cookie_mode', None)
cookies_active = cookie_mode and cookie_mode.get() not in ('', 'none', None)
if cookies_active:
# Cookie-compatible clients only — android/ios don't support cookies
return {
'youtube': {
'player_client': ['tv', 'web_safari', 'web'],
}
}
else:
# Default SABR bypass configuration (no cookies)
return {
'youtube': {
'player_client': ['android', 'tv', 'ios'],
'player_skip': ['webpage', 'configs'],
'skip': ['hls', 'dash'],
'include_hls_manifest': False,
'include_dash_manifest': False
}
}
def get_audio_format_selector(self, quality_option, ffmpeg_available=True):
"""Generate yt-dlp format selector based on audio quality choice with SABR-compatible fallbacks."""
# When cookies are active, HTTPS audio formats also return 403.
# Use HLS format with bestaudio fallback.
cookie_mode = getattr(self, 'cookie_mode', None)
cookies_active = cookie_mode and cookie_mode.get() not in ('', 'none', None)
if cookies_active:
selected_format = 'bestaudio[protocol=m3u8_native]/bestaudio[protocol=m3u8]/bestaudio/worst'
self.log_message(f"Audio format selector for '{quality_option}' (HLS/cookie mode): {selected_format}", "DEBUG")
return selected_format
# Progressive fallback strategy for audio formats due to SABR/PO Token restrictions
audio_format_map = {
'default': 'bestaudio/best[height<=480]/best', # Fallback to low-res video if needed
'lowest': 'worstaudio/bestaudio/best[height<=360]/best',
'best': 'bestaudio/best[height<=720]/best',
'low_webm': 'bestaudio[ext=webm]/bestaudio/best[height<=360]/best',
'medium_webm': 'bestaudio[ext=webm]/bestaudio/best[height<=480]/best',
'standard_webm': 'bestaudio[ext=webm]/bestaudio/best[height<=480]/best',