86 lines
2.3 KiB
Python
86 lines
2.3 KiB
Python
#!/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 unduplicate_list (tracks):
|
|
known = []
|
|
cur = 0
|
|
while cur < len (tracks):
|
|
if tracks [cur] in known:
|
|
del tracks [cur]
|
|
continue
|
|
known.append (tracks [cur])
|
|
cur += 1
|
|
|
|
|
|
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)
|
|
unduplicate_list (tracks)
|
|
shuffle (tracks)
|
|
create_playlist (token, list_playlists (token) [playlist] + ' - Shuffled ' + strftime ('%Y-%m-%d %H:%M:%S'), 'Shuffled playlist', tracks)
|
|
|
|
|
|
def playlist_unduplicate (token, playlist):
|
|
tracks = read_playlist (token, playlist)
|
|
unduplicate_list (tracks)
|
|
create_playlist (token, list_playlists (token) [playlist] + ' - Undiplicates', 'Non duplicated playlist', tracks)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise (NotImplementedError ('no CLI interface yet')) |