-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathspotify.py
381 lines (332 loc) · 12.8 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
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
import sys
import json
import socket
import spotipy
import asyncio
import webbrowser
from time import time
from spotipy import oauth2
from config import *
def listen_for_callback_code():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", int(redirect_uri.split(":")[-1])))
s.listen(1)
while True:
connection, address = s.accept()
buf = str(connection.recv(1024))
if len(buf) > 0:
break
start_code = buf.find("?code=") + 6
end_code = buf.find(" ", start_code)
if "&" in buf[start_code:end_code]:
end_code = buf.find("&")
return buf[start_code:end_code]
async def get_spotify_auth_code():
auth_url = sp_oauth.get_authorize_url()
webbrowser.open(auth_url)
async def async_get_auth_code():
task = asyncio.create_task(get_spotify_auth_code())
await task
return listen_for_callback_code()
def do_spotify_oauth():
try:
with open("token.json", "r") as fh:
token = fh.read()
token = json.loads(token)
except:
token = None
if token:
if int(time()) > token["expires_at"]:
token = sp_oauth.refresh_access_token(token["refresh_token"])
else:
authorization_code = asyncio.run(async_get_auth_code())
print(authorization_code)
if not authorization_code:
print(
"\n[!] Unable to authenticate to Spotify. Couldn't get authorization code"
)
sys.exit(-1)
token = sp_oauth.get_access_token(authorization_code)
if not token:
print("\n[!] Unable to authenticate to Spotify. Couldn't get access token.")
sys.exit(-1)
try:
with open("token.json", "w+") as fh:
fh.write(json.dumps(token))
except:
print("\n[!] Unable to to write token object to disk. This is non-fatal.")
return token
def get_all_playlists():
playlists_pager = spotify.user_playlists(user_id)
playlists = playlists_pager["items"]
while playlists_pager["next"]:
playlists_pager = spotify.next(playlists_pager)
playlists.extend(playlists_pager["items"])
return playlists
def create_playlist(playlist_name):
playlist = spotify.user_playlist_create(user_id, playlist_name)
return playlist["id"]
def get_playlist_id(playlist_name):
playlists = get_all_playlists()
for playlist in playlists:
if playlist["name"] == playlist_name:
return playlist["id"]
return None
def do_durations_match(source_track_duration, found_track_duration):
if source_track_duration == found_track_duration:
print("\t\t\t\t[+] Durations match")
return True
else:
print("\t\t\t\t[!] Durations do not match")
return False
def most_popular_track(tracks):
# Popularity does not always yield the correct result
high_score = 0
winner = None
for track in tracks:
if track["popularity"] > high_score:
winner = track["id"]
high_score = track["popularity"]
return winner
def best_of_multiple_matches(source_track, found_tracks):
counter = 1
duration_matches = [
0,
]
for track in found_tracks:
print("\t\t\t[+] Match {}: {}".format(counter, track["id"]))
if do_durations_match(source_track["duration_ms"], track["duration_ms"]):
duration_matches[0] += 1
duration_matches.append(track)
counter += 1
if duration_matches[0] == 1:
best_track = duration_matches.pop()["id"]
print(
"\t\t\t[+] Only one exact match with matching duration, going with that one: {}".format(
best_track
)
)
return best_track
# TODO: Popularity does not always yield the correct result
best_track = most_popular_track(found_tracks)
print(
"\t\t\t[+] Multiple exact matches with matching durations, going with the most popular one: {}".format(
best_track
)
)
return best_track
def search_for_track(track):
try:
# TODO: This is repetitive, can probably refactor but works for now
print(
"\n[+] Searching for track: {}{}by {} on {}".format(
track["name"],
" " if not track["mix"] else " ({}) ".format(track["mix"]),
", ".join(track["artists"]),
track["release"],
)
)
# Search with Title, Mix, Artists, and Release / Album
query = "{}{}{} {}".format(
track["name"],
" " if not track["mix"] else " {} ".format(track["mix"]),
" ".join(track["artists"]),
track["release"],
)
print("\t[+] Search Query: {}".format(query))
search_results = spotify.search(query)
if len(search_results["tracks"]["items"]) == 1:
track_id = search_results["tracks"]["items"][0]["id"]
print(
"\t\t[+] Found an exact match on name, mix, artists, and release: {}".format(
track_id
)
)
do_durations_match(
track["duration_ms"],
search_results["tracks"]["items"][0]["duration_ms"],
)
return track_id
if len(search_results["tracks"]["items"]) > 1:
print(
"\t\t[+] Found multiple exact matches ({}) on name, mix, artists, and release.".format(
len(search_results["tracks"]["items"])
)
)
return best_of_multiple_matches(track, search_results["tracks"]["items"])
# Not enough results, search w/o release
print(
"\t\t[+] No exact matches on name, mix, artists, and release. Trying without release."
)
# Search with Title, Mix, and Artists
query = "{}{}{}".format(
track["name"],
" " if not track["mix"] else " {} ".format(track["mix"]),
" ".join(track["artists"]),
)
print("\t[+] Search Query: {}".format(query))
search_results = spotify.search(query)
if len(search_results["tracks"]["items"]) == 1:
track_id = search_results["tracks"]["items"][0]["id"]
print(
"\t\t[+] Found an exact match on name, mix, and artists: {}".format(
track_id
)
)
do_durations_match(
track["duration_ms"],
search_results["tracks"]["items"][0]["duration_ms"],
)
return track_id
if len(search_results["tracks"]["items"]) > 1:
print(
"\t\t[+] Found multiple exact matches ({}) on name, mix, and artists.".format(
len(search_results["tracks"]["items"])
)
)
return best_of_multiple_matches(track, search_results["tracks"]["items"])
# Not enough results, search w/o mix, but with release
print(
"\t\t[+] No exact matches on name, mix, and artists. Trying without mix, but with release."
)
query = "{} {} {}".format(
track["name"], " ".join(track["artists"]), track["release"]
)
print("\t[+] Search Query: {}".format(query))
search_results = spotify.search(query)
if len(search_results["tracks"]["items"]) == 1:
track_id = search_results["tracks"]["items"][0]["id"]
print(
"\t\t[+] Found an exact match on name, artists, and release: {}".format(
track_id
)
)
do_durations_match(
track["duration_ms"],
search_results["tracks"]["items"][0]["duration_ms"],
)
return track_id
if len(search_results["tracks"]["items"]) > 1:
print(
"\t\t[+] Found multiple exact matches ({}) on name, artists, and release.".format(
len(search_results["tracks"]["items"])
)
)
return best_of_multiple_matches(track, search_results["tracks"]["items"])
# Not enough results, search w/o mix or release
print(
"\t\t[+] No exact matches on name, artists, and release. Trying with just name and artists."
)
query = "{} {}".format(track["name"], " ".join(track["artists"]))
print("\t[+] Search Query: {}".format(query))
search_results = spotify.search(query)
if len(search_results["tracks"]["items"]) == 1:
track_id = search_results["tracks"]["items"][0]["id"]
print(
"\t\t[+] Found an exact match on name and artists: {}".format(track_id)
)
do_durations_match(
track["duration_ms"],
search_results["tracks"]["items"][0]["duration_ms"],
)
return track_id
if len(search_results["tracks"]["items"]) > 1:
print(
"\t\t[+] Found multiple exact matches ({}) on name and artists.".format(
len(search_results["tracks"]["items"])
)
)
return best_of_multiple_matches(track, search_results["tracks"]["items"])
print("\t\t[+] No exact matches on name and artists.")
print("\t[!] Could not find this song on Spotify!")
return None
# TODO: better error handling
except:
print("Error when searching track")
return None
def track_in_playlist(playlist_id, track_id):
for track in get_all_tracks_in_playlist(playlist_id):
if track["track"]["id"] == track_id:
return True
return False
def add_tracks_to_playlist(playlist_id, track_ids):
if track_ids:
spotify.user_playlist_add_tracks(user_id, playlist_id, track_ids)
def get_all_tracks_in_playlist(playlist_id):
if playlist_id in playlist_track_cache:
return playlist_track_cache[playlist_id]
playlist_tracks_results = spotify.playlist(playlist_id, fields="tracks")
playlist_tracks_pager = playlist_tracks_results["tracks"]
playlist_tracks = playlist_tracks_pager["items"]
while playlist_tracks_pager["next"]:
playlist_tracks_pager = spotify.next(playlist_tracks_pager)
playlist_tracks.extend(playlist_tracks_pager["items"])
playlist_track_cache[playlist_id] = playlist_tracks
return playlist_track_cache[playlist_id]
def clear_playlist(playlist_id):
for track in get_all_tracks_in_playlist(playlist_id):
spotify.user_playlist_remove_all_occurrences_of_tracks(
user_id,
playlist_id,
[
track["track"]["id"],
],
)
def add_new_tracks_to_playlist(genre, tracks_dict):
persistent_top_100_playlist_name = "Beatporter: {} - Top 100".format(genre)
daily_top_10_playlist_name = "Beatporter: {} - Daily Top 10".format(genre)
print(
'[+] Identifying new tracks for playlist: "{}"'.format(
persistent_top_100_playlist_name
)
)
playlists = [
{
"name": persistent_top_100_playlist_name,
"id": get_playlist_id(persistent_top_100_playlist_name),
},
{
"name": daily_top_10_playlist_name,
"id": get_playlist_id(daily_top_10_playlist_name),
},
]
for playlist in playlists:
if not playlist["id"]:
print(
'\t[!] Playlist "{}" does not exist, creating it.'.format(
playlist["name"]
)
)
playlist["id"] = create_playlist(playlist["name"])
# Clear daily playlist
clear_playlist(playlists[1]["id"])
persistent_top_100_track_ids = list()
daily_top_10_track_ids = list()
track_count = 0
for track in tracks_dict:
track_id = search_for_track(track)
if track_id and not track_in_playlist(playlists[0]["id"], track_id):
persistent_top_100_track_ids.append(track_id)
if track_id and track_count < 10:
daily_top_10_track_ids.append(track_id)
track_count += 1
print(
'\n[+] Adding {} new tracks to the playlist: "{}"'.format(
len(persistent_top_100_track_ids), persistent_top_100_playlist_name
)
)
add_tracks_to_playlist(playlists[0]["id"], persistent_top_100_track_ids)
print(
'\n[+] Adding {} new tracks to the playlist: "{}"'.format(
len(daily_top_10_track_ids), daily_top_10_playlist_name
)
)
add_tracks_to_playlist(playlists[1]["id"], daily_top_10_track_ids)
playlist_track_cache = dict()
# Get authenticated to Spotify on import
sp_oauth = oauth2.SpotifyOAuth(
client_id, client_secret, redirect_uri, username=username, scope=scope
)
token_info = do_spotify_oauth()
spotify = spotipy.Spotify(auth=token_info["access_token"], requests_timeout=120)
user_id = spotify.me().get("id")