-
Notifications
You must be signed in to change notification settings - Fork 0
/
YMAudio.py
1776 lines (1468 loc) · 53 KB
/
YMAudio.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
#!/usr/bin/python3
# YMAudio: Yandex.Music Audio Player
import vlc, cimg, notify2, requests, webbrowser, setproctitle, yandex_music
from Scurses import *
from utils import *; logstart('YMAudio')
from .auth import *
try: import notify2
except ModuleNotFoundError: pass
else: notify2 = None
try: from gi.repository import GLib
except ImportError: GLib = None
else:
try: import dbus.service, dbus.mainloop.glib
except ModuleNotFoundError: GLib = None
ym_login: str
ym_pw: str
ym_token: str
db.setfile('~/YMAudio.db')
db.setbackup(False)
db.setsensitive(True)
db.register('ym_login', 'ym_pw', 'ym_token')
yandex_music.Client.notice_displayed = True
COVER_MIN_SIZE = '30x30'
def ym_is_unauthorized(ex):
try: return ('ownerOtherwiseUserBindingError' in ex.args[0])
except (IndexError, KeyError): return False
if (GLib is not None):
class MediaPlayer2(dbus.service.Object):
class _Properties(SlotsOnly):
app: SCApp
def __init__(self, app):
self.app = app
def to_dict(self):
return {k: v.fget(self) if (isinstance(v, property)) else v for k, v in inspect.getmembers(self) if not k.startswith('_') and k not in ('app', 'to_dict')}
class Properties_org_mpris_MediaPlayer2(_Properties):
CanQuit = True
CanRaise = False
HasTrackList = False # TODO
Identity = 'YMAudio'
SupportedUriSchemes = ['']
SupportedMimeTypes = ['']
class Properties_org_mpris_MediaPlayer2_Player(_Properties):
Shuffle = False
MinimumRate = 0.1
MaximumRate = 10.0
CanGoNext = True
CanGoPrevious = True
CanPlay = True
CanPause = True
CanSeek = True
CanControl = True
@property
def Rate(self):
return self.app.p.get_rate()
@Rate.setter
def Rate(self, rate):
self.app.p.set_rate(rate)
@property
def Volume(self):
return self.app.p.audio_get_volume()/100
@Volume.setter
def Volume(self, volume):
self.app.p.audio_set_volume(volume*100)
@property
def PlaybackStatus(self):
return ('Playing' if (self.app.p.is_playing()) else 'Paused' if (self.app.track) else 'Stopped')
@property
def LoopStatus(self):
return ('Track' if (self.app.repeat) else 'None')
@LoopStatus.setter
def LoopStatus(self, loop):
self.app.repeat = (loop != 'None')
@property
def Metadata(self):
track = self.app.track
return dbus.Dictionary({
'mpris:trackid': dbus.ObjectPath(f"/org/mpris/MediaPlayer2/ymaudio/track/{str(track.track_id).replace(':', '_').replace('-', '_')}" if (track) else '/org/mpris/MediaPlayer2/TrackList/NoTrack'),
'mpris:length': dbus.Int64(max(0, self.app.p.get_length())*1000),
**(S({
'mpris:artUrl': self.app.get_cover(track.cover_uri),
'xesam:artist': track.artists_name() or ('',),
'xesam:title': track.title,
'xesam:url': self.app.get_url(track),
'xesam:asText': self.app.get_lyrics(track),
}).filter(None) if (track) else {}),
}, signature='sv')
@property
def Position(self):
return dbus.Int64(max(0, self.app.p.get_time())*1000)
@Position.setter
def Position(self, position):
self.app.p.set_time(position/1000)
def __init__(self, app, *args, **kwargs):
super().__init__(*args, **kwargs)
self.app = app
self.properties_org_mpris_MediaPlayer2 = self.Properties_org_mpris_MediaPlayer2(self.app)
self.properties_org_mpris_MediaPlayer2_Player = self.Properties_org_mpris_MediaPlayer2_Player(self.app)
@dbus.service.method('org.mpris.MediaPlayer2')
def Raise(self):
pass
@dbus.service.method('org.mpris.MediaPlayer2')
def Quit(self):
self.app.quit()
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Next(self):
self.app.playNextTrack(highlight=False)
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Previous(self):
self.app.playPrevTrack(highlight=False)
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Pause(self):
self.app.pause()
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def PlayPause(self):
self.app.playPause()
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Stop(self):
self.app.stop()
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Play(self):
self.app.play()
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def Seek(self, offset):
self.properties_org_mpris_MediaPlayer2_Player.Position += offset
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def SetPosition(self, trackid, position):
self.properties_org_mpris_MediaPlayer2_Player.Position = position
@dbus.service.method('org.mpris.MediaPlayer2.Player')
def OpenUri(self, uri):
pass
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
def Get(self, interface, prop):
return getattr(getattr(self, 'properties_'+interface.replace('.', '_')), prop)
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
def GetAll(self, interface):
return getattr(self, 'properties_'+interface.replace('.', '_')).to_dict()
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')
def Set(self, interface, prop, value):
setattr(getattr(self, 'properties_'+interface.replace('.', '_')), prop, value)
self.PropertiesChanged(interface, {prop: value}, [])
@dbus.service.signal(dbus.PROPERTIES_IFACE, signature='sa{sv}as')
def PropertiesChanged(self, interface, changed_props, invalidated_props):
pass
class YMAudioView(SCVSplitView):
def __init__(self):
super().__init__(0, 2)
def init(self):
super().init()
self.p[0].addView(MenuRecommsView())
self.p[1].addView(ProgressView())
class YMMenuItem:
menu_label: str
class PlaylistsView(SCLoadingSelectingListView, YMMenuItem):
menu_label = "Плейлисты"
# public:
l: list[yandex_music.Playlist]
# internal:
to_reselect: bool
def __init__(self, l=None):
if (l is None): l = []
super().__init__(l)
self.to_reselect = True
@staticmethod
def _cover_uri(playlist: yandex_music.Playlist):
if (not isinstance(playlist, yandex_music.Playlist)): return None
return playlist.cover.uri
@cachedfunction
def _color(self, playlist):
cover = self.app.get_cover(self._cover_uri(playlist), size=COVER_MIN_SIZE, delayed_view=self)
if (not cover): return self._color._noncached(None)
return tuple(i*1000//255 for i in cimg.pixel_color(cover))
def _pair(self, playlist):
if (curses.COLORS < 9 or not curses.can_change_color()): return 0
res = self._color(playlist)
if (res is None): return 0
r, g, b = res
color = 9 #random.randrange(9, curses.COLORS)
curses.init_color(color, r, g, b)
pair = 2 #random.randrange(9, curses.COLORS)
curses.init_pair(pair, color, curses.COLOR_WHITE if (max(r, g, b) < 500) else curses.COLOR_BLACK)
return curses.color_pair(pair)
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
if (self.to_reselect and not (self.l and isinstance(self.l[0], self.LoadItem))):
self.app.selectPlayingPlaylist()
self.to_reselect = False
return ret
def item(self, i):
ret, items = super().item(i)
if (not ret):
if (isinstance(pl := self.l[i], yandex_music.Playlist)):
duration = S(" · ").join(S((pl.track_count, (self.app.strfTime(pl.duration_ms/1000) if (pl.duration_ms) else None))).filter(None))
title = S(pl.title).fit(self.width)
roff = S(duration).fullwidth()
spacer = ' '*(self.width - S(title).fullwidth() - roff)
attrs = items[0][1]
color = (self._pair(pl) if (attrs & curses.A_STANDOUT) else 0)
if (pl.available is False): attrs |= curses.A_DIM
dim = curses.A_DIM*(not attrs & curses.A_STANDOUT)
items = [
(title, attrs | color),
(spacer, attrs | color),
(duration, attrs | color | dim),
]
return (ret, items)
def select(self):
ret = super().select()
if (not ret):
try: pl = self.l[self.n]
except IndexError: pass
else:
if (isinstance(pl, yandex_music.Playlist)):
self.app.win.addView(AudiosView(playlist=pl, autoplay=True))
ret = True
return ret
def load(self):
ret = super().load()
if (not ret):
if (not self.l): self.l += self.app.ym.users_playlists_list()
self.l.append(self.LoadItem(False))
return ret
class AlbumsView(PlaylistsView):
menu_label = "Альбомы"
# public:
l: list[yandex_music.Album]
@staticmethod
def _cover_uri(album: yandex_music.Album):
if (not isinstance(album, yandex_music.Album)): return None
return album.cover_uri
def item(self, i):
ret, items = super().item(i)
if (not ret):
if (isinstance(a := self.l[i], yandex_music.Album)):
flags = ("E"*bool(a.explicit or a.content_warning)) #+ " ♥ "*self.app.is_liked(a) + " 🛇 "*self.app.is_disliked(a)).lstrip()
duration = S(" · ").join(S((a.track_count, (self.app.strfTime(a.duration_ms/1000) if (a.duration_ms) else None))).filter(None))
if (flags): duration = (' ' + duration)
artist = ', '.join(a.artists_name())
if (artist): artist += " — "
subtitle = " · ".join(S((a.version, a.type, (a.genre if (a.type != 'podcast') else None))).filter(None))
title = (a.title + ' '*bool(subtitle))
roff = S(flags + duration).fullwidth()
subtitle = S(subtitle).fit(self.width - S(artist + title).fullwidth() - roff - 1)
artist = S(artist).fit(self.width - S(title + subtitle).fullwidth() - roff - 1)
title = S(title).fit(self.width - S(artist + subtitle).fullwidth() - roff - 1)
spacer = ' '*(self.width - S(artist + title + subtitle).fullwidth() - roff)
attrs = items[0][1]
color = (self._pair(a) if (attrs & curses.A_STANDOUT) else 0)
if (a.available is False): attrs |= curses.A_DIM
dim = curses.A_DIM*(not attrs & curses.A_STANDOUT)
items = [
(artist, attrs | color),
(title, attrs | color | curses.A_BOLD),
(subtitle, attrs | color | dim),
(spacer, attrs | color),
(flags, attrs | color | dim),
(duration, attrs | color | dim),
]
return (ret, items)
def select(self):
ret = super().select()
if (not ret):
try: a = self.l[self.n]
except IndexError: pass
else:
if (isinstance(a, yandex_music.Album)):
self.app.win.addView(AudiosView(playlist=a.with_tracks(), autoplay=True))
ret = True
return ret
def load(self):
ret = super(PlaylistsView, self).load()
if (not ret):
if (not self.l): self.l += [i.album for i in self.app.ym.users_likes_albums()]
self.l.append(self.LoadItem(False))
return ret
class AudiosView(SCLoadingSelectingListView, YMMenuItem):
menu_label = "Понравившееся"
# public:
playlist: '# yandex_music.Playlist'
pl_pos_min: int
# internal:
to_reselect: bool
def __init__(self, l=None, playlist=None, *, autoplay=False):
if (l is None): l = []
super().__init__(l)
self.playlist, self.autoplay = playlist, autoplay
self.to_reselect = True
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
if (self.to_reselect and not (self.l and isinstance(self.l[0], self.LoadItem))):
self.app.selectPlayingTrack()
self.to_reselect = False
return ret
def key(self, c):
if (c.ch.casefold() in 'nт'):
try: t = self.l[self.n]
except IndexError: pass
else:
for ii, (i, pl) in enumerate(self.app.play_next):
if (i == t):
del self.app.play_next[ii]
self.touch()
break
else:
first = c.ch.isupper()
self.app.playNext(t, self.l, first=first)
if (first): self.app.setPlaylist(self.l, self.n, self.pl_pos_min)
elif (c == 'k' or c == 'л'):
self.highlightAndScroll(random.randrange(len(self.l)-1))
elif (c == 'b' or c == 'и'):
self.app.selectPlayingTrack()
elif (c == 'd' or c == 'в'):
try: t = self.l[self.n]
except IndexError: pass
else:
curses.def_prog_mode()
curses.endwin()
url = self.app.get_url(t)
print(f"Downloading: {url}")
os.system(f"""wget {repr(url)} -O {repr(f"{', '.join(t.artists_name())} - {t.title}.mp3")} -q --show-progress""")
curses.reset_prog_mode()
elif (c == 'l' or c == 'д'):
try: t = self.l[self.n]
except IndexError: pass
else:
if (t.lyrics_available):
lyrics = t.get_supplement().lyrics
if (lyrics is not None):
if (isinstance(self.app.win.top, LyricsView)): self.app.win.top.die()
self.app.win.addView(LyricsView(lyrics))
else: return super().key(c)
return True
@staticmethod
def _cover_uri(track: yandex_music.Track):
if (not isinstance(track, yandex_music.Track)): return None
return track.cover_uri
@cachedfunction
def _color(self, track):
cover = self.app.get_cover(self._cover_uri(track), size=COVER_MIN_SIZE, delayed_view=self)
if (not cover): return self._color._noncached(None)
return tuple(i*1000//255 for i in cimg.pixel_color(cover))
def _pair(self, track):
if (curses.COLORS < 9 or not curses.can_change_color()): return 0
res = self._color(track)
if (res is None): return 0
r, g, b = res
color = 9#random.randrange(9, curses.COLORS)
curses.init_color(color, r, g, b)
pair = 2#random.randrange(9, curses.COLORS)
curses.init_pair(pair, color, curses.COLOR_WHITE if (max(r, g, b) < 500) else curses.COLOR_BLACK)
return curses.color_pair(pair)
def is_empty(self, i):
ret = super().is_empty(i)
if (not ret):
try: t = self.l[i]
except IndexError: pass
else:
return (isinstance(t, yandex_music.Track) and t.available is False)
return ret
def item(self, i):
ret, items = super().item(i)
if (not ret):
if (isinstance(t := self.l[i], yandex_music.Track)):
pn_pos = first((ii for ii, (i, pl) in enumerate(self.app.play_next, 1) if i == t), default='')
queue = ((str(pn_pos).join('()') + ' ') if (pn_pos) else '')
flags = ("E"*bool(t.explicit or t.content_warning) + " ♥ "*self.app.is_liked(t) + " 🛇 "*self.app.is_disliked(t)).lstrip()
duration = (self.app.strfTime(t.duration_ms/1000) if (t.duration_ms) else '')
if (flags): duration = (' ' + duration)
artist = ', '.join(t.artists_name())
if (artist): artist += " — "
subtitle = (t.version or '')
title = (t.title + ' '*bool(subtitle))
roff = S(queue + flags + duration).fullwidth()
subtitle = S(subtitle).fit(self.width - S(artist + title).fullwidth() - roff - 1)
artist = S(artist).fit(self.width - S(title + subtitle).fullwidth() - roff - 1)
title = S(title).fit(self.width - S(artist + subtitle).fullwidth() - roff - 1)
spacer = ' '*(self.width - S(artist + title + subtitle).fullwidth() - roff)
attrs = items[0][1]
color = (self._pair(t) if (attrs & curses.A_STANDOUT) else 0)
if (t.available is False): attrs |= curses.A_DIM
dim = curses.A_DIM*(not attrs & curses.A_STANDOUT)
items = [
(artist, attrs | color),
(title, attrs | color | curses.A_BOLD),
(subtitle, attrs | color | dim),
(spacer, attrs | color),
(queue, attrs | color),
(flags, attrs | color | dim),
(duration, attrs | color),
]
return (ret, items)
def select(self):
ret = super().select()
if (not ret):
try: t = self.l[self.n]
except IndexError: pass
else:
if (isinstance(t, yandex_music.Track)):
self.app.setPlaylist(self.l, self.n, self.pl_pos_min)
self.app.playTrack()
ret = True
elif (isinstance(t, yandex_music.Playlist)):
self.app.win.addView(AudiosView(playlist=pl, autoplay=True))
ret = True
return ret
def load(self):
ret = super().load()
if (not ret):
if (not self.l):
if (self.playlist is None): self.playlist = self.app.favourites
try: tracks = sum(self.playlist.volumes, start=[])
except AttributeError: tracks = self.playlist.fetch_tracks()
self.l += [(i.track if (isinstance(i, yandex_music.TrackShort)) else i) or i.fetch_track() for i in tracks]
if (self.autoplay and len(self.l) == 1): self.select(); self.autoplay = False
self.l.append(self.LoadItem(False))
return ret
def reload(self, cleared: bool = False):
super().reload(cleared)
self.playlist = None
self.app.clear_cache()
class ArtistsView(SCSelectingListView):
@staticmethod
def _cover_uri(artist: yandex_music.Artist):
if (not isinstance(artist, yandex_music.Artist)): return None
return artist.cover.uri
def item(self, i):
ret, items = super().item(i)
if (not ret):
if (isinstance(a := self.l[i], yandex_music.Artist)):
flags = '' #" ♥ "*self.app.is_liked(a) + " 🛇 "*self.app.is_disliked(a)).lstrip()
duration = str(max(a.counts.to_dict().values()))
if (flags): duration = (' ' + duration)
artist = (a.name + ' ')
subtitle = " · ".join(a.genres)
roff = S(flags + duration).fullwidth()
subtitle = S(subtitle).fit(self.width - S(artist).fullwidth() - roff - 1)
artist = S(artist).fit(self.width - S(subtitle).fullwidth() - roff - 1)
spacer = ' '*(self.width - S(artist + subtitle).fullwidth() - roff)
attrs = items[0][1]
color = (self._pair(a) if (attrs & curses.A_STANDOUT) else 0)
if (a.available is False): attrs |= curses.A_DIM
dim = curses.A_DIM*(not attrs & curses.A_STANDOUT)
items = [
(artist, attrs | color),
(subtitle, attrs | color | dim),
(spacer, attrs | color),
(flags, attrs | color | dim),
(duration, attrs | color | dim),
]
return (ret, items)
class SearchView(AudiosView, AlbumsView, ArtistsView, YMMenuItem):
class SearchPopupView(SCView):
transparent = True
class SearchBox(curses.textpad.Textbox):
def __init__(self, *args, complete=None, **kwargs):
super().__init__(*args, **kwargs)
if (complete is not None): self.complete = complete
self.result = str()
def _insert_printable_char(self, ch: SCKey):
self.result += ch.ch
self._update_max_yx()
y, x = self.win.getyx()
backyx = None
while (y < self.maxy or x < self.maxx):
if (self.insert_mode): oldch = SCKey(self.win.inch())
try: self.win.addch(ch.ch)
except curses.error: pass
if (not self.insert_mode or not oldch.ch.isprintable()): break
ch = oldch
y, x = self.win.getyx()
if (backyx is None): backyx = y, x
if (backyx is not None): self.win.move(*backyx)
def complete(self, result):
return result
def do_command(self, ch):
self.lastcmd = ch
ch = SCKey(ch)
self._update_max_yx()
y, x = self.win.getyx()
if (ch == curses.ascii.SOH): # ^A
self.win.move(y, 0)
elif (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.ascii.DEL, curses.KEY_BACKSPACE)):
self.result = self.result[:-1]
if (x > 0): self.win.move(y, x-1)
elif (y == 0): pass
elif (self.stripspaces): self.win.move(y-1, self._end_of_line(y-1))
else: self.win.move(y-1, self.maxx)
if (ch in (curses.ascii.BS, curses.ascii.DEL, curses.KEY_BACKSPACE)): self.win.delch()
elif (ch == curses.ascii.EOT): # ^D
self.win.delch()
elif (ch == curses.ascii.ENQ): # ^E
if (self.stripspaces): self.win.move(y, self._end_of_line(y))
else: self.win.move(y, self.maxx)
elif (ch in (curses.ascii.ACK, curses.KEY_RIGHT)): # ^F
if (x < self.maxx): self.win.move(y, x+1)
elif (y == self.maxy): pass
else: self.win.move(y+1, 0)
elif (ch == curses.ascii.BEL): # ^G
return 0
elif (ch == curses.ascii.NL): # ^J
if (self.maxy == 0): return 0
elif (y < self.maxy): self.win.move(y+1, 0)
elif (ch == curses.ascii.VT): # ^K
if (x == 0 and self._end_of_line(y) == 0): self.win.deleteln()
else:
self.win.move(y, x)
self.win.clrtoeol()
elif (ch == curses.ascii.FF): # ^L
self.win.refresh()
elif (ch in (curses.ascii.SO, curses.KEY_DOWN)): # ^N
if (y < self.maxy):
self.win.move(y+1, x)
if (x > self._end_of_line(y+1)): self.win.move(y+1, self._end_of_line(y+1))
elif (ch == curses.ascii.SI): # ^O
self.win.insertln()
elif (ch in (curses.ascii.DLE, curses.KEY_UP)): # ^P
if (y > 0):
self.win.move(y-1, x)
if (x > self._end_of_line(y-1)): self.win.move(y-1, self._end_of_line(y-1))
elif (ch in (curses.ascii.ESC, curses.KEY_EXIT)):
self.result = ''
return 0
elif (ch == curses.ascii.TAB):
self.set(self.complete(self.result))
elif (ch.ch.isprintable()):
if (y < self.maxy or x < self.maxx): self._insert_printable_char(ch)
return 1
def set(self, s):
self.win.move(0, 0)
self.win.clrtoeol()
self.result = ''
for i in s:
self._insert_printable_char(SCKey(i))
self.win.refresh()
def edit(self, validate=None):
while (True):
try: ch = self.win.get_wch()
except curses.error: continue # TODO FIXME
if (validate): ch = validate(ch)
if (not ch): continue
if (not self.do_command(ch)): break
self.win.refresh()
return self.result
SEARCH = "Поиск"
QUERY = "Запрос:"
def __init__(self, callback: callable):
super().__init__()
self.callback = callback
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
eh, ew = 5, 48
ey, ex = (self.height-eh)//2, (self.width-ew)//2
ep = curses.newwin(eh, ew, ey, ex)
ep.addstr(0, 0, '╭'+'─'*(ew-2)+'╮')
for i in range(1, eh-1): ep.addstr(i, 0, '│'+' '*(ew-2)+'│')
ep.addstr(eh-2, 0, '╰'+'─'*(ew-2)+'╯')
ep.addstr(1, 2, self.SEARCH.center(ew-4))
ep.addstr(2, 2, self.QUERY)
ep.refresh()
y, x = stdscr.getbegyx()
search = self.SearchBox(curses.newwin(y+1, x+ew-4-len(self.QUERY), ey+2, ex+3+len(self.QUERY)), complete=self.app.search_complete)
query = search.edit().strip()
self.callback(query)
self.die()
ret = True
return ret
menu_label = "Поиск"
search: '# yandex_music.Search'
query: str
def __init__(self, l=None, search=None):
if (l is None): l = []
super().__init__(l)
self.search = search
def init(self):
super().init()
self.app.win.addView(self.SearchPopupView(self.set_query))
self.to_load = False
def set_query(self, query: str):
if (not query):
self.die()
return
self.query = query
self.to_load = True
def load(self):
ret = SCLoadingSelectingListView.load(self)
if (not ret):
l = []
try:
if (self.search is None): self.search = self.app.ym.search(self.query)
#else: self.search = self.search.next_page() # TODO FIXME: TypeError
except (yandex_music.exceptions.BadRequestError): pass
else:
if (self.search.best is not None): l += [self.search.best.result, self.EmptyItem()]
if (self.search.playlists is not None): l += [i for i in self.search.playlists.results if i not in l]
if (self.search.albums is not None): l += [i for i in self.search.albums.results if i not in l]
if (self.search.tracks is not None): l += [i for i in self.search.tracks.results if i not in l]
self.l += l
self.l.append(self.LoadItem(False)) #bool(l))) # TODO FIXME
return ret
def reload(self, cleared: bool = False):
super().reload(cleared)
self.search = None
class MenuRecommsView(AudiosView):
station = 'user:onmywave'
from_ = 'user-onyourwave'
# public:
batch_id: str
def __init__(self, l=None):
if (l is None): l = [
AudiosView,
PlaylistsView,
AlbumsView,
SearchView,
self.EmptyItem(),
]
super().__init__(l)
self.pl_pos_min = len(self.l)
def item(self, i):
ret, items = super().item(i)
if (not ret):
if (isinstance(t := self.l[i], type) and issubclass(t, YMMenuItem)):
attrs = items[0][1]
text = S(f" * {t.menu_label}").fit(self.width)
items = [(text, attrs)]
return (ret, items)
def select(self):
ret = super(AudiosView, self).select()
if (not ret):
try: t = self.l[self.n]
except IndexError: pass
else:
if (self.is_empty(self.n)): pass
elif (isinstance(t, type) and issubclass(t, YMMenuItem)):
self.app.win.addView(t())
ret = True
elif (isinstance(t, yandex_music.Track)):
if (self.app.playlist is not self.l): self.app.ym.rotor_station_feedback_radio_started(self.station, self.from_)
self.app.setPlaylist(self.l, self.n, self.pl_pos_min, station=(self.station, self.batch_id))
self.app.playTrack(cache=False)
ret = True
return ret
def load(self):
ret = super(AudiosView, self).load()
if (not ret):
r = self.app.ym.rotor_station_tracks(self.station, queue=self.app.track.track_id if (self.app.track) else None)
for i in r.sequence:
if (i.track not in self.l): self.l.append(i.track)
self.l.append(self.LoadItem(True))
self.batch_id = r.batch_id
return ret
def reload(self, cleared: bool = False):
del self.l[self.pl_pos_min:]
super().reload(True)
self.n = self.pl_pos_min
class LyricsView(SCView):
transparent = True
text: str
t: int
def __init__(self, lyrics: yandex_music.Lyrics):
super().__init__()
self.lyrics = lyrics
def init(self):
super().init()
self.text = S(self.lyrics.full_lyrics)
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
eh, ew = self.height-2, self.width-4
self.t = max(0, min(self.t, self.text.wrap(ew-3).count('\n') - eh+4))
ep = stdscr.subpad(eh, ew, 2, 2)
ep.addstr(0, 0, '╭'+'─'*(ew-2)+'╮')
for i in range(1, eh-1): ep.addstr(i, 0, '│'+' '*(ew-2)+'│')
ep.addstr(eh-2, 0, '╰'+'─'*(ew-2)+'╯')
text = self.text.wrap(ew-3)
for ii, i in enumerate(text.split('\n')[self.t:eh-3 + self.t]):
ep.addstr(ii+1, 2, i)
return ret
def key(self, c):
if (c == curses.KEY_UP):
self.t -= 1
self.touch()
elif (c == curses.KEY_DOWN):
self.t += 1
self.touch()
else: return super().key(c)
return True
class ProgressView(SCView):
def __init__(self):
super().__init__()
self.paused = bool()
self.repeat = bool()
self.tm = str()
def init(self):
self.tm = time.strftime('%X')
def proc(self):
ret = super().proc()
if (not ret):
paused = (not self.app.p.is_playing() and self.app.p.will_play())
repeat = self.app.repeat
tm = time.strftime('%X')
if ((paused, repeat, tm) != (self.paused, self.repeat, self.tm)):
self.paused, self.repeat, self.tm = paused, repeat, tm
self.touch()
return ret
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
pl = self.app.p.get_length()
pt = max(0, self.app.p.get_time())
pp = min(1, self.app.p.get_position())
pgrstr = (self.app.strfTime(pt/1000), (self.app.strfTime(max(0, pl)/1000) if (pl != 0) else '--:--'), self.tm)
bar = Progress.format_bar(pp, 1, self.width - len(str().join(pgrstr))-4, border='')
icons = '↺'*self.repeat
if (icons): icons = ' '+icons
stdscr.addstr(0, 1, S(self.app.trackline).cyclefit(self.width-2 - len(icons), self.app.tl_rotate, start_delay=10).ljust(self.width-2 - len(icons))+icons, curses.A_UNDERLINE)
stdscr.addstr(1, 1, pgrstr[0], curses.A_BLINK*self.paused)
stdscr.addstr(1, 1+len(pgrstr[0]), '/'+pgrstr[1]+' │')
stdscr.addstr(1, 4+len(str().join(pgrstr[:2])), bar[:math.ceil(self.app.loaded*len(bar))], curses.color_pair(1))
stdscr.addstr(1, self.width-2 - len(pgrstr[-1]), '▏'+pgrstr[-1])
self.touch()
return ret
class LoginView(SCView):
AUTHORIZATION = "Авторизация (Яндекс)"
LOGIN = "Логин:"
PASSWORD = "Пароль:"
CAPTCHA = "Капча:"
ERROR = "Неизвестная ошибка"
transparent = True
def __init__(self, callback=None):
super().__init__()
self.callback = callback or noop
class TextBox(curses.textpad.Textbox):
def set(self, s):
self.do_command(curses.ascii.VT)
for i in s:
self._insert_printable_char(ord(i))
self.win.refresh()
class PasswordBox(TextBox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.result = str()
def _insert_printable_char(self, ch):
self.result += chr(ch)
return super()._insert_printable_char('*')
def do_command(self, ch):
if (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY_BACKSPACE)): self.result = self.result[:-1]
return super().do_command(ch)
def set(self, s):
self.result = ''
super().set(s)
def gather(self):
return self.result
def draw(self, stdscr):
global ym_login, ym_pw
ret = super().draw(stdscr)
if (not ret):
cap = None
l, p = ym_login, ub64(ym_pw)
try: t = self.app.auth.get_token(l, p)
except YMAuthCaptcha as ex: cap = ex
except YMAuthError: pass
else:
if (t is not None):
self.app.set_token(t)
self.callback()
self.die()
ret = True
return ret # XXX
eh, ew = 7, 48
ey, ex = (self.height-eh)//2, (self.width-ew)//2
ep = curses.newwin(eh, ew, ey, ex)
ep.addstr(0, 0, '╭'+'─'*(ew-2)+'╮')
for i in range(1, eh-1): ep.addstr(i, 0, '│'+' '*(ew-2)+'│')
ep.addstr(eh-2, 0, '╰'+'─'*(ew-2)+'╯')
ep.addstr(1, 2, self.AUTHORIZATION.center(ew-4))
ep.addstr(2, 2, self.LOGIN)
ep.addstr(3, 2, self.PASSWORD)
ep.addstr(4, 2, self.CAPTCHA, curses.A_DIM*(cap is None))
ep.refresh()
y, x = stdscr.getbegyx()
login = self.TextBox(curses.newwin(y+1, x+ew-4-len(self.LOGIN), ey+2, ex+3+len(self.LOGIN)))
login.set(l)
password = self.PasswordBox(curses.newwin(y+1, x+ew-4-len(self.PASSWORD), ey+3, ex+3+len(self.PASSWORD)))
password.set(p)
captcha = self.TextBox(curses.newwin(y+1, x+ew-4-len(self.CAPTCHA), ey+4, ex+3+len(self.CAPTCHA)))
while (True):
ep.addstr(2, 2, self.LOGIN, curses.A_BOLD); ep.refresh()
try: l = login.edit().strip()
finally: ep.addstr(2, 2, self.LOGIN)
ep.addstr(3, 2, self.PASSWORD, curses.A_BOLD); ep.refresh()
try: p = password.edit().strip()
finally: ep.addstr(3, 2, self.PASSWORD)
ep.addstr(4, 2, self.CAPTCHA, curses.A_BOLD if (cap is not None) else curses.A_DIM); ep.refresh()
if (cap is not None):
webbrowser.open(cap.image_url)
try: c = captcha.edit().strip()
finally: ep.addstr(4, 2, self.CAPTCHA)
cap = cap.with_answer(c)
try: t = self.app.auth.get_token(l, p, cap)
except YMAuthError as ex:
if (isinstance(ex, YMAuthCaptcha)): cap = ex
else: raise
ep.addstr(1, 2, S(str(ex) or self.ERROR).fit(ew-4).center(ew-4))
continue
else:
if (t is not None):
ym_login, ym_pw = l, b64(p)
break
self.app.set_token(t)
self.callback()
self.die()
ret = True
return ret
class HelpView(SCView):
transparent = True
def draw(self, stdscr):
ret = super().draw(stdscr)
if (not ret):
eh, ew = 18, 40
ep = stdscr.subpad(eh, ew, (self.height-eh)//2, (self.width-ew)//2)