-
Notifications
You must be signed in to change notification settings - Fork 1
/
Spotify.py
216 lines (188 loc) · 7.38 KB
/
Spotify.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
from __future__ import unicode_literals
import spotify
import logging
import threading
import platform
import random
log = logging.getLogger('root')
# log.setLevel(logging.DEBUG)
#
# stream = logging.StreamHandler(sys.stdout)
# stream.setLevel(logging.DEBUG)
#
# formatter = logging.Formatter('[%(asctime)s] %(levelname)8s %(module)15s: %(message)s')
# stream.setFormatter(formatter)
#
# log.addHandler(stream)
#
#logging.basicConfig(level=logging.DEBUG)
class Spotify:
def __init__(self):
self.end_of_track = threading.Event()
self.logged_in = threading.Event()
self.logged_out = threading.Event()
self.logged_out.set()
log.debug("Spawning spotify.Session()")
self.session = spotify.Session()
self.session.on(
spotify.SessionEvent.CONNECTION_STATE_UPDATED,
self.on_connection_state_changed)
self.session.on(
spotify.SessionEvent.END_OF_TRACK, self.on_end_of_track)
self.tracks = []
myPlatform = platform.system()
log.debug("Detecting platform")
try:
if myPlatform == 'Linux':
log.info("{0} platform detected; using ALSA".format(myPlatform))
self.audio_driver = spotify.AlsaSink(self.session)
else:
log.info("{0} platform detected; using PortAudio".format(myPlatform))
self.audio_driver = spotify.PortAudioSink(self.session)
except ImportError as e:
log.warning('No audio sink found; audio playback unavailable. Exception: {0}'.format(e.args))
# log.debug("spotify.Config()")
# self.config = spotify.Config()
# self.config.user_agent = 'Alarm Clock'
log.debug("Spotify event loop")
self.event_loop = spotify.EventLoop(self.session)
self.event_loop.start()
def on_connection_state_changed(self, session):
log.debug("on_connection_state_changed: ")
if session.connection.state is spotify.ConnectionState.LOGGED_IN:
log.debug("LOGGED_IN")
self.logged_in.set()
self.logged_out.clear()
#self.event_loop.stop()
elif session.connection.state is spotify.ConnectionState.LOGGED_OUT:
log.debug("LOGGED_OUT")
self.logged_in.clear()
self.logged_out.set()
#self.event_loop.start()
def on_end_of_track(self, session):
log.debug("on_end_of_track: ")
#self.session.player.play(False)
self.end_of_track.set()
self.play_uri(str(self.tracks.pop().link))
def login(self, username, password):
log.debug("login")
self.session.login(username,password, remember_me=True)
self.logged_in.wait(15)
def relogin(self):
log.debug("relogin")
"relogin -- login as the previous logged in user"
try:
self.session.relogin()
self.logged_in.wait(15)
except spotify.Error as e:
log.error(e)
def forget_me(self):
log.debug("forget_me")
"forget_me -- forget the previous logged in user"
self.session.forget_me()
def logout(self):
log.debug("logout")
"logout"
self.session.logout()
self.logged_out.wait(15)
def whoami(self):
log.debug("whoami")
"whoami"
if self.logged_in.is_set():
log.info(
'I am %s aka %s. You can find me at %s',
self.session.user.canonical_name,
self.session.user.display_name,
self.session.user.link)
else:
log.info(
'I am not logged in, but I may be %s',
self.session.remembered_user)
def play_uri(self, line):
log.debug("play_uri: {0}".format(line))
"play <spotify track uri>"
if not self.logged_in.is_set():
log.warning('You must be logged in to play')
return
try:
track = self.session.get_track(line)
track.load()
except (ValueError, spotify.Error) as e:
log.warning(e)
return
log.info('Loading track into player')
try:
self.session.player.load(track)
except spotify.error.LibError as e:
log.error("Exception: {0}".format(e.args))
return
log.info('Playing track')
self.end_of_track.clear()
self.session.player.play()
def pause(self):
log.info('Pausing track')
self.session.player.play(False)
def resume(self):
log.info('Resuming track')
self.session.player.play()
def stop(self):
log.info('Stopping track')
self.session.player.play(False)
self.session.player.unload()
def seek(self, seconds):
"seek <seconds>"
if not self.logged_in.is_set():
log.warning('You must be logged in to seek')
return
if self.session.player.state is spotify.PlayerState.UNLOADED:
log.warning('A track must be loaded before seeking')
return
self.session.player.seek(int(seconds) * 1000)
def search(self, query):
"search <query>"
if not self.logged_in.is_set():
log.warning('You must be logged in to search')
return
try:
result = self.session.search(query)
result.load()
except spotify.Error as e:
log.warning(e)
return
log.info(
'%d tracks, %d albums, %d artists, and %d playlists found.',
result.track_total, result.album_total,
result.artist_total, result.playlist_total)
log.info('Top tracks:')
for track in result.tracks:
log.info(
'[%s] %s - %s', track.link, track.artists[0].name, track.name)
def get_playlists(self):
log.debug("Number of playlists: {0}".format(len(self.session.playlist_container)))
for playlist in self.session.playlist_container:
try:
playlist_uri = playlist.load()
log.info("Name: {0} URI: {1}".format(playlist.name, playlist_uri))
except AttributeError as e:
log.info("Oops, encountered a folder of platlists. Not sure howto handle, so moving on: {0}".format(e.args))
def get_tracks_from_playlist(self, uri):
log.debug("play_playlist: {0}".format(uri))
playlist = self.session.get_playlist(uri)
playlist.load()
log.debug("{0} tracks loaded".format(len(playlist.tracks)))
for i in sorted(range(len(playlist.tracks)), key=lambda k: random.random()):
# log.debug("index: {0}".format(i))
# log.info("Fetching {0} from playlist and sending to player".format(playlist.tracks[i].name))
self.tracks.append(playlist.tracks[i])
return self.tracks
# this is a blocking function - do not use
def play_playlist(self, uri):
log.debug("play_playlist: {0}".format(uri))
playlist = self.session.get_playlist(uri)
playlist.load()
log.debug("{0} tracks loaded".format(len(playlist.tracks)))
for i in sorted(range(len(playlist.tracks)), key=lambda k: random.random()):
# log.debug("index: {0}".format(i))
# log.info("Fetching {0} from playlist and sending to player".format(playlist.tracks[i].name))
self.play_uri(str(playlist.tracks[i].link))
self.end_of_track.wait()