-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLazy_Selector.py
2327 lines (2019 loc) · 94.1 KB
/
Lazy_Selector.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
""" Lazy Selector app """
__VERSION__ = "5.0.0"
# Run all_songs shuffle and sort in background
# from profiler import profile_function
import vlcmixer as mixer
from streams.search import YTSearch
from streams.YT import (
get_sanitizedinfo,
get_video_streams,
get_audio_streams,
get_url_details,
get_play_stream,
)
from streams.downloader import (
ADownloader,
Task,
)
from streams.utils import (
prevent_sleep,
allow_sleep,
file_details,
safe_delete,
strfdelta,
is_url,
r_path,
)
from core import (
EXTS,
BASE_DIR,
scroll_widget,
)
from concurrent.futures import ThreadPoolExecutor
from socket import gethostname, gethostbyname
from multiprocessing import Manager, freeze_support, Lock
from multiprocessing.managers import (
SyncManager,
)
from stat import S_IREAD, S_IWUSR
from plyer import battery, notification
import logging
import sys
import os
import orjson
from send2trash import send2trash
# from random import shuffle
import images
from time import sleep, time
from datetime import timedelta
from tkinter import (
Tk, Frame, Label,
Button,
PhotoImage,
Menu, DoubleVar,
Listbox, Entry,
Scrollbar, Toplevel,
Canvas,
BooleanVar
)
from tkinter.ttk import Scale, Notebook, Style
from ttkthemes import ThemedStyle
try:
from idlelib.tooltip import ToolTip
# for python greater than 3.7
except ImportError:
from idlelib.tooltip import Hovertip as ToolTip
from dialogs import (
DetailsPopup,
showinfo, okcancel,
getquality,
)
from tkinter.filedialog import (
askopenfilenames, askdirectory
)
from storage import (
AppConfigs,
DCache,
atime_sortkey,
)
from webbrowser import open as open_tab
logging.basicConfig(
filename="errors.log",
filemode="w",
level=logging.ERROR,
encoding="utf-8",
)
logger = logging.getLogger(__name__)
DATA_DIR = r_path("data", base_dir=BASE_DIR)
CACHE_DIR = os.path.join(DATA_DIR, "appcache")
QUEUE_FILE = os.path.join(CACHE_DIR, "queue.json")
EXIFTOOL_PATH = os.path.join(r_path("exiftool", base_dir=BASE_DIR), "exiftool.exe")
CURRENT_PID = os.getpid()
QUEUE_LOCK = Lock()
def handle_yt_errors(error) -> str:
""" return a friendly string for error """
return "An error has occured while fetching info..."
def get_q(filename) -> list:
""" get files written to this file """
with open(filename, "rb") as q_file:
data = orjson.loads(q_file.read())
if data:
set_q(QUEUE_FILE, [])
return data
def set_q(filename, data: list):
""" write data to json """
# synchronize with lock
QUEUE_LOCK.acquire()
with open(filename, "wb") as q_file:
serialized = orjson.dumps(
data,
option=orjson.OPT_INDENT_2
)
q_file.write(serialized)
# release write lock
QUEUE_LOCK.release()
class Options():
__slots__ = ()
# in seconds
TIMEOUT = 120
LISTBOX_OPTIONS = {"bg": "white smoke", "fg": "black", "width": 42,
"selectbackground": "DeepSkyBlue3", "selectforeground": "white",
"height": 43, "relief": "flat",
"font": ("New Times Roman", 9), "highlightthickness": 0}
SCALE_OPTIONS = {"from_": 0, "orient": "horizontal", "length": 225, "cursor": "hand2"}
FILENAMES_INITIALDIR = os.path.expanduser("~\\Music")
ALT_DIRS = {FILENAMES_INITIALDIR, }
class Player(Options):
"""
Plays audio and video files in
win is tkinter's toplevel widget Tk
"""
_CONFIG = AppConfigs(os.path.join(DATA_DIR, "lazylog.cfg"))
BG = _CONFIG.get_inner("theme", "bg")
FG = _CONFIG.get_inner("theme", "fg")
# @profile_function
def __init__(self, win, shared_dict: SyncManager.dict):
self._root = win
self.shared_dict = shared_dict
self._root.resizable(0, 0)
self._root.config(bg=Player.BG)
self._root.title("Lazy Selector")
self._root.tk_focusFollowsMouse()
self._root.wm_protocol("WM_DELETE_WINDOW", self._kill)
self.uptime_loopid = self._root.after(1000, self._set_uptime)
# use png image for icon
self._root.wm_iconphoto(1, PhotoImage(data=images.APP_IMG))
# for screens with high DPI minus 102
self._screen_height = self._root.winfo_screenheight() - 104 if self._root.winfo_screenheight() >= 900 else self._root.winfo_screenheight() - 84
self.shuffle_mixer = mixer.VLC()
self.video_search = YTSearch()
self._progress_variable = DoubleVar()
self.mute_variable = BooleanVar()
self.loopone_variable = BooleanVar()
# get last window position
position = Player._CONFIG.get_inner("window", "position")
# get last search
self.search_str = Player._CONFIG.get_inner("searches", "last")
# get search history
self._search_history = set(Player._CONFIG.get_inner("searches", "all"))
self._root.geometry("318x118+" + position)
self.progressbar_style = ThemedStyle()
self.progressbar_style.theme_use("equilux")
self.progressbar_style.configure("custom.Horizontal.TScale", background=Player.BG)
self.progressbar_style.configure("TButton", foreground="gray97", focuscolor="gray97")
self.progressbar_style.configure("TCombobox", foreground="gray97")
self.threadpool = ThreadPoolExecutor(max_workers=20)
# create cache
self.file_cache = DCache(CACHE_DIR)
self._all_files = []
self.collected = []
self.index = -1
self.collection_index = -1
self.stream_index = -1
self._uptime = 0
self.tab_num = 0
self.isStreaming = 0
self.change_stream = 1
self._title_link = None
# let duration be greater than 0; prevent slider being at the end on startup
self.duration = 60
self._song = ""
self._title_txt = ""
self.ftime = "00:00"
self._play_btn_command = None
self._play_prev_command = None
self._play_next_command = None
self.list_frame = None
self.listbox = None
self.controls_frame = None
self.main_frame = None
self.done_frame = None
self.top = None
self._slider_above = 0
self._playing = 0
self.lowbatt_notified = 0
self.reset_preferences = 0
self._supported_extensions = tuple(EXTS)
# value to let refresher open dir chooser; otherwise use previous
self._open_folder = 0
self.previous_img = PhotoImage(data=images.PREVIOUS_IMG)
self.play_img = PhotoImage(data=images.PLAY_IMG)
self.pause_img = PhotoImage(data=images.PAUSE_IMG)
self.next_img = PhotoImage(data=images.NEXT_IMG)
self.lpo_image = PhotoImage(data=images.LDARKPOINTER_IMG)
self.play_btn_img = self.play_img
if Player.BG == "gray97":
self.more_image = PhotoImage(data=images.MORE_IMG)
self.rpo_image = PhotoImage(data=images.POINTER_IMG)
else:
self.more_image = PhotoImage(data=images.DARKMORE_IMG)
self.rpo_image = PhotoImage(data=images.DARKPOINTER_IMG)
self.menubar = Menu(self._root)
self._root.config(menu=self.menubar)
self.file_menu = Menu(self.menubar, tearoff=0,
fg=Player.FG, bg=Player.BG)
self.menubar.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="Open Folder",
command=self._manual_add)
self.file_menu.add_separator()
self.file_menu.add_command(label="Add to Queue",
command=self._select_fav)
self.theme_menu = Menu(self.menubar, tearoff=0,
fg=Player.FG, bg=Player.BG)
self.menubar.add_cascade(label="Theme", menu=self.theme_menu)
self.theme_menu.add_command(label="Light",
command=lambda: self._update_color("gray97", "black"))
self.theme_menu.add_separator()
self.theme_menu.add_command(label="Dark",
command=lambda: self._update_color("gray28", "gray97"))
self.about_menu = Menu(self.menubar, tearoff=0, selectcolor=Player.FG,
fg=Player.FG, bg=Player.BG)
self.menubar.add_cascade(label="Help", menu=self.about_menu)
self.about_menu.add_command(label="Switch Slider", command=self._change_place)
self.about_menu.add_separator()
self.about_menu.add_checkbutton(label="Reset preferences", command=self._remove_pref)
self.about_menu.add_separator()
self.about_menu.add_command(label="About Lazy Selector", command=self._about)
file_passed = self._refresher()
self._init()
if file_passed:
self.on_eos()
rem_battery = battery.get_state()["percentage"]
if (rem_battery < 41) and (rem_battery > 16):
notification.notify(
title="Lazy Selector",
message=f'{rem_battery}% Charge Available',
app_name="Lazy Selector",
app_icon=f"{DATA_DIR}\\app.ico" if os.path.exists(f"{DATA_DIR}\\app.ico") else None
)
# ------------------------------------------------------------------------------------------------------------------------------
def send_event(
self, funcname: str,
*args,
**kwargs
):
"""
put funcname, args, and kwargs as a `Task` in shared_dict
for the downloader to pick
"""
msg = Task(funcname, args, kwargs)
self.shared_dict["task"] = msg
while True:
rtv = self.shared_dict.pop(funcname, "00")
if rtv != "00":
return rtv
sleep(0.01)
def update_downloader_progress(self):
""" get and update downloader progress from downloader """
progress_txt = self.shared_dict.pop("progress", None)
if progress_txt: # not None or empty str
try:
self.status_bar.configure(text=progress_txt)
except Exception: # when statusbar is destroyed
pass
# repeat infinitely until cancelled
self.progress_loopid = self.status_bar.after(
700, self.update_downloader_progress
)
def cancel_afters(self):
""" cancel all after calls on close """
try:
self.status_bar.after_cancel(self.progress_loopid)
except AttributeError:
pass
self._root.after_cancel(self.uptime_loopid)
def close_playlistwindow(self):
""" close playlist window if available """
self.controls_frame.pack_forget()
try:
self.status_bar.after_cancel(self.progress_loopid)
except Exception:
pass
self.list_frame.pack_forget()
self.listbox.pack_forget()
self.scrollbar.pack_forget()
self.controls_frame, self.list_frame = None, None
self.listbox, self.scrollbar = None, None
self.progress_bar.style = None
self.controls_frame = None
self.collected = []
self.tab_num = 0
def toggle_sleep(self):
""" if player and downloader are idle sleep """
if (self.is_downloading() and self._playing):
prevent_sleep()
else:
allow_sleep()
def _on_enter(self, event):
"""
On mouse over widget
"""
event.widget["bg"] = "gray97"
def _on_leave(self, event):
"""
On mouse leave widget
"""
if self.controls_frame is not None:
event.widget["bg"] = "gray28"
else:
# use the current theme on leave; that includes light
event.widget["bg"] = Player.BG
def _convert(self, text: str):
"""
Trims title text
"""
if len(text) > 46: # not so perfect
if text[:46].isupper():
text = f"{text[:43]}..."
else:
text = f"{text[:45]}..."
return text
@property
def isOffline(self) -> bool:
""" return True if no internet """
return gethostbyname(gethostname()) == "127.0.0.1"
def get_sinfo(self, url) -> dict:
"""
get sinfo from either cache or
extract, cache and return it
"""
sinfo = self.file_cache.get_stream(url)
if not sinfo:
sinfo = get_sanitizedinfo(url)
if sinfo:
self.file_cache.cache_stream(url, sinfo)
return sinfo
def file_fromlistbox(self, index: int) -> str:
"""
get selected file of listbox index
from either all_files or collected
"""
if self.collected:
return self.collected[index]
return self._all_files[index]
# ------------------------------------------------------------------------------------------------------------------------------
def _update_bindings(self):
"""
Mouse hover bindings; to change background of button in dark mode
"""
if self.controls_frame is not None or Player.BG == "gray28":
self._previous_btn.bind("<Enter>", self._on_enter)
self._previous_btn.bind("<Leave>", self._on_leave)
self._play_btn.bind("<Enter>", self._on_enter)
self._play_btn.bind("<Leave>", self._on_leave)
self._next_btn.bind("<Enter>", self._on_enter)
self._next_btn.bind("<Leave>", self._on_leave)
# ------------------------------------------------------------------------------------------------------------------------------
def __update_listbox(self):
"""
Inserts items to the Listbox
"""
self.listbox.pack_forget()
self.scrollbar.pack_forget()
self.searchlabel.configure(text="Updating...")
self.searchlabel.place(x=10, y=72)
self.collection_index = -1
self.collected = []
# self.searchbar.delete(0, "end")
self.listbox.delete(0, "end")
try:
self.back_toplaylist_btn.destroy()
except AttributeError:
pass
try:
# self._root.geometry("318x118+")
for file in self._all_files:
self.listbox.insert("end", file)
self.listbox_select(self.index)
self.listbox.pack(side="left", padx=3)
self.scrollbar.pack(side="left", fill="y")
self._resize_listbox()
except AttributeError:
pass
def _update_listbox(self):
"""
Threads __update_listbox function
Inserts items to listbox from self._all_files
"""
if self.listbox is not None and self.scrollbar is not None:
self.threadpool.submit(self.__update_listbox)
# ------------------------------------------------------------------------------------------------------------------------------
def _resize_listbox(self):
"""
Dynamically resize Listbox according to the number of items
"""
self.searchbar.place(x=178, y=73)
if self.listbox.size() > 35:
self._root.geometry(f"318x{self._screen_height}+" + f"{self._root.winfo_x()}+{5}")
if not self.tab_num:
self.searchlabel.configure(text="Search:")
else:
self.searchlabel.configure(text="Search online:")
elif self.listbox.size() > 0:
# one line takes 16 pixels on my machine
height = 124 + (self.listbox.size() * 16)
y = self._root.winfo_y()
difference = self._screen_height - (y + height)
# if the new height surpasses screen bottom, then subtract the difference from y to get new y
if difference < 0:
y = y - (difference * -1)
if y < 5: # prevent the window from going beyond the screen top
y = 5
self._root.geometry(f"318x{height}+" + f"{self._root.winfo_x()}+{y}")
if not self.tab_num:
self.searchlabel.configure(text="Search:")
else:
self.searchlabel.configure(text="Search online:")
else:
self._root.geometry(f"318x{self._screen_height}+" + f"{self._root.winfo_x()}+{5}")
self.searchlabel.configure(text="No files found!")
# direct focus to searchbar
# self.searchbar.focus_set()
# ------------------------------------------------------------------------------------------------------------------------------
def __on_search(self):
"""
updates listbox with match for string searched else updates listbox
fetches and updates online streams if tab_num is 1
"""
self.searchbar.selection_clear()
search_string = self.searchbar.get()
if len(search_string) > 1:
if len(self._search_history) >= 6: # keep upto 5 searches
self._search_history.pop()
if self.tab_num:
# online
if not self.isOffline:
self.searchlabel.configure(text="Updating...")
# do search here bacause;
# this function is threaded,
# query_str is needed; unlike _handle_stream_tab's search
if is_url(search_string):
self.searchlabel.configure(text="Extracting url...")
sinfo = self.get_sinfo(search_string)
title = get_url_details(sinfo, only="title")
if title: # is not None:
# update, placed last if not in _title_link
self._title_link[title] = search_string
# update gui
self._handle_stream_tab() # blocking
try:
# get index using title after updating gui
index = self.listview.get(0, "end").index(title)
except ValueError:
index = -1
self.listview_select(index)
else:
# no title is found, sinfo is empty
self.status_bar.configure(text="Could not extract url...")
else: # else is search str
self._search_history.add(search_string) # save only online searches
self.search_str = search_string # avoid saving link as last search
self._title_link = self.video_search.search(search_string)
# update listview window in streams tab
self.thread_updating_streams()
self.stream_index = -1
if self.tab_num:
self.searchlabel.configure(text="Search online:")
else:
self.searchlabel.configure(text="Search:")
else:
# local files tab
self.collected = []
self.collection_index = -1
try:
self.back_toplaylist_btn.destroy()
except AttributeError:
pass
# ---------------------------------back button-------------
self.back_toplaylist_btn = Button(self.controls_frame, image=self.lpo_image, bg="gray28",
pady=0, relief="flat", width=66, height=12)
self.back_toplaylist_btn.place(x=3, y=74)
# ToolTip(self.back_toplaylist_btn, "Leave search-results playlist", hover_delay=0)
search_str = search_string.lower()
# ---------------------------------
self.listbox.delete(0, "end")
self.collected = [song for song in self._all_files if search_str in song.lower()]
self.listbox.insert("end", *self.collected)
self._resize_listbox()
# give the button functionality after update is done
self.back_toplaylist_btn.configure(command=self._update_listbox)
else:
if (not self.tab_num):
if self.listbox.size() != len(self._all_files):
self._update_listbox()
def _on_search(self, event):
"""
Threads __on_search function
"""
self.threadpool.submit(self.__on_search)
def complete_searches(self, event):
""" suggest inline """
if (len(event.keysym) == 1) and (event.char): # skip special keys
if self._search_history:
typed = self.searchbar.get()
start = len(typed)
match = ""
for sw in self._search_history:
if sw.startswith(typed):
match = sw
break
if match:
# update searchbar
self.searchbar.delete(0, "end")
self.searchbar.insert(0, match)
self.searchbar.selection_range(start, "end")
def entryhighlight(self, event=None):
""" highlight text whenever search entry takes focus """
if event is not None:
event.widget.selection_range(0, "end")
def _file_metadata(self, file: str, title: str):
""" get file metadata """
try:
# get local file details
details = self.file_cache.get_metadata(title)
if not details:
details = file_details(file, exiftool_path=EXIFTOOL_PATH)
self.file_cache.cache_metadata(title, details)
DetailsPopup(self._root, title, details, bg="white")
except IndexError:
pass
def _file_details(self):
""" get and display file metadata """
index = self.listbox.curselection()[-1]
title = self.file_fromlistbox(index)
filename = self.valid_path(title)
# thread
self.threadpool.submit(
self._file_metadata,
filename, title
)
def _url_metadata(self, url: str, title: str):
""" popup url details """
try:
sinfo = self.get_sinfo(url)
if sinfo:
details = get_url_details(sinfo) # dict for display
DetailsPopup(self._root, title, details, bg="white")
else:
self.status_bar.configure(text="Could not fetch metadata...")
except Exception as e:
logger.exception(e)
self.status_bar.configure(text="")
def _url_details(self):
""" get and display url metadata """
self.status_bar.configure(text="Fetching metadata...")
title = self.listview.selection_get()
url = self._title_link.get(title)
# get metadata
self.threadpool.submit(
self._url_metadata,
url, title
)
# ------------------------------------------------------------------------------------------------------------------------------
def _on_refresh(self):
""" refresh playlist files function """
self.index = -1
self._all_files = [
i.name
for i in os.scandir(self._songspath)
if (i.name.endswith(self._supported_extensions) and i.is_file())
]
self._all_files.sort(key=atime_sortkey(self._songspath))
if self.listbox is not None:
self._update_listbox()
# ------------------------------------------------------------------------------------------------------------------------------
def _delete_listitem(self):
"""
Listbox's Remove from Playlist
"""
for i in reversed(self.listbox.curselection()):
if not self.collected:
item = self._all_files[i]
self._all_files.remove(item)
else:
item = self.collected[i]
self.collected.remove(item)
self.listbox.delete(i)
if i <= self.index:
# adjust to playlist shifting
self.index -= 1
self._resize_listbox()
# ------------------------------------------------------------------------------------------------------------------------------
def _remove_streams(self):
""" remove selected streams from view """
for i in reversed(self.listview.curselection()):
title = self.listview.get(i)
self._title_link.pop(title, None)
self.listview.delete(i)
# ------------------------------------------------------------------------------------------------------------------------------
def _send2trash(self):
"""
Try sending to trash if not removable disk, else delete permanently
"""
selected = self.listbox.curselection()
if selected:
answer = okcancel(
self._root,
"Lazy Selector",
"Selected files will be moved to Recycle Bin\nContinue to delete?",
)
if answer:
for i in reversed(selected):
if self.collected:
item = self.collected[i]
self.collected.remove(item)
if i <= self.collection_index:
# adjust to 'collected' shifting
self.collection_index -= 1
else:
item = self._all_files[i]
self._all_files.remove(item)
if i <= self.index:
# adjust to playlist shifting
self.index -= 1
self.listbox.delete(i)
# delete file
filename = os.path.normpath(self.valid_path(item))
try:
# go to next before deleting to avoid 'file is open by another program' error
if filename == self._song:
self._play_prev(prev=0)
send2trash(filename)
except Exception as e:
logger.exception(e)
safe_delete(filename)
self._resize_listbox()
# ------------------------------------------------------------------------------------------------------------------------------
def _addto_queue(self):
"""
Listbox's Play Next
"""
try:
i = self.listbox.curselection()[-1]
if (not self.collected) and (i != self.index and i != self.index + 1): # if adding from main list
item = self._all_files[i]
try:
if i > self.index:
# if the selected item is below the currently, delete first to avoid shift in indexes
# deleting after insertion shifts the item down by 1
self.listbox.delete(i)
self._all_files.remove(self._all_files[i]) # remove item
self.listbox.insert(self.index + 1, item)
self._all_files.insert(self.index + 1, item)
else:
# insert first then delete before items shift up, including the currently playing
self.listbox.insert(self.index + 1, item)
self._all_files.insert(self.index + 1, item)
self.listbox.delete(i)
self._all_files.remove(self._all_files[i]) # remove item
self.index -= 1
except ValueError:
pass
self.listbox_select(self.index, see=False)
# if adding from searched list
elif (self.collected) and (i != self.collection_index
and i != self.collection_index + 1) and self.collection_index != -1:
item = self.collected[i]
try:
if i > self.collection_index:
# delete first then insert for index greater than pivot (collection_index)
self.listbox.delete(i)
self.collected.remove(self.collected[i]) # remove item
self.listbox.insert(self.collection_index + 1, item)
self.collected.insert(self.collection_index + 1, item)
else:
# if index to add is less than the pivot
self.listbox.insert(self.collection_index + 1, item)
self.collected.insert(self.collection_index + 1, item)
self.listbox.delete(i)
self.collected.remove(self.collected[i]) # remove item
self.collection_index -= 1
except ValueError:
pass
self.listbox_select(self.collection_index, see=False)
except IndexError: # IndexError occurs when nothing was selected in the Listbox
pass
def _addto_playlist(self):
""" function to be called on 'Play Next in Playlist' """
try:
i = self.listbox.curselection()[-1]
self.listbox.selection_clear(0, "end")
item = self.collected[i]
num = self._all_files.index(item)
if item != self._all_files[self.index + 1]:
try:
self._all_files.remove(item) # remove and insert later
# if item removed is above the currently playing in the playlist
if num <= self.index:
# since we're removing before inserting
# removing an item at an index less than self.index
# causes list to shift by -1
# so our true index becomes self.index - 1
self.index -= 1
except ValueError:
pass
self._all_files.insert(self.index + 1, item)
except IndexError:
pass
# ------------------------------------------------------------------------------------------------------------------------------
def _listbox_rightclick(self, event):
"""
Popup event function to bind to local files' listbox right click
"""
popup = Menu(self.listbox, tearoff=0, bg="gray28", fg="gray97", font=("New Times Roman", 9, "bold"),
activebackground="DeepSkyBlue3")
popup.add_command(label="Play", command=self._on_click)
if self.collected:
popup.add_command(label="Play Next Here", command=self._addto_queue)
# popup.add_separator()
popup.add_command(label="Play Next in Playlist", command=self._addto_playlist)
else:
popup.add_command(label="Play Next", command=self._addto_queue)
popup.add_separator()
popup.add_command(label="Refresh Playlist", command=self._on_refresh)
popup.add_separator()
popup.add_command(label="Remove from Playlist", command=self._delete_listitem)
popup.add_command(label="Delete from Storage", command=self._send2trash)
popup.add_separator()
popup.add_command(label="Properties", command=self._file_details)
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
popup.grab_release()
def _rightclick(self, event):
"""
Popup event function to bind to main window right click
"""
popup = Menu(self.main_frame, tearoff=0, bg=Player.BG, fg=Player.FG, font=("New Times Roman", 9),
activebackground="DeepSkyBlue3")
popup.add_command(label="Add to Queue", command=self._select_fav)
popup.add_command(label="Show Playlist", command=self._listview)
popup.add_separator()
popup.add_command(label="Refresh Playlist", command=self._on_refresh)
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
popup.grab_release()
def _play_options(self, event):
"""
pop-up for playback options like 'mute'
"""
popup = Menu(self._more_btn, tearoff=0, bg="gray97", fg="gray28", font=("New Times Roman", 9, "bold"),
activebackground="DeepSkyBlue3", selectcolor="gray28")
popup.add_checkbutton(label="Mute", variable=self.mute_variable, command=self.mute_mixer)
popup.add_checkbutton(label="Loop One", variable=self.loopone_variable, command=self._onoff_repeat)
try:
popup.tk_popup(event.x_root - 70, event.y_root - 30, 0)
finally:
popup.grab_release()
# ------------------------------------------------------------------------------------------------------------------------------
def _streams_rightclick(self, event):
"""
Popup event function to bind to streams listbox right click
"""
popup = Menu(self.listview, tearoff=0, bg="gray28", fg="gray97", font=("New Times Roman", 9, "bold"),
activebackground="DeepSkyBlue3")
popup.add_command(label="Play", command=self._on_click)
popup.add_separator()
popup.add_command(label="Download Audio", command=self.download_audio)
popup.add_command(label="Download Video", command=self.download_video)
popup.add_separator()
popup.add_command(label="Remove from Playlist", command=self._remove_streams)
popup.add_separator()
popup.add_command(label="Properties", command=self._url_details)
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
popup.grab_release()
def is_downloading(self):
""" return True if downloading """
return not self.send_event("is_done")
# ----------------------------------------------------------------------------------------------------------------------
def _download_audio(self):
""" download youtube audio of link """
# get link from title
self.status_bar.configure(text="Fetching audio info...")
title = self.listview.selection_get()
link = self._title_link.get(title)
try:
sinfo = self.get_sinfo(link)
if sinfo:
self.audio_streams = tuple(get_audio_streams(sinfo))
for_display = [f"{i}. {s.p} {s.p_size}" for i, s in enumerate(self.audio_streams, start=1)]
self.status_bar.configure(text="")
if for_display:
quality = getquality(
self._root, title,
"Audio", for_display,
self.download_location
)
self.prepare_download(quality)
else:
self.status_bar.configure(text="Some data is missing: no audio streams...")
else:
self.status_bar.configure(text="Could not fetch audio info...")
except Exception as e:
logger.exception(e)
error_msg = handle_yt_errors(e)
self.status_bar.configure(text=error_msg)
def download_audio(self):
""" threaded download audio """
self.threadpool.submit(self._download_audio)
def _download_video(self):
""" download youtube video of link """
# get link from title
self.status_bar.configure(text="Fetching video info...")
title = self.listview.selection_get()
link = self._title_link.get(title)
try:
sinfo = self.get_sinfo(link)
if sinfo:
self.video_streams = tuple(get_video_streams(sinfo))
for_display = [f"{i}. {s.p} {s.p_size}" for i, s in enumerate(self.video_streams, start=1)]
self.status_bar.configure(text="")
if for_display:
quality = getquality(self._root, title,
"Video", for_display, self.download_location)
self.prepare_download(quality)
else:
self.status_bar.configure(text="Some data is missing: no video streams...")
else:
self.status_bar.configure(text="Could not fetch video info...")
except Exception as e:
logger.exception(e)
error_msg = handle_yt_errors(e)
self.status_bar.configure(text=error_msg)
def download_video(self):
""" threaded download video """
self.threadpool.submit(self._download_video)
def prepare_download(self, q):
if q:
try:
q, self.download_location, f_preset = q
index, quality = q.split(". ")
index = int(index) - 1 # minus 1 because enumerate starts from 1
if "kbps" in quality:
aud_strm = self.audio_streams[index]
self.send_event(
"audio_download",
aud_strm,
self.download_location,
preset=f_preset,
)
else:
vid_strm = self.video_streams[index]
self.send_event(
"video_download",
vid_strm,
self.download_location,
preset=f_preset,
)