-
Notifications
You must be signed in to change notification settings - Fork 6
/
core.py
1091 lines (876 loc) · 46.2 KB
/
core.py
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 json
import os
import sys
from PyQt5.QtCore import QProcess, pyqtSignal, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QFileDialog, QTreeWidgetItem, qApp, QDialog, QApplication, QMessageBox, \
QTabWidget, QListWidgetItem
from Modules import Dialog, Download, MainTab, ParameterTree, MainWindow, AboutTab, Downloader, ParameterTab, TextTab
from Modules.download_element import ProcessListItem, MockDownload
from Modules.parameter_tree import DATA_SLOT, LEVEL_SLOT, INDEX_SLOT, DISPLAY_NAME_SLOT
from utils.filehandler import FileHandler
from utils.utilities import path_shortener, color_text, format_in_list, SettingsError, get_stylesheet, \
get_win_accent_color, ProfileLoadError, LessNiceDict, to_clipboard
class GUI(MainWindow):
"""
Runnable class that makes a wrapper for youtube-dl.
"""
sendClose = pyqtSignal()
EXIT_CODE_REBOOT = -123456789
def __init__(self):
"""
GUI that wraps a youtube-dl.exe to download videos and more.
"""
super().__init__()
# startup checks
self.initial_checks()
# Holds temporary passwords
# TODO: Better password solution
self._temp = LessNiceDict()
# Builds GUI and everything related to that.
self.build_gui()
def initial_checks(self):
"""Loads settings and finds necessary files. Checks the setting file for errors."""
self._debug = None
self.file_handler = FileHandler()
self.settings = self.file_handler.load_settings()
self.downloader = Downloader(self.file_handler, self.settings.user_options['parallel'])
# Find important executables and files
self.youtube_dl_path = self.file_handler.find_exe('youtube-dl.exe')
self.ffmpeg_path = self.file_handler.find_exe('ffmpeg.exe')
self.program_workdir = self.file_handler.work_dir
self.license_path = self.file_handler.find_file('LICENSE')
# Download destination if not set by user
self.local_dl_path = self.file_handler.work_dir + '/DL/'
# NB! For stylesheet stuff, the slashes '\' in the path, must be replaced with '/'.
# Using replace('\\', '/') on path. Done by file handler.
self.icon_list = []
# TODO: Turn into something more practical??
# Find icon paths
self.unchecked_icon = self.file_handler.find_file('GUI\\Icon_unchecked.ico')
self.checked_icon = self.file_handler.find_file('GUI\\Icon_checked.ico')
self.alert_icon = self.file_handler.find_file('GUI\\Alert.ico')
self.window_icon = self.file_handler.find_file('GUI\\Grabber.ico')
self.down_arrow_icon = self.file_handler.find_file('GUI\\down-arrow2.ico')
self.down_arrow_icon_clicked = self.file_handler.find_file('GUI\\down-arrow2-clicked.ico')
# Adding icons to list. For debug purposes.
self.icon_list.append(self.unchecked_icon)
self.icon_list.append(self.checked_icon)
self.icon_list.append(self.alert_icon)
self.icon_list.append(self.window_icon)
self.icon_list.append(self.down_arrow_icon)
self.icon_list.append(self.down_arrow_icon_clicked)
# Creating icon objects for use in message windows.
self.alertIcon = QIcon()
self.windowIcon = QIcon()
# Setting the icons image, using found paths.
self.alertIcon.addFile(self.alert_icon)
self.windowIcon.addFile(self.window_icon)
def build_gui(self):
"""Generates the GUI elements, and hooks everything up."""
# Removes anim from combobox opening
QApplication.setEffectEnabled(Qt.UI_AnimateCombo, False)
# Sorts the parameters, so that favorite ones are added to the favorite widget.
favorites = {i: self.settings[i] for i in self.settings.get_favorites()}
options = {k: v for k, v in self.settings.parameters.items() if k not in favorites}
# Create top level tab widget system for the UI
self.tab_widget = QTabWidget(self)
# Close signal
self.onclose.connect(self.confirm)
# Confirmation to close signal
self.sendClose.connect(self.closeE)
# First Tab | Main tab
self.tab1 = MainTab(self.settings, self.tab_widget)
self.tab1.start_btn.clicked.connect(self.queue_download)
# Stop button stops downloads, and may clear queue.
self.tab1.stop_btn.clicked.connect(self.stop_download)
self.tab1.close_btn.clicked.connect(self.close)
# Perform check if enough is present to start a download after user actions
self.tab1.checkbox.stateChanged.connect(self.allow_start)
self.tab1.url_input.textChanged.connect(self.allow_start)
# Queue downloading
self.tab1.url_input.returnPressed.connect(self.tab1.start_btn.click)
# Change profile
self.tab1.profile_dropdown.currentTextChanged.connect(self.load_profile)
# Delete profile
self.tab1.profile_dropdown.deleteItem.connect(self.delete_profile)
# Tab 2 | Parameter Tab
self.tab2 = ParameterTab(options, favorites, self.settings, self)
# Connecting tab 2.
self.tab2.open_folder_action.triggered.connect(self.open_folder)
self.tab2.copy_action.triggered.connect(self.copy_to_cliboard)
self.tab2.options.itemChanged.connect(self.parameter_updater)
self.tab2.options.move_request.connect(self.move_item)
self.tab2.options.itemRemoved.connect(self.item_removed)
self.tab2.options.addOption.connect(self.add_option)
self.tab2.favorites.itemChanged.connect(self.parameter_updater)
self.tab2.favorites.move_request.connect(self.move_item)
self.tab2.favorites.itemRemoved.connect(self.item_removed)
self.tab2.favorites.addOption.connect(self.add_option)
self.tab2.browse_btn.clicked.connect(self.savefile_dialog)
self.tab2.save_profile_btn.clicked.connect(self.save_profile)
# Tab 3 | Basic text editor
self.tab3 = TextTab(parent=self)
# When loadbutton is clicked, launch load textfile.
self.tab3.loadButton.clicked.connect(self.load_text_from_file)
# When savebutton clicked, save text to file.
self.tab3.saveButton.clicked.connect(self.save_text_to_file)
# Tab 4
# Button to browse for .txt file to download files.
self.tab4 = AboutTab(self.settings, parent=self)
# Connect buttons to functions
self.tab4.update_btn.clicked.connect(self.update_youtube_dl)
self.tab4.dirinfo_btn.clicked.connect(self.dir_info)
self.tab4.reset_btn.clicked.connect(self.reset_settings)
self.tab4.location_btn.clicked.connect(self.textfile_dialog)
self.tab4.debug_info.clicked.connect(self.toggle_debug)
self.tab4.dl_mode_btn.clicked.connect(self.toggle_modes)
# Future tab creation here! Currently 4 tabs
# TODO: Move stylesheet applying to method, make color picking dialog to customize in realtime
# Windows specific, only triggered in settings manually
if self.settings.user_options['use_win_accent']:
try:
color = get_win_accent_color()
bg_color = f"""
QMainWindow {{
background-color: {color};
}}
QTabBar {{
background-color: {color};
}}"""
except (OSError, PermissionError):
bg_color = ''
else:
bg_color = ''
self.style_with_options = bg_color + f"""
QCheckBox::indicator:unchecked {{
image: url({self.unchecked_icon});
}}
QCheckBox::indicator:checked {{
image: url({self.checked_icon});
}}
QComboBox::down-arrow {{
border-image: url({self.down_arrow_icon});
height: {self.tab1.profile_dropdown.iconSize().height()}px;
width: {self.tab1.profile_dropdown.iconSize().width()}px;
}}
QComboBox::down-arrow::on {{
image: url({self.down_arrow_icon_clicked});
height: {self.tab1.profile_dropdown.iconSize().height()}px;
width: {self.tab1.profile_dropdown.iconSize().width()}px;
}}
QTreeWidget::indicator:checked {{
image: url({self.checked_icon});
}}
QTreeWidget::indicator:unchecked {{
image: url({self.unchecked_icon});
}}"""
if not self.settings.user_options['show_collapse_arrows']:
self.style_with_options += """
QTreeWidget::branch {{
image: none;
border-image: none;
}}
QTreeWidget::branch:has-siblings:!adjoins-item {{
image: none;
border-image: none;
}}
QTreeWidget::branch:has-siblings:adjoins-item {{
border-image: none;
image: none;
}}
QTreeWidget::branch:!has-children:!has-siblings:adjoins-item {{
border-image: none;
image: none;
}}
"""
# Adds tabs to the tab widget
self.tab_widget.addTab(self.tab1, 'Main')
self.tab_widget.addTab(self.tab2, 'Param')
self.tab_widget.addTab(self.tab3, 'List')
self.tab_widget.addTab(self.tab4, 'About')
# Sets the styling for GUI
self.setStyleSheet(get_stylesheet() + self.style_with_options)
self.setWindowTitle('Grabber')
self.setWindowIcon(self.windowIcon)
# Set base size.
self.setMinimumWidth(340)
self.setMinimumHeight(400)
# Selects the text in the URL box when focus is gained
if self.settings.user_options['select_on_focus']:
self.gotfocus.connect(self.window_focus_event)
else:
self.tab1.url_input.setFocus()
# Check for youtube
if self.youtube_dl_path is None:
self.tab4.update_btn.setDisabled(True)
self.alert_message('Warning!', '\nNo youtube-dl.exe found! Add to path, '
'or make sure it\'s in the same folder as this program. '
'Then close and reopen this program.', '')
# Sets the download items tooltips to the full file path.
self.download_name_handler()
# Ensures widets are in correct state at startup and when tab1.lineedit is changed.
self.allow_start()
# Shows the main window.
self.setCentralWidget(self.tab_widget)
self.show()
# Below NEEDS to connect after show!!
# Ensures size of parameter tab is right
self.resizedByUser.connect(self.resize_contents)
# Called after show, to ensure base size is consistent.
self.tab2.enable_favorites(bool(favorites))
# State changed
self.downloader.stateChanged.connect(self.allow_start)
self.tab_widget.currentChanged.connect(self.resize_contents)
def toggle_debug(self):
""" Can be triggered to enable/disable debugging information """
self._debug = not self._debug
self.tab4.debug_info.setText(f'Debug:\n{self._debug}')
for i in self.tab1.process_list.iter_items():
i.toggle_debug(self._debug)
def toggle_modes(self):
""" Swap between parallel and sequential download mode. """
if self.downloader.RUNNING or self.downloader.has_pending():
self.alert_message('Action failed',
'Mode was not changed',
"Unable to toggle between download mode with active downloads!")
return
else:
parallel = not self.settings.user_options['parallel']
self.settings.user_options['parallel'] = parallel
self.tab4.dl_mode_btn.setText(("Singular" if not parallel else "Parallel") + '\nDownloads')
self.downloader.set_mode(parallel=parallel)
def save_profile(self):
""" Save parameter config to a profile. """
dialog = Dialog(self.tab_widget, 'Name profile', 'Give a name to the profile!')
if dialog.exec() != QDialog.Accepted:
return
elif dialog.option.text() in ('Custom', 'None'):
self.alert_message('Error', 'This profile name is not allowed!', '')
profile_name = dialog.option.text()
if profile_name in self.settings.profiles:
result = self.alert_message('Overwrite profile?',
f'Do you want to overwrite profile:',
f'{profile_name}'.center(45),
True)
if result != QMessageBox.Yes:
return
self.tab1.profile_dropdown.blockSignals(True)
self.tab1.profile_dropdown.setDisabled(False)
if self.tab1.profile_dropdown.findText(profile_name) == -1:
self.tab1.profile_dropdown.addItem(profile_name)
self.tab1.profile_dropdown.setCurrentText(profile_name)
self.tab1.profile_dropdown.removeItem(self.tab1.profile_dropdown.findText('None'))
self.tab1.profile_dropdown.removeItem(self.tab1.profile_dropdown.findText('Custom'))
self.tab1.profile_dropdown.blockSignals(False)
self.settings.create_profile(profile_name)
self.file_handler.save_settings(self.settings.settings_data)
self.file_handler.save_profiles(self.settings.profiles_data)
def load_profile(self):
""" Loads a profile and sets the GUI to that configuration """
try:
profile_name = self.tab1.profile_dropdown.currentText()
if profile_name in ('None', 'Custom'):
return
success = self.settings.change_profile(profile_name)
if not success:
self.alert_message('Error',
'Failed to find profile',
f'The profile "{profile_name}" was not found!')
return
favorites = {i: self.settings[i] for i in self.settings.get_favorites()}
options = {k: v for k, v in self.settings.parameters.items() if k not in favorites}
self.tab2.options.load_profile(options)
self.tab2.favorites.load_profile(favorites)
self.tab2.find_download_widget()
self.download_name_handler()
self.tab1.profile_dropdown.blockSignals(True)
self.tab1.profile_dropdown.removeItem(self.tab1.profile_dropdown.findText('None'))
self.tab1.profile_dropdown.removeItem(self.tab1.profile_dropdown.findText('Custom'))
self.tab1.profile_dropdown.blockSignals(False)
self.file_handler.save_settings(self.settings.settings_data)
except Exception as e:
# TODO: Replace this with logging
import traceback
traceback.print_exc()
def delete_profile(self):
""" Removes a profile """
index = self.tab1.profile_dropdown.currentIndex()
text = self.tab1.profile_dropdown.currentText()
if text in ('Custom', 'None'):
return
self.settings.delete_profile(text)
self.tab1.profile_dropdown.blockSignals(True)
self.tab1.profile_dropdown.removeItem(index)
self.tab1.profile_dropdown.addItem('Custom')
self.tab1.profile_dropdown.setCurrentText('Custom')
self.tab1.profile_dropdown.blockSignals(False)
self.file_handler.save_settings(self.settings.settings_data)
def item_removed(self, item: QTreeWidgetItem, index):
"""
Parent who had child removed. Updates settings and numbering of settings_data 35
TODO: Apply named constant variables to data entries instead of numbers.
Constants defined in parameter_tree.py
"""
def get_index(data, option_name):
try:
return data[parameter_name]['options'].index(option_name)
except KeyError:
# TODO: Logging
# print(f'Profile {profile} has no parameter {parameter_name}, skipping')
return None
except ValueError:
# print(f'Profile {profile} does not have the option {option_name}, skipping')
return None
parameter_name = item.data(0, DISPLAY_NAME_SLOT)
option_name = self.settings.parameters[parameter_name]['options'][index]
has_option = []
for profile, data in self.settings.profiles_data.items():
new_index = get_index(data, option_name)
if new_index is not None and data[parameter_name]['active option'] == new_index:
has_option.append(profile)
if has_option:
self.alert_message('Error',
f'One or more profiles has this as the selected option:',
f'\t{", ".join(has_option)}')
return
item.treeWidget().del_option(item, item.child(index))
self.settings.remove_parameter_option(item.data(0, DISPLAY_NAME_SLOT), index)
# Deletes from profiles
for profile, data in self.settings.profiles_data.items():
new_index = get_index(data, option_name)
if new_index is None:
continue
del data[parameter_name]['options'][new_index]
new_index = data[parameter_name]['active option']
new_index -= 1 if new_index > 0 else 0
data[parameter_name]['active option'] = new_index
self.file_handler.save_profiles(self.settings.profiles_data)
self.file_handler.save_settings(self.settings.settings_data)
def design_option_dialog(self, name, description):
"""
Creates dialog for user input
# TODO: Use this method where possible
"""
dialog = Dialog(self.tab_widget, name, description)
if dialog.exec_() == QDialog.Accepted:
return dialog.option.text()
return None
def add_option(self, item: QTreeWidgetItem):
"""
Check if parameter has a possible option parameter, and lets the user add on if one exist.
"""
if item.data(0, DATA_SLOT) == 'Download location':
self.alert_message('Error!', 'Please use the browse button\nto select download location!', None)
return
if item.data(0, LEVEL_SLOT) == 2:
self.alert_message('Error!', 'Custom option does not take a command!', None)
return
# TODO: Standardise setting an parameter to checked, and updating to expanded state.
elif '{}' in self.settings[item.data(0, DATA_SLOT)]['command']:
item.treeWidget().blockSignals(True)
option = self.design_option_dialog(item.text(0), item.toolTip(0))
if option:
if option in self.settings[item.data(0, DATA_SLOT)]['options']:
self.alert_message('Error', 'That option already exists!', '')
item.treeWidget().blockSignals(False)
return True
new_option = ParameterTree.make_option(option.strip(),
item,
True,
1,
None,
None,
0)
move = item.takeChild(item.indexOfChild(new_option))
item.insertChild(0, move)
self.settings.add_parameter_option(item.data(0, DATA_SLOT), option)
for i in range(len(self.settings[item.data(0, DATA_SLOT)]['options'])):
child = item.child(i)
child.setData(0, INDEX_SLOT, i)
if i == 0:
child.setCheckState(0, Qt.Checked)
child.setFlags(child.flags() ^ Qt.ItemIsUserCheckable)
else:
child.setCheckState(0, Qt.Unchecked)
child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(0, Qt.Checked)
item.setExpanded(True)
item.treeWidget().update_size()
try:
self.settings.need_parameters.remove(item.data(0, DATA_SLOT))
except ValueError:
pass
self.file_handler.save_settings(self.settings.settings_data)
item.treeWidget().blockSignals(False)
return True
else:
item.treeWidget().blockSignals(False)
return False
else:
self.alert_message('Error!', 'The specified option does not take arguments!', None)
return False
# print('Doesn\'t have an option')
def move_item(self, item: QTreeWidgetItem, favorite: bool):
""" Move an time to or from the favorites tree. """
if favorite:
tree = self.tab2.options
self.settings.user_options['favorites'].remove(item.data(0, DISPLAY_NAME_SLOT))
else:
tree = self.tab2.favorites
self.settings.user_options['favorites'].append(item.data(0, DISPLAY_NAME_SLOT))
self.tab2.enable_favorites(bool(self.settings.user_options['favorites']))
tree.blockSignals(True)
tree.addTopLevelItem(item)
self.tab2.options.update_size()
self.tab2.favorites.update_size()
self.file_handler.save_settings(self.settings.settings_data)
if item.checkState(0) == Qt.Checked:
item.setExpanded(True)
else:
item.setExpanded(False)
tree.blockSignals(False)
def resize_contents(self):
""" Resized parameterTree widgets in tab2 to the window."""
if self.tab_widget.currentIndex() == 0:
self.tab1.process_list.setMinimumWidth(self.window().width() - 18)
elif self.tab_widget.currentIndex() == 1:
size = self.height() - (self.tab2.opt_frame2.height() + self.tab2.download_lineedit.height()
+ self.tab2.optlabel.height() + self.tab_widget.tabBar().height() + 40)
ParameterTree.max_size = size
self.tab2.options.setFixedHeight(size)
self.tab2.favorites.setFixedHeight(size)
def window_focus_event(self):
""" Selects text in tab1 line edit on window focus. """
# self.tab2.options.max_size =
if self.tab1.url_input.isEnabled():
self.tab1.url_input.setFocus()
self.tab1.url_input.selectAll()
def copy_to_cliboard(self):
""" Adds text to clipboard. """
if self.settings.is_activate('Download location'):
text = self.settings.get_active_setting('Download location')
else:
text = self.local_dl_path
to_clipboard(text)
def open_folder(self):
""" Opens a folder at specified location. """
# noinspection PyCallByClass
QProcess.startDetached('explorer {}'.format(self.tab2.download_lineedit.toolTip().replace("/", "\\")))
def download_name_handler(self):
""" Formats download names and removes the naming string for ytdl. """
item = self.tab2.download_option
item.treeWidget().blockSignals(True)
for number in range(item.childCount()):
path = self.settings['Download location']['options'][number]
item.child(number).setToolTip(0, path)
item.child(number).setText(0, path_shortener(path))
if item.checkState(0) == Qt.Checked:
for number in range(item.childCount()):
if item.child(number).checkState(0) == Qt.Checked:
self.tab2.download_lineedit.setText(item.child(number).data(0, DISPLAY_NAME_SLOT))
self.tab2.download_lineedit.setToolTip(item.child(number).data(0, DATA_SLOT))
break
else:
# TODO: Add error handling here
print('WARNING! No selected download item, this should not happen.... ')
print('You messed with the settings... didn\'t you?!')
# raise SettingsError('Error, no active option!')
else:
self.tab2.download_lineedit.setText(path_shortener(self.local_dl_path))
self.tab2.download_lineedit.setToolTip(self.local_dl_path)
item.treeWidget().blockSignals(False)
def download_option_handler(self, full_path: str):
""" Handles the download options. """
# Adds new dl location to the tree and settings. Removes oldest one, if there is more than 3.
# Remove try/except later.
item = self.tab2.download_option
if not full_path.endswith('/'):
full_path += '/'
short_path = path_shortener(full_path)
names = [item.child(i).data(0, DISPLAY_NAME_SLOT) for i in range(item.childCount())]
if short_path in names and full_path in self.settings['Download location']['options']:
self.alert_message('Warning', 'Option already exists!', '', question=False)
return
item.treeWidget().blockSignals(True)
sub = ParameterTree.make_option(name=full_path,
parent=item,
checkstate=False,
level=1,
tooltip=full_path,
dependency=None,
subindex=None)
sub.setData(0, DISPLAY_NAME_SLOT, short_path)
# print('sorting enabled?', item.treeWidget().isSortingEnabled())
# Take item from one tree and insert in another.
moving_sub = item.takeChild(item.indexOfChild(sub))
item.insertChild(0, moving_sub)
# Renumber the items, to give then the right index.
for number in range(item.childCount()):
item.child(number).setData(0, INDEX_SLOT, number)
if self.settings['Download location']['options'] is None:
self.settings['Download location']['options'] = [full_path]
else:
self.settings.add_parameter_option('Download location', full_path)
item.treeWidget().update_size()
item.treeWidget().setSortingEnabled(True)
item.treeWidget().blockSignals(False)
# self.tab2.download_lineedit.setText(location)
# self.tab2.download_lineedit.setToolTip(tooltip)
try:
self.settings.need_parameters.remove(item.data(0, DATA_SLOT))
except ValueError:
pass
item.setCheckState(0, Qt.Checked)
sub.setCheckState(0, Qt.Checked)
self.file_handler.save_settings(self.settings.settings_data)
# TODO: Show queue option
def reset_settings(self):
result = self.alert_message('Warning!',
'Restart required!',
'To reset the settings, '
'the program has to be restarted. '
'Do you want to reset and restart?',
question=True)
if result == QMessageBox.Yes:
self.settings = self.file_handler.load_settings(reset=True)
qApp.exit(GUI.EXIT_CODE_REBOOT)
def parameter_updater(self, item: QTreeWidgetItem, col=None, save=True):
"""Handles updating the options for a parameter."""
if 'Custom' != self.tab1.profile_dropdown.currentText():
self.tab1.profile_dropdown.addItem('Custom')
self.tab1.profile_dropdown.setCurrentText('Custom')
self.settings.user_options['current_profile'] = ''
if item.data(0, LEVEL_SLOT) == 0:
if item.data(0, DATA_SLOT) in self.settings.need_parameters:
result = self.alert_message('Warning!', 'This parameter needs an option!', 'There are no options!\n'
'Would you make one?', True)
if result == QMessageBox.Yes:
success = self.add_option(item)
if not success:
item.treeWidget().blockSignals(True)
item.setCheckState(0, Qt.Unchecked)
item.treeWidget().blockSignals(False)
item.treeWidget().check_dependency(item)
else:
item.treeWidget().blockSignals(True)
item.setCheckState(0, Qt.Unchecked)
item.treeWidget().blockSignals(False)
item.treeWidget().check_dependency(item)
if item.checkState(0) == Qt.Checked:
self.settings[item.data(0, DATA_SLOT)]['state'] = True
if item.data(0, DATA_SLOT) == 'Download location':
for i in range(item.childCount()):
self.parameter_updater(item.child(i), save=False)
else:
self.settings[item.data(0, DATA_SLOT)]['state'] = False
if item.data(0, DATA_SLOT) == 'Download location':
self.tab2.download_lineedit.setText(path_shortener(self.local_dl_path))
self.tab2.download_lineedit.setToolTip(self.local_dl_path)
elif item.data(0, LEVEL_SLOT) == 1:
# Settings['Settings'][Name of setting]['active option']] = index of child
self.settings[item.parent().data(0, DATA_SLOT)]['active option'] = item.data(0, INDEX_SLOT)
if item.parent().data(0, DATA_SLOT) == 'Download location':
if item.checkState(0) == Qt.Checked:
self.tab2.download_lineedit.setText(item.data(0, DISPLAY_NAME_SLOT))
self.tab2.download_lineedit.setToolTip(item.data(0, DATA_SLOT))
if save:
self.file_handler.save_settings(self.settings.settings_data)
def dir_info(self):
# TODO: Print this info to GUI.
file_dir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/')
debug = [color_text('Youtube-dl.exe path: ') + str(self.youtube_dl_path),
color_text('ffmpeg.exe path: ') + str(self.ffmpeg_path),
color_text('Filedir: ') + str(file_dir),
color_text('Workdir: ') + str(self.file_handler.work_dir),
color_text('Youtube-dl working directory: ') + str(self.program_workdir)]
debug += [color_text('\nIcon paths:'), *self.icon_list]
debug += [color_text('\nChecking if icons are in place:', 'darkorange', 'bold')]
for i in self.icon_list:
if i is not None:
if self.file_handler.is_file(str(i)):
try:
debug.append(f'Found: {os.path.split(i)[1]}')
except IndexError:
debug.append(f'Found: {i}')
if self.icon_list.count(None):
debug.append(color_text(f'Missing {self.icon_list.count(None)} icon file(s)!'))
# RichText does not support both the use of \n and <br> at the same time. Use <br>
debug_info = '<br>'.join([text.replace('\n', '<br>') for text in debug if text is not None])
mock_download = MockDownload(info=debug_info)
self.add_download_to_gui(mock_download)
self.tab_widget.setCurrentIndex(0)
def update_youtube_dl(self):
# TODO: Require no other downloads active
update = Download(self.program_workdir,
self.youtube_dl_path,
['-U', '--encoding', 'utf-8'],
info='Youtube-dl update',
parent=self)
self.tab_widget.setCurrentIndex(0) # Go to main
self.add_download_to_gui(update)
self.downloader.queue_dl(update)
def savefile_dialog(self):
location = QFileDialog.getExistingDirectory(parent=self.tab_widget)
if location == '':
pass
elif os.path.exists(location):
self.download_option_handler(location)
else:
self.alert_message('Error', 'Could not find the specified folder.'
'\nReport this on githib if it keeps happening.')
def textfile_dialog(self):
location = \
QFileDialog.getOpenFileName(parent=self.tab_widget, filter='*.txt',
caption='Select textfile with video links')[0]
if location == '':
pass
elif self.file_handler.is_file(location):
if not self.tab3.SAVED:
result = self.alert_message('Warning!',
'Selecting new textfile,'
' this will load over the text in the download list tab!',
'Do you want to load over the unsaved changes?',
question=True)
if result == QMessageBox.Yes:
self.settings.user_options['multidl_txt'] = location
self.tab4.textfile_url.setText(location)
self.tab3.SAVED = True
self.load_text_from_file()
self.file_handler.save_settings(self.settings.settings_data)
else:
self.settings.user_options['multidl_txt'] = location
self.tab4.textfile_url.setText(location)
self.tab3.SAVED = True
self.load_text_from_file()
self.file_handler.save_settings(self.settings.settings_data)
else:
self.alert_message('Error!', 'Could not find file!', '')
# Check if the checkbox is toggled, and disables the line edit if it is.
# Also disables start button if lineEdit is empty and checkbox is not checked
def queue_download(self):
command = []
if self.tab1.checkbox.isChecked():
txt = self.settings.user_options['multidl_txt']
url = None
if not txt:
self.alert_message('Error!', 'No textfile selected!', '')
return
command += ['-a', f'{txt}']
else:
txt = self.tab1.url_input.text()
url = txt
command.append(f'{txt}')
# for i in range(len(command)):
# command[i] = command[i].format(txt=txt)'
# TODO: Let user pick naming format
file_name_format = '%(title)s.%(ext)s'
for parameter, options in self.settings.parameters.items():
if parameter == 'Download location':
if options['state']:
add = format_in_list(options['command'],
self.settings.get_active_setting(parameter) + file_name_format)
command += add
else:
command += ['-o', self.local_dl_path + file_name_format]
elif parameter == 'Keep archive':
if options['state']:
add = format_in_list(options['command'],
os.path.join(os.getcwd(), self.settings.get_active_setting(parameter)))
command += add
elif parameter == 'Username':
if options['state']:
option = self.settings.get_active_setting(parameter)
if hash(option) in self._temp:
_password = self._temp[hash(option)]
else:
dialog = Dialog(self,
'Password',
f'Input you password for the account "{option}".',
allow_empty=True,
password=True)
if dialog.exec_() == QDialog.Accepted:
self._temp[hash(option)] = _password = dialog.option.text()
else:
self.alert_message('Error', color_text('ERROR: No password was entered.', sections=(0, 6)),
'')
return
add = format_in_list(options['command'], option)
add += ['--password', _password]
command += add
else:
if options['state']:
option = self.settings.get_active_setting(parameter)
add = format_in_list(options['command'], option)
command += add
# Sets encoding to utf-8, allowing better character support in output stream.
command += ['--encoding', 'utf-8']
if self.ffmpeg_path is not None:
command += ['--ffmpeg-location', self.ffmpeg_path]
download = Download(self.program_workdir, self.youtube_dl_path, command, parent=self)
self.add_download_to_gui(download, url=url)
self.downloader.queue_dl(download)
def add_download_to_gui(self, download, url=None):
scrollbar = self.tab1.process_list.verticalScrollBar()
place = scrollbar.sliderPosition()
go_bottom = (place == scrollbar.maximum())
slot = QListWidgetItem(parent=self.tab1.process_list)
gui_progress = ProcessListItem(download, slot, debug=self._debug, url=url)
self.tab1.process_list.addItem(slot)
self.tab1.process_list.setItemWidget(slot, gui_progress)
gui_progress.adjust()
self.tab1.process_list.resize(self.tab1.process_list.size())
if go_bottom:
self.tab1.process_list.scrollToBottom()
gui_progress.stat_update()
def stop_download(self):
parallel = self.settings.user_options['parallel']
if parallel and self.downloader.many_active():
result = self.alert_message('Stop all?',
'Parallel mode stops all pending and active donwloads!',
'Do you want to continue?', True, True)
if result == QMessageBox.Yes:
self.downloader.stop_download(True)
elif parallel:
self.downloader.stop_download()
elif self.downloader.has_pending():
result = self.alert_message('Stop all?', 'Stop all pending downloads too?', '', True, True)
if result == QMessageBox.Cancel:
return
else:
self.downloader.stop_download(all_dls=(result == QMessageBox.Yes))
else:
self.downloader.stop_download()
for item in self.tab1.process_list.iter_items():
item.is_running()
def allow_start(self):
""" Adjusts buttons depending on users input and program state """
self.tab1.stop_btn.setDisabled(not self.downloader.RUNNING)
self.tab1.url_input.setDisabled(self.tab1.checkbox.isChecked())
if not self.tab1.timer.isActive():
self.tab1.start_btn.setDisabled(self.tab1.url_input.text() == '' and not self.tab1.checkbox.isChecked())
# TODO: Move to tab 3?
def load_text_from_file(self):
if self.tab3.SAVED:
content = self.file_handler.read_textfile(self.settings.user_options['multidl_txt'])
if content is not None:
self.tab3.textedit.clear()
for line in content.split():
self.tab3.textedit.append(line.strip())
self.tab3.textedit.append('')
self.tab3.textedit.setFocus()
self.tab3.saveButton.setDisabled(True)
self.tab3.SAVED = True
else:
if self.settings.user_options['multidl_txt']:
warning = 'No textfile selected!\nBrowse for one in the About tab.'
else:
warning = 'Could not find/load file!'
self.alert_message('Error!', warning, '')
else:
result = self.alert_message('Warning',
'Overwrite?',
'Do you want to load over the unsaved changes?',
question=True)
if result == QMessageBox.Yes:
self.tab3.SAVED = True
self.load_text_from_file()
def save_text_to_file(self):
# TODO: Implement Ctrl+L for loading of files.
if self.settings.user_options['multidl_txt']:
self.file_handler.write_textfile(self.settings.user_options['multidl_txt'],
self.tab3.textedit.toPlainText())
self.tab3.saveButton.setDisabled(True)
self.tab3.SAVED = True
else:
result = self.alert_message('Warning!',
'No textfile selected!',
'Do you want to create one?',
question=True)
if result == QMessageBox.Yes:
save_path = QFileDialog.getSaveFileName(parent=self.tab_widget, caption='Save as', filter='*.txt')
if save_path[0]:
self.file_handler.write_textfile(save_path[0],
self.tab3.textedit.toPlainText())
self.settings.user_options['multidl_txt'] = save_path[0]
self.file_handler.save_settings(self.settings.settings_data)
self.tab4.textfile_url.setText(self.settings.user_options['multidl_txt'])
self.tab3.saveButton.setDisabled(True)
self.tab3.SAVED = True
def alert_message(self, title, text, info_text, question=False, allow_cancel=False):
""" A quick dialog for providing warnings or asking for user questions."""
warning_window = QMessageBox(parent=self)
warning_window.setText(text)
warning_window.setIcon(QMessageBox.Warning)
warning_window.setWindowTitle(title)