-
Notifications
You must be signed in to change notification settings - Fork 0
/
sp.py
56 lines (49 loc) · 1.92 KB
/
sp.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
from spotipy import client
import spotipy.util as util
import logging
from configparser import ConfigParser
class SpotipyPlayer(object):
def __init__(self):
self.config = ConfigParser()
self.config.read('spotify.cfg')
credentials = dict(self.config['DEFAULT'])
token = util.prompt_for_user_token(**credentials)
self.sp = client.Spotify(auth=token)
self.device_id = self.__find_device()
self.sp.transfer_playback(device_id=self.device_id, force_play=False)
self.current = None
def __find_device(self):
devices = self.sp.devices()
if devices is None:
RuntimeError('No spotify devices found')
for dev in devices['devices']:
if dev['name'] == self.config['device']['name']:
return dev['id']
logging.warning('Found devices: ' + str(devices))
raise NameError(
'Could not detect device "' + DEVICE_NAME + '"'
)
def get_tracks(self, playlist):
if playlist == 'songs':
results = self.sp.current_user_saved_tracks(limit=50)
else:
results = self.sp.user_playlist_tracks(user='henhuy', playlist_id=playlist)
songs = []
while True:
for item in results['items']:
songs.append(item['track']['uri'])
results = self.sp.next(results)
if results is None or results['next'] is None:
break
return songs
def play(self, playlist='songs'):
if self.current is None or self.current != playlist:
songs = self.get_tracks(playlist)
self.sp.start_playback(device_id=self.device_id, uris=songs)
self.current = playlist
else:
self.sp.start_playback(device_id=self.device_id)
def stop(self):
self.sp.pause_playback(device_id=self.device_id)
def next(self):
self.sp.next_track(self.device_id)