forked from marcdjulien/spotify-terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.py
1435 lines (1155 loc) · 50.1 KB
/
state.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 os
import pickle
import re
import time
from threading import Lock, Thread, Event
import unicurses as uc
from model import (
UnableToFindDevice,
NoneTrack,
Playlist,
PlayerAction,
Track,
Device,
Option
)
import common
logger = common.logging.getLogger(__name__)
class SpotifyState(object):
"""Represents the programs internal state of Spotify and menus.
User input will alter this state.
"""
# Different states.
MAIN_MENU_STATE, \
SEARCH_MENU_STATE, \
DEVICE_MENU_STATE, \
LOAD_STATE, \
EXIT_STATE, \
ADD_TO_PLAYLIST_SELECT_PLAYLIST, \
ADD_TO_PLAYLIST_CONFIRM_PLAYLIST, \
SELECT_ARTIST = range(8)
# Attributes to save between runs.
PICKLE_ATTRS = [
"command_history",
"previous_tracks",
"current_context",
"current_device"
]
# Enums for repeat state.
REPEAT_OFF, REPEAT_CONTEXT, REPEAT_TRACK = range(3)
# List of backspace keys.
BACKSPACE_KEYS = [uc.KEY_BACKSPACE, 8]
# List of enter keys.
ENTER_KEYS = [uc.KEY_ENTER, 10, 13]
# List of keys for cancling.
CANCEL_KEYS = [uc.KEY_EXIT, 27] + BACKSPACE_KEYS
# How often to sync the player state.
SYNC_PLAYER_PERIOD = 60 * 5
# How often to sync the available devices.
SYNC_DEVICES_PERIOD = 1
def __init__(self, api, config):
self.lock = Lock()
"""Lock for the class."""
self.api = api
"""SpotifyApi object to make Spotify API calls."""
self.config = config
"""The Config parameters."""
self.sync_period = common.PeriodicCallback(self.SYNC_PLAYER_PERIOD,
self.sync_player_state)
"""Periodic for syncing the player."""
self.sync_devices = common.PeriodicCallback(self.SYNC_DEVICES_PERIOD,
self.sync_available_devices,
active=False)
"""Periodic for syncing the available devices."""
self.periodics = [
self.sync_period,
self.sync_devices
]
"""All Periodics."""
self.main_menu = ListCollection("main",
[List("user"),
List("tracks"),
List("player")])
self.search_menu = ListCollection("search",
[List("search_results")])
self.select_device_menu = ListCollection("select_device",
[List("devices")])
self.confirm_menu = ListCollection("confirm",
[List("confirm", header="Are you sure?")])
self.artist_menu = ListCollection("select_artist",
[List("artists", header="Select an artist")])
self.current_menu = self.main_menu
"""The current model that we are acting on."""
self.current_popup_menu = self.confirm_menu
self.previous_tracks = []
"""Keeps track of previously displayed Tracks."""
self.current_context = None
"""The currently playing context."""
self.current_device = UnableToFindDevice
"""The current Device."""
self.available_devices = []
"""The list of available devices."""
self.playing = False
"""Whether the play is playing or not."""
self.progress = None
"""Progress into the track."""
self.shuffle = False
"""Whether to shuffle or not."""
self.volume = 0
"""Volume of the player."""
self.repeat = self.REPEAT_CONTEXT
"""Whether to repeat or not. Default is context."""
self.currently_playing_track = NoneTrack
"""The currently playing track."""
self.command_cursor_i = 0
"""The cursor location of the command."""
self.command_query = []
"""The command being typed."""
self.command_history = []
self.command_history_i = 0
"""History of commands."""
self.prev_command = ["exit"]
"""The previous command that was executed."""
self.running = True
"""Whether we're running or not."""
self.commands = {
"search": self._execute_search,
"find": self._execute_find,
"volume": self._execute_volume,
"play": self._execute_play,
"pause": self._execute_pause,
"shuffle": self._execute_shuffle,
"repeat": self._execute_repeat,
"exit": self._execute_exit
}
"""Dictionary of commands and their execution functions."""
self.current_state = self.MAIN_MENU_STATE
"""Current state of the applicaiton."""
self.creating_command = False
"""Whether we're typing a command or not."""
self.futures = []
"""List of futures to execute."""
self.last_update_time = time.time()
"""The last time we were called to update."""
def save_state(self):
"""Save the state to disk."""
ps = {
attr_name: getattr(self, attr_name)
for attr_name in self.PICKLE_ATTRS
}
state_filename = common.get_file_from_cache(self.api.get_username(), "state")
with open(state_filename, "wb") as file:
logger.debug("Saving %s state", self.api.get_username())
pickle.dump(ps, file)
def load_state(self):
"""Load part of the state from disk."""
state_filename = common.get_file_from_cache(self.api.get_username(), "state")
if os.path.isfile(state_filename):
with open(state_filename, "rb") as file:
logger.debug("Loading %s state", self.api.get_username())
ps = pickle.load(file)
for attr in self.PICKLE_ATTRS:
setattr(self, attr, ps[attr])
def init(self):
# Get the User info.
self.user = self.api.get_user()
if not self.user:
print("Could not load user {}".format(self.api.get_username()))
exit(1)
# Initialize PlayerActions.
self.main_menu['player'].update_list([
PlayerAction("(S)", self._toggle_shuffle),
PlayerAction("<< ", self._play_previous),
PlayerAction("(P)", self._toggle_play),
PlayerAction(" >>", self._play_next),
PlayerAction("(R)", self._toggle_repeat),
PlayerAction(" --", self._decrease_volume),
PlayerAction(" ++", self._increase_volume),
])
self.confirm_menu['confirm'].update_list([Option("Yes"),
Option("No")])
# Get current player state.
player_state = self.sync_player_state()
# Get the users playlists.
playlists = self.api.get_user_playlists(self.user)
if not playlists:
print("Could not load playlists. Try again.")
exit(1)
playlists = list(playlists)
# Add the Saved tracks playlist.
saved = Playlist({
"name": "Saved",
"uri": common.SAVED_TRACKS_CONTEXT_URI,
"id": "",
"owner_id": self.api.get_id()
})
playlists.insert(0, saved)
self.main_menu['user'].update_list(tuple(playlists))
# Initialize track list.
if player_state:
context = player_state['context']
self._set_context(context)
else:
if not self.restore_previous_tracks(0):
logger.debug("Loading the Saved track list")
self._set_playlist(self.main_menu['user'][0])
def sync_player_state(self):
player_state = self.api.get_player_state()
if player_state:
self.currently_playing_track = Track(player_state['item']) \
if player_state['item'] else NoneTrack
self.playing = player_state['is_playing']
self.current_device = Device(player_state['device'])
self.volume = self.current_device['volume_percent']
self._set_player_repeat(player_state['repeat_state'])
self._set_player_shuffle(player_state['shuffle_state'])
duration = player_state['progress_ms']
if self.currently_playing_track and duration:
self.progress = [duration, self.currently_playing_track['duration_ms']]
return player_state
else:
self.progress = None
self.currently_playing_track = NoneTrack
self.current_device = UnableToFindDevice
def sync_available_devices(self):
self.available_devices = self.api.get_devices()
self.select_device_menu['devices'].update_list(self.available_devices,
reset_index=False)
def process_key(self, key):
if self.is_loading():
# In the loading state.
self._update_loading_state(key)
elif self.is_adding_track_to_playlist():
# Adding a Track to a Playlist
self._update_adding_track_to_playlist_state(key)
elif self.is_selecting_artist():
# Selecting an Artist
self._update_selecting_artist(key)
else:
# In the main screen.
self._update_main_state(key)
self._run_calcs()
# We probably just selected a Track, let's plan
# to re-sync in 5s.
if key in self.ENTER_KEYS:
self.sync_period.call_in(5)
def _update_loading_state(self, key):
# Get the current Future.
future = self.futures[0]
# If it's done, leave the LOAD_STATE.
# But if there are more Futures to execute, continue to run them.
if future.is_done():
self.futures.pop(0)
if not self.futures:
self.current_state = future.get_end_state() or self.MAIN_MENU_STATE
else:
self.futures[0].run()
def _update_adding_track_to_playlist_state(self, key):
if key:
logger.info(key)
if self.current_state == self.ADD_TO_PLAYLIST_SELECT_PLAYLIST:
if key == uc.KEY_UP:
self.main_menu["user"].decrement_index()
elif key == uc.KEY_DOWN:
self.main_menu["user"].increment_index()
elif key in self.CANCEL_KEYS:
self.track_to_add = None
self.playlist_to_add = None
self.current_state = self.MAIN_MENU_STATE
elif key in self.ENTER_KEYS:
self.playlist_to_add = self.main_menu.get_current_list_entry()
self.current_state = self.ADD_TO_PLAYLIST_CONFIRM_PLAYLIST
elif self.current_state == self.ADD_TO_PLAYLIST_CONFIRM_PLAYLIST:
if key == uc.KEY_UP:
self.confirm_menu["confirm"].decrement_index()
elif key == uc.KEY_DOWN:
self.confirm_menu["confirm"].increment_index()
elif key in self.CANCEL_KEYS:
self.track_to_add = None
self.playlist_to_add = None
self.current_state = self.MAIN_MENU_STATE
elif key in self.ENTER_KEYS:
entry = self.confirm_menu.get_current_list_entry()
if entry.get().lower() == "yes":
self._add_track_to_playlist(self.track_to_add, self.playlist_to_add)
else:
self.track_to_add = None
self.playlist_to_add = None
self.current_state = self.MAIN_MENU_STATE
def _update_selecting_artist(self, key):
if self.current_state == self.SELECT_ARTIST:
if key == uc.KEY_UP:
self.artist_menu["artists"].decrement_index()
elif key == uc.KEY_DOWN:
self.artist_menu["artists"].increment_index()
elif key in self.CANCEL_KEYS:
self.current_state = self.MAIN_MENU_STATE
elif key in self.ENTER_KEYS:
artist = self.artist_menu.get_current_list_entry()
if artist:
self._set_artist(artist)
self.current_state = self.MAIN_MENU_STATE
def _update_main_state(self, key):
if key == uc.KEY_LEFT:
if self.is_creating_command():
self.command_cursor_i -= 1
elif self.in_main_menu():
if self.main_menu.get_current_list().name == "player":
if self.main_menu.get_current_list().get_index() == 0:
self.main_menu.list_i = 0
else:
self.main_menu.get_current_list().decrement_index()
else:
self.main_menu.list_i = 0
elif key == uc.KEY_RIGHT:
if self.is_creating_command():
self.command_cursor_i += 1
elif self.in_main_menu():
if self.main_menu.get_current_list().name == "player":
self.main_menu.get_current_list().increment_index()
elif self.main_menu.get_current_list().name in ["user", "tracks"]:
self.main_menu.increment_list()
elif self.in_search_menu():
entry = self.search_menu.get_current_list_entry()
if entry['type'] == 'album':
self.current_state = self.MAIN_MENU_STATE
self._set_album(entry)
elif entry['type'] == 'artist':
albums = self.api.get_albums_from_artist(entry)
if albums:
self.search_menu['results'].update_list(albums)
elif key == uc.KEY_UP:
if self.is_creating_command():
if self.command_history:
self.command_history_i = common.clamp(self.command_history_i-1,
0,
len(self.command_history)-1)
self._set_command_query(self.command_history[self.command_history_i])
elif self.in_main_menu():
if self.main_menu.get_current_list().name == "player":
self.main_menu.decrement_list()
else:
self.main_menu.get_current_list().decrement_index()
elif self.in_search_menu() or self.in_select_device_menu():
self.current_menu.get_current_list().decrement_index()
elif key == uc.KEY_DOWN:
if self.is_creating_command():
if self.command_history:
self.command_history_i = common.clamp(self.command_history_i+1,
0,
len(self.command_history)-1)
self._set_command_query(self.command_history[self.command_history_i])
elif self.in_main_menu():
if self.main_menu.get_current_list().name == "player":
self.main_menu.increment_list()
elif self.main_menu.get_current_list().name == "tracks":
self.main_menu.get_current_list().increment_index()
else:
self.main_menu.get_current_list().increment_index()
elif self.in_search_menu() or self.in_select_device_menu():
self.current_menu.get_current_list().increment_index()
elif key in self.BACKSPACE_KEYS:
if self.is_creating_command():
if self.command_cursor_i > 0:
self.get_command_query().pop(self.command_cursor_i - 1)
self.command_cursor_i -= 1
else:
self.current_state = self.MAIN_MENU_STATE
self.creating_command = False
elif self.in_main_menu():
self.restore_previous_tracks()
elif self.in_search_menu():
self.current_state = self.MAIN_MENU_STATE
elif self.in_select_device_menu():
self.current_state = self.MAIN_MENU_STATE
elif key == uc.KEY_NPAGE:
if not self.is_creating_command():
self.current_menu.get_current_list().increment_index(15)
elif key == uc.KEY_PPAGE:
if not self.is_creating_command():
self.current_menu.get_current_list().decrement_index(15)
# ASCII character pressed
elif (0 <= key <= 256) or (key in self.config):
char = chr(key)
if self.is_creating_command():
if 32 <= key and key <= 126:
self.get_command_query().insert(self.command_cursor_i, char)
self.command_cursor_i += 1
elif key in self.ENTER_KEYS:
self._process_command(self.get_command_query())
return
elif key in [uc.KEY_EXIT, 27]:
if self.in_search_menu():
self.current_state = self.MAIN_MENU_STATE
elif self.in_select_device_menu():
self.current_state = self.MAIN_MENU_STATE
elif self.is_creating_command():
self.current_state = self.MAIN_MENU_STATE
elif char in ['/', ':', '"']:
# Start creating command
if not self.is_creating_command():
if char == '"':
self._set_command_query("\"\"")
self.command_cursor_i = 1
else:
self._set_command_query(char)
self.command_cursor_i = 1
self.creating_command = True
elif key == self.config.find_next:
if self.prev_command[0] in ["find"]:
i = int(self.prev_command[1])
command = self.prev_command
command[1] = str(i + 1)
self._process_command(" ".join(command))
elif key == self.config.find_previous:
if self.prev_command[0] in ["find"]:
i = int(self.prev_command[1])
command = self.prev_command
command[1] = str(i - 1)
self._process_command(" ".join(command))
elif key == self.config.add_track:
entry = self.current_menu.get_current_list_entry()
if entry['type'] == 'track':
self.track_to_add = entry
self.main_menu.set_current_list('user')
self.main_menu['user'].set_index(0)
self.current_state = self.ADD_TO_PLAYLIST_SELECT_PLAYLIST
elif key == self.config.show_devices:
self.current_state = self.DEVICE_MENU_STATE
self.sync_devices.activate()
elif key == self.config.refresh:
self.sync_player_state()
elif key == self.config.goto_artist:
entry = self.current_menu.get_current_list_entry()
if entry['type'] == 'track':
artists = entry['artists']
if len(artists) == 1:
self._set_artist(artists[0])
else:
self._set_choose_artist(artists)
elif key == self.config.current_artist:
entry = self.currently_playing_track
if entry:
artists = entry['artists']
if len(artists) == 1:
self._set_artist(artists[0])
else:
self._set_choose_artist(artists)
elif key == self.config.goto_album:
entry = self.current_menu.get_current_list_entry()
if entry['type'] == 'track':
album = entry['album']
self._set_album(album)
elif entry['type'] == 'album':
self._set_album(entry)
elif key == self.config.current_album:
entry = self.currently_playing_track
if entry:
album = entry['album']
self._set_album(album)
elif key == self.config.current_context:
state = self.api.get_player_state()
if state:
context = state['context']
self._set_context(context)
elif char == '\t':
if self.current_context and self.current_menu.get_current_list().name == "tracks":
if common.is_all_tracks_context(self.current_context):
artist = self.current_context['artist']
self._set_artist(artist)
elif self.current_context.get("type") == "artist":
self._set_artist_all_tracks(self.current_context)
elif key == self.config.play:
self._toggle_play()
elif key == self.config.next_track:
self._play_next()
elif key == self.config.previous_track:
self._play_previous()
elif self.config.is_volume_key(key):
config_param = self.config.get_config_param(key)
volume = 10*int(config_param.split("_")[1])
self._process_command("volume {}".format(volume))
elif key == self.config.volume_down:
self._process_command("volume {}".format(self.volume - 5))
elif key == self.config.volume_up:
self._process_command("volume {}".format(self.volume + 5))
elif key in self.ENTER_KEYS:
if self.in_search_menu():
entry = self.search_menu.get_current_list_entry()
if entry:
if entry['type'] == 'artist':
self._set_artist(entry)
elif entry['type'] == 'album':
self._set_album(entry)
elif entry['type'] == 'track':
self._play(entry, context=None)
self.current_state = self.MAIN_MENU_STATE
elif self.in_main_menu():
if self.main_menu.get_current_list().name == "user":
playlist = self.main_menu.get_current_list_entry()
if playlist:
self._set_playlist(playlist)
elif self.main_menu.get_current_list().name == "tracks":
entry = self.main_menu.get_current_list_entry()
if entry:
if entry['type'] == 'artist':
self._set_artist(entry)
elif entry['type'] == 'album':
self._set_album(entry)
elif entry['type'] == 'track':
self._play(entry, context=self.current_context)
elif self.main_menu.get_current_list().name == "player":
self.main_menu.get_current_list_entry().action()
elif self.in_select_device_menu():
new_device = self.select_device_menu.get_current_list_entry()
if new_device:
self._set_player_device(new_device, self.playing)
self.current_state = self.MAIN_MENU_STATE
else:
if key is not None:
logger.debug("Unregistered key: %d", key)
def _run_calcs(self):
"""Run any calculations that we need to do at the end of the update."""
self.command_cursor_i = common.clamp(self.command_cursor_i,
0,
len(self.get_command_query()))
# Run all Periodics.
for periodic in self.periodics:
periodic.update(time.time())
# Set our menu.
if self.in_search_menu():
self.current_menu = self.search_menu
elif self.in_select_device_menu():
self.current_menu = self.select_device_menu
else:
self.current_menu = self.main_menu
# Make sure sync_devices is only active when selecting a device.
if not self.in_select_device_menu():
if self.sync_devices.is_active():
self.sync_devices.deactivate()
# Set our popup menu.
if self.is_adding_track_to_playlist():
self.current_popup_menu = self.confirm_menu
elif self.is_selecting_artist():
self.current_popup_menu = self.artist_menu
# Calculate track progress.
time_delta = 1000*(time.time() - self.last_update_time)
if self.progress and self.playing:
self.progress[0] = self.progress[0] + time_delta
# Song is done. Let's plan to re-sync in 1 second.
percent = float(self.progress[0])/self.progress[1]
if percent > 1.0:
logger.debug("Reached end of song. Re-syncing in 2s.")
self.sync_period.call_in(2)
self.progress = None
# Save off this last time.
self.last_update_time = time.time()
def _process_command(self, command_input):
logger.debug("Processing command: %s", command_input)
# Convert everything to string first
if not isinstance(command_input, basestring):
command_input = "".join(command_input).strip()
if not command_input:
self.creating_command = False
return
# Convert special commands.
if command_input[0] == ":":
if command_input == ":":
self.creating_command = False
return
elif command_input.lower().startswith(":q"):
command_string = "exit"
else:
command_string = command_input[1::]
elif command_input[0] == '"':
if command_input == '"' or command_input == '""':
self.creating_command = False
return
else:
command_string = "search {}".format(command_input[1::])
if command_string[-1] == '"':
command_string = command_string[:-1]
elif command_input[0] == "/":
command_string = "find 0 {}".format(command_input[1::])
else:
command_string = command_input
# Get tokens
toks = command_string.split()
# Get the command.
command = toks[0]
# Execute the command if it exists.
if command not in self.commands:
logger.debug("%s is not a valid command", command)
else:
logger.debug("Final command: %s", toks)
# Get the arguments for the command.
command_args = toks[1::] if len(toks) > 1 else []
# Save as the last command.
self.prev_command = toks
# Execute the appropriate command.
self.commands[command](*command_args)
self.command_history.append(command_input)
self.command_history_i = len(self.command_history)
self.creating_command = False
def _execute_search(self, *query):
query = " ".join(query)
logger.debug("search %s", query)
results = self.api.search(("artist", "album", "track"), query)
if results:
self.search_menu["search_results"].update_list(results)
self.search_menu["search_results"].header = "Search results for \"{}\"".format(query)
else:
self.search_menu["search_results"].update_list([])
self.search_menu["search_results"].header = "No results found for \"{}\"".format(query)
self.current_state = self.SEARCH_MENU_STATE
def _execute_find(self, i, *query):
query = " ".join(query)
logger.debug("find:%s", query)
cur_list = self.current_menu.get_current_list()
found = []
for index, item in enumerate(cur_list):
if query.lower() in str(item).lower():
found.append(index)
if found:
self.current_menu.get_current_list().set_index(found[int(i) % len(found)])
def _execute_shuffle(self, state):
state = state.lower().strip()
state = True if state == "true" else False
self._set_player_shuffle(state)
self.api.shuffle(state)
def _execute_repeat(self, state):
state = state.lower().strip()
if state in ["off", "context", "track"]:
self._set_player_repeat(state)
self.api.repeat(state)
def _execute_volume(self, volume):
volume = common.clamp(int(volume), 0, 100)
if 0 <= volume and volume <= 100:
self.volume = volume
self.api.volume(self.volume)
def _execute_play(self):
self.playing = True
self._play(None, None)
def _execute_pause(self):
self.playing = False
self.api.pause()
def _execute_exit(self):
self.current_state = self.EXIT_STATE
def _play(self, track, context):
context_uri = None
uris = None
track_id = None
if track:
self.currently_playing_track = track
self.progress = [0, track['duration_ms']]
track_id = track['uri']
# The Saved Tracks playlist in Spotify doesn't have a Context.
# So we have to give the API a list of Tracks to play
# to mimic a context.
if context:
if context['uri'] == common.SAVED_TRACKS_CONTEXT_URI:
uris = [t['uri'] for t in
self.api.get_tracks_from_playlist(self.main_menu['user'][0])]
track_id = self.main_menu['tracks'].i
elif context.get('type') == 'artist':
uris = [s['uri']
for s in self.api.get_selections_from_artist(self.current_context)
if s['type'] == 'track']
track_id = self.main_menu['tracks'].i
elif common.is_all_tracks_context(context):
uris = [t['uri'] for t in self.main_menu['tracks'].list]
track_id = self.main_menu['tracks'].i
else:
context_uri = context['uri']
# If using a custom context, limit it to 750 tracks.
if uris:
n = 750
offset_i = max(track_id - (n/2) + 1, 0)
uris = uris[offset_i:offset_i + n]
track_id -= offset_i
self.api.play(track_id, context_uri, uris, self.current_device)
def _play_next(self):
def wait_and_sync():
time.sleep(2)
self.sync_player_state()
future = Future(target=self.api.next,
result=wait_and_sync,
progress=False)
self.execute_future(future)
def _play_previous(self):
def wait_and_sync():
time.sleep(2)
self.sync_player_state()
future = Future(target=self.api.previous,
result=wait_and_sync,
progress=False)
self.execute_future(future)
def _toggle_play(self):
if self.playing:
self._process_command("pause")
else:
self._process_command("play")
def _toggle_shuffle(self):
self._process_command("shuffle {}".format(not self.shuffle))
def _toggle_repeat(self):
self._process_command("repeat {}".format(
['off', 'context', 'track'][(self.repeat + 1) % 3]
))
def _decrease_volume(self):
self._process_command("volume {}".format(self.volume - 5))
def _increase_volume(self):
self._process_command("volume {}".format(self.volume + 5))
def _get_repeat_enum(self, repeat):
return {"off": self.REPEAT_OFF,
"track": self.REPEAT_TRACK,
"context": self.REPEAT_CONTEXT}[repeat]
def _add_track_to_playlist(self, track, playlist):
self.api.add_track_to_playlist(track, playlist)
self.track_to_add = None
self.playlist_to_add = None
def _set_playlist(self, playlist):
future = Future(target=(self.api.get_tracks_from_playlist, playlist),
result=(self._set_tracks, (playlist, playlist['name'])),
end_state=self.MAIN_MENU_STATE)
self.execute_future(future)
def _set_artist(self, artist):
future = Future(target=(self.api.get_selections_from_artist, artist),
result=(self._set_tracks, (artist, artist['name'])),
end_state=self.MAIN_MENU_STATE)
self.execute_future(future)
def _set_artist_all_tracks(self, artist):
future = Future(target=(self.api.get_all_tracks_from_artist, artist),
result=(self._set_tracks, (common.get_all_tracks_context(artist),
"All tracks from " + artist['name'])),
end_state=self.MAIN_MENU_STATE)
self.execute_future(future)
def _set_album(self, album):
future = Future(target=(self.api.get_tracks_from_album, album),
result=(self._set_tracks, (album, album['name'])),
end_state=self.MAIN_MENU_STATE)
self.execute_future(future)
def _set_context(self, context):
if context is None:
context = {
"type":"playlist",
"uri": common.SAVED_TRACKS_CONTEXT_URI
}
target_api_call = {
"artist": self.api.get_selections_from_artist,
"playlist": self.api.get_tracks_from_playlist,
"album": self.api.get_tracks_from_album,
common.ALL_ARTIST_TRACKS_CONTEXT_TYPE: self.api.get_all_tracks_from_artist,
}[context["type"]]
context = self.api.convert_context(context)
future = Future(target=(target_api_call, context),
result=(self._set_tracks, (context, context['name'])),
end_state=self.MAIN_MENU_STATE)
self.execute_future(future)
def _set_tracks(self, tracks, context, header):
with self.lock:
# Save the track listing.
self.previous_tracks.append((tracks, context, header))
# Set the new track listing.
self.current_context = context
self.main_menu['tracks'].update_list(tracks)
self.main_menu['tracks'].header = header
# Go to the tracks pane.
self.main_menu.set_current_list('tracks')
self.main_menu['tracks'].set_index(0)
def _set_choose_artist(self, artists):
self.artist_menu["artists"].update_list(artists)
self.artist_menu["artists"].set_index(0)
self.current_state = self.SELECT_ARTIST
def _set_player_device(self, new_device, play):
self.sync_player_state()
self.current_device = new_device
self.api.transfer_playback(new_device, play)
def _set_command_query(self, text):
self.command_query = list(text)
def _set_player_repeat(self, state):
self.repeat = self._get_repeat_enum(state)
self.main_menu['player'][4].title = "({})".format(['x', 'o', '1'][self.repeat])
def _set_player_shuffle(self, state):
self.shuffle = state
self.main_menu['player'][0].title = "({})".format(
{True: "S", False: "s"}[self.shuffle]
)
def restore_previous_tracks(self, i=1):
if len(self.previous_tracks) > i:
last = None
for _ in range(i+1):
last = self.previous_tracks.pop()
self._set_tracks(*last)
return True
else:
return False
def is_creating_command(self):
return self.creating_command
def in_search_menu(self):
return self.is_in_state(self.SEARCH_MENU_STATE)
def in_main_menu(self):
return self.is_in_state(self.MAIN_MENU_STATE)
def in_select_device_menu(self):
return self.is_in_state(self.DEVICE_MENU_STATE)
def is_loading(self):
return self.is_in_state(self.LOAD_STATE)
def is_adding_track_to_playlist(self):
return self.is_in_state(self.ADD_TO_PLAYLIST_SELECT_PLAYLIST,
self.ADD_TO_PLAYLIST_CONFIRM_PLAYLIST)
def is_selecting_artist(self):
return self.is_in_state(self.SELECT_ARTIST)
def is_running(self):
return not self.is_in_state(self.EXIT_STATE)
def is_in_state(self, *states):
return self.current_state in states
def get_cursor_i(self):
return self.command_cursor_i
def get_display_name(self):
return self.api.get_display_name()
def get_command_query(self):
return self.command_query
def get_currently_playing_track(self):
return self.currently_playing_track
def execute_future(self, future):
# If we're not already executing one, run it.
# Otherwise, it will be added to the queue and executed later.
logger.debug("Adding Future: %s", future)
self.futures.append(future)
if not self.is_loading():
self.current_state = self.LOAD_STATE