Initial commit

This commit is contained in:
Sasha MOREL 2021-01-10 18:56:16 +01:00
commit 1c38a7a37e
1 changed files with 68 additions and 0 deletions

68
spotify_shuffle.py Normal file
View File

@ -0,0 +1,68 @@
#!/usr/bin/python3 -B
# https://developer.spotify.com/console/
from urllib import request
from json import loads as json_read, dumps as json_write
from random import shuffle
from time import strftime
def get_or_post (token, url, data = None):
d = None
if type (data) == bytes:
d = data
elif type (data) == str:
d = data.encode ('UTF-8')
t = request.urlopen (request.Request (url, data = d, headers = {'Authorization': 'Bearer ' + token}))
return (json_read (t.read ()))
def get_user_id (token):
return (get_or_post (token, 'https://api.spotify.com/v1/me') ['id'])
def list_playlists (token):
r = {}
for i in get_or_post (token, 'https://api.spotify.com/v1/me/playlists') ['items']:
r [i ['id']] = i ['name']
return (r)
def read_playlist (token, id):
r = []
index = 0
limit = 100
while True:
count = 0
for i in get_or_post (token, 'https://api.spotify.com/v1/playlists/' + id + '/tracks?offset=' + str (index) + '&limit=' + str (limit)) ['items']:
r.append (i ['track'] ['uri'])
count += 1
index += limit
if count != limit:
break
return (r)
def create_playlist (token, name, description, tracks):
playlist_id = get_or_post (token, 'https://api.spotify.com/v1/users/' + get_user_id (token) + '/playlists', data = json_write ({'name': name, 'description': description, 'public': False})) ['id']
p = 0
limit = 100
while True:
t = tracks [p:p+limit]
get_or_post (token, 'https://api.spotify.com/v1/playlists/' + playlist_id + '/tracks', data = json_write ({'position': p, 'uris': t}))
if len (t) == limit:
p += limit
else:
break
def playlist_shuffle (token, playlist):
tracks = read_playlist (token, playlist)
shuffle (tracks)
create_playlist (token, list_playlists (token) [playlist] + ' - Shuffled ' + strftime ('%Y-%m-%d %H:%M:%S'), 'Shuffled playlist', tracks)
if __name__ == '__main__':
raise (NotImplementedError ('no CLI interface yet'))