-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
3595 lines (3245 loc) · 126 KB
/
main.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
# pylint: disable=possibly-used-before-assignment
# region imports
import curses
import multiprocessing
import os
import sys
import threading
import click
import msgspec
from collections import defaultdict
from queue import Queue
from random import randint
from shutil import move, copy, rmtree
from time import sleep, time
from maestro import config
from maestro import helpers
from maestro.__version__ import VERSION
from maestro.config import print_to_logfile # pylint: disable=unused-import
# endregion
# region utility functions/classes
def _play(
stdscr,
playlist,
volume,
loop,
clip_mode,
reshuffle,
update_discord,
visualize,
stream,
username,
password,
lyrics,
translated_lyrics,
):
helpers.init_curses(stdscr)
can_mac_now_playing = False
if sys.platform == "darwin":
try:
from maestro.mac_presence import (
MacNowPlaying,
AppDelegate,
app_helper_loop,
)
# pylint: disable=no-name-in-module,import-error
from AppKit import (
NSApp,
NSApplication,
# NSApplicationDelegate,
NSApplicationActivationPolicyProhibited,
NSDate,
NSRunLoop,
)
# pylint: enable
mac_now_playing = MacNowPlaying()
can_mac_now_playing = True
except (
Exception # pylint: disable=bare-except,broad-except
) as mac_import_err:
print_to_logfile("macOS PyObjC import error:", mac_import_err)
if loop:
next_playlist = playlist[:]
helpers.bounded_shuffle(next_playlist, reshuffle)
else:
next_playlist = None
player = helpers.PlaybackHandler(
stdscr,
playlist,
clip_mode,
visualize,
stream,
(username, password) if username and password else (None, None),
lyrics,
translated_lyrics,
)
player.volume = volume
if can_mac_now_playing:
player.can_mac_now_playing = True
player.mac_now_playing = mac_now_playing
player.mac_now_playing.title_queue = Queue()
player.mac_now_playing.artist_queue = Queue()
player.mac_now_playing.q = Queue()
ns_application = NSApplication.sharedApplication()
ns_application.setActivationPolicy_(
NSApplicationActivationPolicyProhibited
)
# NOTE: keep ref to delegate object, setDelegate_ doesn't retain
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
app_helper_process = multiprocessing.Process(
daemon=True,
target=app_helper_loop,
)
app_helper_process.start()
if update_discord:
player.threaded_initialize_discord()
prev_volume = volume
while player.i in range(len(player.playlist)):
player.playback.load_file(player.song_path)
if player.song.set_clip in player.song.clips:
player.clip = player.song.clips[player.song.set_clip]
else:
player.clip = (0, player.playback.duration)
player.paused = False
player.lyrics = (
player.song.parsed_override_lyrics or player.song.parsed_lyrics
)
player.lyric_pos = None
if player.lyrics is not None:
player.lyrics_scroller = helpers.Scroller(
len(player.lyrics), player.screen_height - 1
)
player.translated_lyrics = player.song.parsed_translated_lyrics
player.playback.play()
player.set_volume(volume)
player.update_metadata()
# latter is clip-agnostic, former is clip-aware
player.duration = player.playback.duration
if player.clip_mode:
clip_start, clip_end = player.clip
player.duration = clip_end - clip_start
player.seek(clip_start)
start_time = pause_start = time()
player.last_timestamp = player.playback.curr_pos
next_song = 1 # -1 if going back, 0 if restarting, +1 if next song
player.restarting = False
while True:
if not player.playback.active or (
player.clip_mode and player.playback.curr_pos > player.clip[1]
):
next_song = not player.looping_current_song
break
# fade in first 2 seconds of clip
if (
player.clip_mode
and clip_start != 0 # if clip doesn't start at beginning
and clip_end - clip_start > 5 # if clip is longer than 5 secs
and player.playback.curr_pos < clip_start + 2
):
player.set_volume(
player.volume * (player.playback.curr_pos - clip_start) / 2
)
else:
player.set_volume(player.volume)
if player.can_mac_now_playing: # macOS Now Playing event loop
try:
if player.update_now_playing:
player.mac_now_playing.update()
player.update_now_playing = False
NSRunLoop.currentRunLoop().runUntilDate_(
NSDate.dateWithTimeIntervalSinceNow_(0.05)
)
except Exception as e:
print_to_logfile("macOS Now Playing error:", e)
player.can_mac_now_playing = False
if (
player.can_mac_now_playing
and not player.mac_now_playing.q.empty()
):
c = player.mac_now_playing.q.get()
if c in "nN":
if player.i == len(player.playlist) - 1 and not loop:
pass
else:
next_song = 1
player.playback.stop()
break
elif c in "bB":
if player.i == 0:
pass
else:
next_song = -1
player.playback.stop()
break
elif c in "rR":
player.playback.stop()
next_song = 0
break
elif c in "qQ":
player.ending = True
break
elif c == " ":
player.paused = not player.paused
if player.paused:
player.playback.pause()
pause_start = time()
else:
player.playback.resume()
start_time += time() - pause_start
if player.can_mac_now_playing:
player.mac_now_playing.paused = player.paused
if player.paused:
player.mac_now_playing.pause()
else:
player.mac_now_playing.resume()
player.update_now_playing = True
player.update_screen()
else:
c = player.stdscr.getch() # int
next_c = player.stdscr.getch()
while next_c != -1:
c, next_c = next_c, player.stdscr.getch()
if c != -1:
try:
ch = chr(c)
if ch in "\b\x7f":
c = curses.KEY_DC
elif ch in "\r\n":
c = curses.KEY_ENTER
except (ValueError, OverflowError):
ch = None
if c == curses.KEY_UP:
player.scroll_backward()
player.update_screen()
elif c == curses.KEY_DOWN:
player.scroll_forward()
player.update_screen()
elif c == curses.KEY_SLEFT:
if player.want_lyrics:
player.lyrics_width += 1
player.update_screen()
elif c == curses.KEY_SRIGHT:
if player.want_lyrics:
player.lyrics_width -= 1
player.update_screen()
elif c == 337: # SHIFT + UP
if player.scroller.pos > 0:
if player.scroller.pos == player.i:
player.i -= 1
elif player.scroller.pos == player.i + 1:
player.i += 1
(
player.playlist[player.scroller.pos],
player.playlist[player.scroller.pos - 1],
) = (
player.playlist[player.scroller.pos - 1],
player.playlist[player.scroller.pos],
)
player.scroller.scroll_backward()
elif c == 336: # SHIFT + DOWN
if player.scroller.pos < player.scroller.num_lines - 1:
if player.scroller.pos == player.i:
player.i += 1
elif player.scroller.pos == player.i - 1:
player.i -= 1
(
player.playlist[player.scroller.pos],
player.playlist[player.scroller.pos + 1],
) = (
player.playlist[player.scroller.pos + 1],
player.playlist[player.scroller.pos],
)
player.scroller.scroll_forward()
else:
if player.prompting is None:
if c == curses.KEY_LEFT:
player.seek(
player.playback.curr_pos - config.SCRUB_TIME
)
player.update_screen()
elif c == curses.KEY_RIGHT:
player.seek(
player.playback.curr_pos + config.SCRUB_TIME
)
player.update_screen()
elif c == curses.KEY_ENTER:
if player.focus == 0:
# pylint: disable=invalid-unary-operand-type
# -2 because pos can be 0
next_song = -(player.scroller.pos) - 2
player.playback.stop()
break
elif player.focus == 1:
if (
helpers.is_timed_lyrics(player.lyrics)
and player.lyric_pos is not None
):
player.seek(
player.lyrics[player.lyric_pos].time
)
player.snap_back()
player.update_screen()
elif c == curses.KEY_DC:
if len(player.playlist) > 1:
player.scroller.num_lines -= 1
if (
player.scroller.pos == player.i
): # deleted current song
next_song = 3
player.playback.stop()
break
deleted_song = player.playlist[
player.scroller.pos
]
del player.playlist[player.scroller.pos]
if loop:
for i in range(len(next_playlist)):
if next_playlist[i] == deleted_song:
del next_playlist[i]
break
# deleted song before current
if player.scroller.pos < player.i:
player.i -= 1
# deleted last song
if (
player.scroller.pos
== player.scroller.num_lines
):
player.scroller.pos -= 1
player.scroller.refresh()
elif c == 27: # ESC key
if player.show_help:
player.show_help = False
player.update_screen()
elif ch is not None:
if ch in "nN":
if (
not player.i == len(player.playlist) - 1
or loop
):
next_song = 1
player.playback.stop()
break
elif ch in "bB":
if player.i != 0:
next_song = -1
player.playback.stop()
break
elif ch in "rR":
player.restarting = True
player.playback.stop()
next_song = 0
break
elif ch in "lL":
player.looping_current_song = (
player.looping_current_song + 1
) % len(config.LOOP_MODES)
player.update_screen()
elif ch in "cC":
player.clip_mode = not player.clip_mode
if player.clip_mode:
clip_start, clip_end = player.clip
player.duration = clip_end - clip_start
if (
player.playback.curr_pos
< clip_start
or player.playback.curr_pos
> clip_end
):
player.seek(clip_start)
else:
player.duration = (
player.playback.duration
)
player.update_screen()
elif ch in "pP":
player.snap_back()
player.update_screen()
elif ch in "gG":
if loop:
player.playback.stop()
next_song = 2
break
elif ch in "eE":
player.ending = not player.ending
player.update_screen()
elif ch in "qQ":
player.ending = True
break
elif ch in "dD":
if player.want_discord:
player.want_discord = False
if player.discord_rpc is not None:
player.discord_rpc.close()
player.discord_connected = 0
else:
def f():
player.initialize_discord()
player.update_discord_metadata()
player.update_stream_metadata()
threading.Thread(
target=f,
daemon=True,
).start()
elif ch in "iI":
player.prompting = (
"",
0,
config.PROMPT_MODES["insert"],
)
curses.curs_set(True)
screen_size = player.stdscr.getmaxyx()
player.scroller.resize(screen_size[0] - 3)
player.update_screen()
elif ch in "aA":
player.prompting = (
"",
0,
config.PROMPT_MODES["append"],
)
curses.curs_set(True)
screen_size = player.stdscr.getmaxyx()
player.scroller.resize(screen_size[0] - 3)
player.update_screen()
elif ch == ",":
player.prompting = (
"",
0,
config.PROMPT_MODES["tag"],
)
curses.curs_set(True)
screen_size = player.stdscr.getmaxyx()
player.scroller.resize(screen_size[0] - 3)
player.update_screen()
elif ch in "mM":
if player.volume == 0:
player.volume = prev_volume
else:
player.volume = 0
player.update_screen()
elif ch in "vV":
player.want_vis = not player.want_vis
player.update_screen()
elif ch in "sS":
player.want_stream = not player.want_stream
if player.want_stream:
if player.username is not None:
threading.Thread(
target=player.update_stream_metadata,
daemon=True,
).start()
player.ffmpeg_process.start()
else:
player.ffmpeg_process.terminate()
player.update_discord_metadata()
player.update_screen()
elif ch == " ":
player.paused = not player.paused
if player.paused:
player.playback.pause()
pause_start = time()
else:
player.playback.resume()
start_time += time() - pause_start
if player.can_mac_now_playing:
player.mac_now_playing.paused = (
player.paused
)
if player.paused:
player.mac_now_playing.pause()
else:
player.mac_now_playing.resume()
player.update_now_playing = True
player.update_screen()
elif ch in "[-":
player.volume = max(
0, player.volume - config.VOLUME_STEP
)
player.update_screen()
prev_volume = player.volume
elif ch in "]=":
player.volume = min(
100, player.volume + config.VOLUME_STEP
)
player.update_screen()
prev_volume = player.volume
elif ch in "yY":
player.want_lyrics = not player.want_lyrics
elif ch in "oO":
helpers.SONG_DATA.load()
helpers.SONGS.load()
for song in player.playlist:
song.reset()
if (
player.song.set_clip
in player.song.clips
):
player.clip = player.song.clips[
player.song.set_clip
]
else:
player.clip = (
0,
player.playback.duration,
)
player.duration = (
player.clip[1] - player.clip[0]
)
player.lyrics = (
player.song.parsed_override_lyrics
or player.song.parsed_lyrics
)
if player.lyrics is not None:
player.lyrics_scroller = (
helpers.Scroller(
len(player.lyrics),
player.screen_height - 1,
)
)
player.translated_lyrics = (
player.song.parsed_translated_lyrics
)
from keyring.errors import NoKeyringError
try:
player.username = helpers.get_username()
player.password = helpers.get_password()
except NoKeyringError:
pass
player.update_screen()
elif ch in "hH":
player.show_help = not player.show_help
elif ch in "tT":
player.want_translated_lyrics = (
not player.want_translated_lyrics
and player.want_lyrics
)
elif ch in "fF":
player.prompting = (
"",
0,
config.PROMPT_MODES["find"],
)
curses.curs_set(True)
screen_size = player.stdscr.getmaxyx()
player.scroller.resize(screen_size[0] - 3)
player.update_screen()
elif ch in "{_":
player.snap_back()
player.focus = 0
elif ch in "}+":
player.snap_back()
player.focus = 1
else:
if c == curses.KEY_LEFT:
# pylint: disable=unsubscriptable-object
player.prompting = (
player.prompting[0],
max(player.prompting[1] - 1, 0),
player.prompting[2],
)
player.update_screen()
elif c == curses.KEY_RIGHT:
# pylint: disable=unsubscriptable-object
player.prompting = (
player.prompting[0],
min(
player.prompting[1] + 1,
len(player.prompting[0]),
),
player.prompting[2],
)
player.update_screen()
elif c == curses.KEY_DC:
# pylint: disable=unsubscriptable-object
player.prompting_delete_char()
player.update_screen()
elif c == curses.KEY_ENTER:
# pylint: disable=unsubscriptable-object
# fmt: off
if (
player.prompting[2] == config.PROMPT_MODES["tag"]
):
tags = set(player.prompting[0].split(","))
for song in player.playlist:
song.tags |= tags
player.prompting = None
curses.curs_set(False)
player.scroller.resize(screen_size[0] - 2)
player.update_screen()
elif player.prompting[2] == config.PROMPT_MODES["find"]:
try:
song = helpers.CLICK_SONG(player.prompting[0])
i = player.playlist.index(song)
if i != -1:
player.scroller.pos = i
player.prompting = None
curses.curs_set(False)
player.scroller.resize(screen_size[0] - 2)
player.update_screen()
except click.BadParameter:
pass
else:
try:
song = helpers.CLICK_SONG(player.prompting[0])
if player.prompting[2] == config.PROMPT_MODES["insert"]:
player.playlist.insert(
player.scroller.pos + 1,
song,
)
inserted_pos = player.scroller.pos + 1
if player.i > player.scroller.pos:
player.i += 1
else:
player.playlist.append(song)
inserted_pos = len(player.playlist) - 1
if loop:
if reshuffle >= 0:
next_playlist.insert(randint(max(0, inserted_pos-reshuffle), min(len(playlist)-1, inserted_pos+reshuffle)), song)
elif reshuffle == -1:
next_playlist.insert(randint(0, len(playlist) - 1), song)
player.scroller.num_lines += 1
player.prompting = None
curses.curs_set(False)
player.scroller.resize(screen_size[0] - 2)
player.update_screen()
except click.BadParameter:
pass
elif c == 27: # ESC key
player.prompting = None
curses.curs_set(False)
player.scroller.resize(screen_size[0] - 2)
player.update_screen()
elif ch is not None:
player.prompting = (
# pylint: disable=unsubscriptable-object
player.prompting[0][: player.prompting[1]]
+ ch
+ player.prompting[0][
player.prompting[1] :
],
player.prompting[1] + 1,
player.prompting[2],
)
player.update_screen()
if (
player.can_mac_now_playing
): # sync macOS Now Playing pos with playback pos
if (
abs(player.mac_now_playing.pos - player.playback.curr_pos)
> 1
):
player.seek(player.mac_now_playing.pos)
player.update_screen()
else:
player.mac_now_playing.pos = round(player.playback.curr_pos)
progress_bar_width = player.stdscr.getmaxyx()[1] - 18
frame_duration = min(
(
1
if progress_bar_width < config.MIN_PROGRESS_BAR_WIDTH
else player.duration / (progress_bar_width * 8)
),
1 / config.FPS if player.want_vis else 1,
)
if (
abs(player.playback.curr_pos - player.last_timestamp)
> frame_duration
):
player.last_timestamp = player.playback.curr_pos
player.update_screen()
sleep(0.01) # NOTE: so CPU usage doesn't fly through the roof
if player.paused:
time_listened = pause_start - start_time
else:
time_listened = time() - start_time
# region update stats
def stats_update(s: helpers.Song, t: float):
s.listen_times[config.CUR_YEAR] += t
s.listen_times["total"] += t
threading.Thread(
target=stats_update, args=(player.song, time_listened), daemon=True
).start()
# endregion
if player.ending and not player.restarting:
player.quit()
if player.can_mac_now_playing:
app_helper_process.terminate()
return
if next_song == -1:
if player.i == player.scroller.pos:
player.scroller.scroll_backward()
player.i -= 1
elif next_song == 1:
if player.i == len(player.playlist) - 1:
if loop:
next_next_playlist = next_playlist[:]
if reshuffle:
helpers.bounded_shuffle(next_next_playlist, reshuffle)
player.playlist, next_playlist = (
next_playlist,
next_next_playlist,
)
player.i = -1
player.scroller.pos = 0
else:
return
else:
if player.i == player.scroller.pos:
player.scroller.scroll_forward()
player.i += 1
elif next_song == 0:
if player.looping_current_song == config.LOOP_MODES["one"]:
player.looping_current_song = config.LOOP_MODES["none"]
elif next_song <= -2: # user pos -> -(pos + 2)
player.i = -next_song - 2
elif next_song == 2: # next page
next_next_playlist = next_playlist[:]
if reshuffle:
helpers.bounded_shuffle(next_next_playlist, reshuffle)
player.playlist, next_playlist = (
next_playlist,
next_next_playlist,
)
player.i = 0
player.scroller.pos = 0
elif next_song == 3: # deleted current song
deleted_song = player.playlist[player.i]
del player.playlist[player.i]
if loop:
for i in range(len(next_playlist)):
if next_playlist[i] == deleted_song:
del next_playlist[i]
break
# endregion
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.pass_context
def cli(ctx: click.Context):
"""A command line interface for playing music."""
# ~/.maestro-files
if not os.path.exists(config.MAESTRO_DIR):
os.makedirs(config.MAESTRO_DIR)
# ensure config.SETTINGS has all settings
update_settings = False
if not os.path.exists(config.SETTINGS_FILE):
config.settings = config.DEFAULT_SETTINGS
update_settings = True
else:
with open(config.SETTINGS_FILE, "r", encoding="utf-8") as f:
s = f.read()
if s:
config.settings = msgspec.json.decode(s)
for key in config.DEFAULT_SETTINGS:
if key not in config.settings:
config.settings[key] = config.DEFAULT_SETTINGS[key]
update_settings = True
else:
config.settings = config.DEFAULT_SETTINGS
update_settings = True
# ~/.maestro-files/songs.json
if not os.path.exists(config.SONGS_INFO_PATH):
if os.path.exists(config.OLD_SONGS_INFO_PATH):
if ctx.invoked_subcommand == "migrate":
return
ctx.fail(
"Legacy song data detected. Please run 'maestro migrate' to convert the old songs file to the new format."
)
with open(config.SONGS_INFO_PATH, "x", encoding="utf-8") as _:
pass
# ~/.maestro-files/songs/
if not os.path.exists(config.settings["song_directory"]):
os.makedirs(config.settings["song_directory"])
t = time()
if t - config.settings["last_version_sync"] > 24 * 60 * 60: # 1 day
config.settings["last_version_sync"] = t
update_settings = True
try:
import requests
response = requests.get(
"https://pypi.org/pypi/maestro-music/json", timeout=5
)
latest_version = response.json()["info"]["version"]
if helpers.versiontuple(latest_version) > helpers.versiontuple(
VERSION
):
click.secho(
f"A new version of maestro is available. Run 'pip install --upgrade maestro-music' to update to version {latest_version}.",
fg="yellow",
)
except Exception as e:
print_to_logfile("Failed to check for updates:", e)
# ensure config.SETTINGS_FILE is up to date
if update_settings:
import safer
with safer.open(config.SETTINGS_FILE, "wb") as g:
g.write(msgspec.json.encode(config.settings))
# ensure config.LOGFILE is not too large (1 MB)
t = time()
if os.path.exists(config.LOGFILE) and os.path.getsize(config.LOGFILE) > 1e6:
# move to backup
backup_path = os.path.join(config.OLD_LOG_DIR, f"maestro-{int(t)}.log")
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
move(config.LOGFILE, backup_path)
# delete old log files
if os.path.exists(config.OLD_LOG_DIR):
for file in os.listdir(config.OLD_LOG_DIR):
if file.endswith(".log"):
if t - int(file.split(".")[0].split("-")[1]) > 24 * 60 * 60:
os.remove(os.path.join(config.OLD_LOG_DIR, file))
@cli.command()
@click.argument("path_", metavar="PATH_OR_URL")
@click.argument("tags", nargs=-1)
@click.option(
"-M/-nM",
"--move/--no-move",
"move_",
default=False,
help="Move file from PATH to maestro's internal song database instead of copying.",
)
@click.option(
"-n",
"--name",
type=str,
help="What to name the song, if you don't want to use the title from Youtube/Spotify/filename. Do not include an extension (e.g. '.wav'). Ignored if adding multiple songs.",
)
@click.option(
"-R/-nR",
"--recursive/--no-recursive",
"recurse",
default=False,
help="If PATH is a folder, add songs in subfolders.",
)
@click.option(
"-Y/-nY",
"--youtube/--no-youtube",
default=False,
help="Add a song from a YouTube or YouTube Music URL.",
)
@click.option(
"-S/-nS",
"--spotify/--no-spotify",
default=False,
help="Add a song from Spotify (track URL, album URL, playlist URL, artist URL, or search query).",
)
@click.option(
"-f",
"--format",
"format_",
type=click.Choice(("wav", "mp3", "flac", "vorbis")),
help="Specify the format of the song if downloading from YouTube, YouTube Music, or Spotify URL.",
default="mp3",
show_default=True,
)
@click.option(
"-P/-nP",
"--playlist/--no-playlist",
"playlist_",
default=False,
help="If song URL passed is from a YouTube playlist, download all the songs. If the URL points directly to a playlist, this flag is unncessary.",
)
@click.option(
"-m",
"--metadata",
"metadata_pairs",
default=None,
help="Add metadata to the song. If adding multiple songs, the metadata is added to each song. The format is 'key1:value1|key2:value2|...'.",
)
@click.option(
"-a",
"--artist",
help="Specify the artist. If also specified in '-m/--metadata', this takes precedence.",
)
@click.option(
"-b",
"--album",
help="Specify the album. If also specified in '-m/--metadata', this takes precedence.",
)
@click.option(
"-c",
"--album-artist",
help="Specify the album artist. If also specified in '-m/--metadata', this takes precedence.",
)
@click.option(
"-nD/-D",
"--skip-dupes/--no-skip-dupes",
default=False,
help="Skip adding song names that are already in the database. If not passed, 'copy' is appended to any duplicate names.",
)
@click.option(
"-L/-nL",
"--lyrics/--no-lyrics",
default=True,
help="Search for and download lyrics for the song.",
)
@click.option(
"-q",
"--audio-quality",
type=click.Choice(
(
"auto",
# "disable",
"8k",
"16k",
"24k",
"32k",
"40k",
"48k",
"64k",
"80k",
"96k",
"112k",
"128k",
"160k",
"192k",
"224k",
"256k",
"320k",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
),
case_sensitive=False,
),
default="auto",
help="Specify the audio quality to download. 0 is the best quality, 9 is the worst. 'auto' is the default (5). You can also specify a bitrate (e.g. '128k').",
)
def add(
path_,
tags,
move_,
name,
recurse,