-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
557 lines (407 loc) · 15.7 KB
/
functions.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
###################################
### Author: Gary McGovern ###
### File: functions.py ###
###################################
from OAuth import *
from server import run_server
import webbrowser
import time
import os.path
import requests
import subprocess
import threading
import wget
from bs4 import BeautifulSoup
def createThread(funcName, threadName, argsPassed=""):
thread = threading.Thread(target=funcName, name=threadName, args=(argsPassed))
thread.daemon = True
thread.start()
thread.join(1)
return thread
def auth():
responseType = "code"
redirect = "http://127.0.0.1:5000/"
scope = "user-read-private"
fullpath = '{0}?client_id={1}&response_type={2}&redirect_uri={3}&scope={4}'.format(
endPoints("auth"),
clientID,
responseType,
redirect,
scope
)
webbrowser.open(fullpath)
def endPoints(endpoint):
authBaseUrl = "https://accounts.spotify.com/"
apiBaseUrl = "https://api.spotify.com/"
ytBaseUrl = "https://www.googleapis.com/"
if endpoint == "":
fullUrl = authBaseUrl
elif endpoint == "auth":
fullUrl = '{0}authorize'.format(authBaseUrl)
elif endpoint == "token":
fullUrl = '{0}api/token'.format(authBaseUrl)
elif endpoint == "userData":
fullUrl = '{0}v1/me'.format(apiBaseUrl)
elif endpoint == "search":
fullUrl = '{0}v1/search?q='.format(apiBaseUrl)
elif endpoint == "artist":
fullUrl = '{0}v1/artists/'.format(apiBaseUrl)
elif endpoint == "track":
fullUrl = '{0}v1/tracks/'.format(apiBaseUrl)
elif endpoint == "album":
fullUrl = '{0}v1/albums/'.format(apiBaseUrl)
elif endpoint == "user":
fullUrl = '{0}v1/users/'.format(apiBaseUrl)
elif endpoint == "artistTopTracks":
fullUrl = '{0}v1/artists/idhere/top-tracks'.format(apiBaseUrl)
elif endpoint == "artistAlbums":
fullUrl = '{0}v1/artists/idhere/albums'.format(apiBaseUrl)
elif endpoint == "albumTracks":
fullUrl = '{0}v1/albums/idhere/tracks'.format(apiBaseUrl)
elif endpoint == "artistRelated":
fullUrl = '{0}v1/artists/idhere/related-artists'.format(apiBaseUrl)
elif endpoint == "recentTrack":
fullUrl = '{0}v1/me/player/recently-played'.format(apiBaseUrl)
elif endpoint == "currentTrack":
fullUrl = '{0}v1/me/player/play'.format(apiBaseUrl)
elif endpoint == "featPlaylists":
fullUrl = '{0}v1/browse/featured-playlists'.format(apiBaseUrl)
elif endpoint == "newReleases":
fullUrl = '{0}v1/browse/new-releases'.format(apiBaseUrl)
elif endpoint == "recomByTrack":
fullUrl = '{0}v1/recommendations?&seed_tracks='.format(apiBaseUrl)
elif endpoint == "recomByArtist":
fullUrl = '{0}v1/recommendations?&seed_artists='.format(apiBaseUrl)
elif endpoint == "youtube":
fullUrl = '{0}youtube/v3/'.format(ytBaseUrl)
else:
fullUrl = ""
print("Unknown Endpoint!")
return fullUrl
# this feature on spotify's api is in beta, so may not actually work
# premium is also required. I'll use a local file to save prev/currentTrack.
def setCurrentTrack(trackID, trackName=""):
token = grabToken('token')
searchRes = requests.get(
'{0}&context_uri:"spotify:track:{1}"'.format
(
endPoints("currentTrack"),
trackID
),
headers={'Authorization': 'Bearer {0}'.format(token)})
if not searchRes.status_code == 204: # it didn't work or some error occurred
prevTrackFile = open(os.path.join('data', "prevTrack.txt"), 'w')
prevTrackFile.write("{0},{1}".format(trackID, trackName))
prevTrackFile.close()
def search(type, query, limit=20, offset=0):
token = grabToken('token')
searchRes = requests.get(
'{0}{1}&type={2}&limit={3}&offset={4}'.format
(
endPoints("search"),
query,
type,
limit,
offset
),
headers={'Authorization': 'Bearer {0}'.format(token)})
# check if token is still valid, if not refresh and try again
if searchRes.status_code == 401:
refreshToken()
token = grabToken('token')
searchRes = requests.get(
'{0}{1}&type={2}&limit={3}&offset={4}'.format
(
endPoints("search"),
query,
type,
limit,
offset
),
headers={'Authorization': 'Bearer {0}'.format(token)})
jsonData = searchRes.json()
results = jsonData['{0}s'.format(type)]['items']
nameResult = []
idResult = []
artistResult = []
artistIDResult = []
userIdResult = []
for result in results:
nameResult.append(result['name'])
idResult.append(result['id'])
if type == 'playlist':
userIdResult.append(result['owner']['id'])
if type == 'track':
artistResult.append(result['artists'][0]['name'])
artistIDResult.append(result['artists'][0]['id'])
return nameResult, idResult, artistResult, artistIDResult, userIdResult
def getArtistBio(id):
url = "https://open.spotify.com/artist/{}/about".format(id)
request = requests.get(url)
html = BeautifulSoup(request.text, "lxml")
fullBio = ""
for para in html.findAll("div", {"class", "bio-primary"}):
fullBio += para.text
for para in html.findAll("div", {"class", "bio-secondary"}):
fullBio += para.text
return fullBio
# using this for all data fetching(track, album etc), removing redundant functions
def getData(id, dataType, userID="", countryCode="IE"):
token = grabToken('token')
# playlist url is structured a bit differently
# needs a users id
if dataType == 'playlist':
endPointData = ('{0}{1}{2}{3}'.format
(
endPoints('user'),
userID,
'/playlists/',
id
))
elif dataType == 'artistAlbums' or dataType == 'artistRelated' \
or dataType == 'albumTracks' or dataType == 'artistTopTracks':
endPointDataTemp = ('{}'.format
(
endPoints(dataType)
))
endPointData = endPointDataTemp.replace("idhere", id)
if dataType == 'artistAlbums':
endPointData += "?&album_type=album"
elif dataType == 'artistTopTracks':
endPointData += "?country={}".format(countryCode)
elif dataType == "featPlaylists" or dataType == "newReleases":
endPointData = ('{0}?limit={1}'.format
(
endPoints(dataType),
"10"
))
else:
endPointData = ('{0}{1}'.format
(
endPoints(dataType),
id
))
item = requests.get(endPointData, headers={'Authorization': 'Bearer {0}'.format(token)})
# check if token is still valid, if not refresh and try again
if item.status_code == 401:
refreshToken()
item = requests.get(endPointData, headers={'Authorization': 'Bearer {0}'.format(token)})
jsonData = item.json()
if dataType == "track":
trackName = jsonData['name']
artistName = jsonData['artists'][0]['name']
trackImage = jsonData['album']['images'][1]['url']
popularity = jsonData['popularity']
artistID = jsonData['artists'][0]['id']
return trackName, artistName, trackImage, artistID, popularity
elif dataType == "artist":
artistName = jsonData['name']
artistImage = jsonData['images'][0]['url']
popularity = jsonData['popularity']
followers = jsonData['followers']['total']
artistID = jsonData['id']
return artistName, artistImage, popularity, artistID, followers
elif dataType == "album":
albumName = jsonData['name']
albumTrackTotal = jsonData['tracks']['total']
albumArtist = jsonData['artists'][0]['name']
artistId = jsonData['artists'][0]['id']
albumImage = jsonData['images'][0]['url']
return albumName, albumArtist, artistId, albumImage, albumTrackTotal
elif dataType == "playlist":
playlistName = jsonData['name']
playlistTrackTotal = jsonData['tracks']['total']
playlistImage = jsonData['images'][0]['url']
try:
user = jsonData['owner']['display_name']
except KeyError:
user = jsonData['owner']['id']
return playlistName, user, playlistImage, playlistTrackTotal
elif dataType == "artistAlbums":
results = jsonData['items']
albumImages = []
albumNames = []
albumIds = []
for result in results:
# remove duplicates
if result['name'] in albumNames:
pass
else:
albumImages.append(result['images'][0]['url'])
albumNames.append(result['name'])
albumIds.append(result['id'])
return albumImages, albumNames, albumIds
elif dataType == "artistRelated":
results = jsonData['artists']
artistNames = []
artistImages = []
artistIds = []
for result in results:
artistNames.append(result['name'])
artistImages.append(result['images'][0]['url'])
artistIds.append(result['id'])
return artistNames, artistImages, artistIds
elif dataType == "artistTopTracks":
results = jsonData['tracks']
trackNames = []
trackImages = []
trackIds = []
for result in results:
trackNames.append(result['name'])
trackImages.append(result['album']['images'][0]['url'])
trackIds.append(result['id'])
return trackNames, trackImages, trackIds
elif dataType == "featPlaylists":
results = jsonData['playlists']['items']
playlistNames = []
playlistImages = []
playlistIDs = []
for result in results:
playlistNames.append(result['name'])
playlistImages.append(result['images'][0]['url'])
playlistIDs.append(result['id'])
return playlistNames, playlistImages, playlistIDs
elif dataType == "newReleases":
results = jsonData['albums']['items']
newRelNames = []
newRelArtistNames = []
newRelArtistIds = []
newRelImages = []
newRelIDs = []
newRelType = [] # album or single
for result in results:
newRelArtistNames.append(result['artists'][0]['name'])
newRelArtistIds.append(result['artists'][0]['id'])
newRelNames.append(result['name'])
newRelImages.append(result['images'][0]['url'])
newRelIDs.append(result['id'])
newRelType.append(result['album_type'])
return newRelNames, newRelArtistNames, newRelImages, newRelIDs, newRelType, newRelArtistIds
elif dataType == "recomByTrack":
results = jsonData['tracks']
artistNames = []
artistIds = []
trackImages = []
trackNames = []
trackIds = []
for result in results:
artistNames.append(result['artists'][0]['name'])
artistIds.append(result['artists'][0]['id'])
trackImages.append(result['album']['images'][0]['url'])
trackNames.append(result['name'])
trackIds.append(result['id'])
return artistNames, trackImages, trackNames, trackIds, artistIds
elif dataType == "albumTracks":
results = jsonData['items']
trackNames = []
trackIds = []
trackArtists = []
for result in results:
trackNames.append(result['name'])
trackIds.append(result['id'])
trackArtists.append(result['artists'][0]['name'])
return trackNames, trackIds, trackArtists
def requestToken(redirect, clientID, clientSecret):
code = grabToken('code')
getToken = requests.post(endPoints("token"), data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect,
'client_id': clientID,
'client_secret': clientSecret
}
)
if (getToken.status_code == 200):
# extract token and expiry time
jsonData = getToken.json()
expires = jsonData['expires_in']
token = jsonData['access_token']
rToken = jsonData['refresh_token']
# store token
tokenFile = open(os.path.join('data', "token.txt"), 'w')
tokenFile.write(token)
tokenFile.close()
# store refresh token
refTokenFile = open(os.path.join('data', "reftoken.txt"), 'w')
refTokenFile.write(rToken)
refTokenFile.close()
else:
print('Failed to get token. Status code: {0}'.format(getToken))
def refreshToken():
rToken = grabToken('refresh')
getnewToken = requests.post(endPoints("token"), data={
'grant_type': 'refresh_token',
'refresh_token': rToken,
'client_id': clientID,
'client_secret': clientSecret
}
)
jsonData = getnewToken.json()
token = jsonData['access_token']
# store token
tokenFile = open(os.path.join('data', "token.txt"), 'w')
tokenFile.write(token)
tokenFile.close()
print('Valid Token Grabbed')
def grabToken(tokenType):
if tokenType == 'refresh':
name = 'refToken'
elif tokenType == 'token':
name = 'token'
else:
name = 'code'
tokenFile = open(os.path.join('data', "{0}.txt".format(name)), 'r')
token = tokenFile.read()
return token
def prevLogin():
if not (os.path.isfile(os.path.join('data', "token.txt"))):
refreshToken()
token = grabToken('token')
getUserData = requests.get(endPoints("userData"), headers={'Authorization': 'Bearer {0}'.format(token)}, timeout=1)
# check if token is still valid, if not refresh and try again
if getUserData.status_code == 401:
refreshToken()
token = grabToken('token')
getUserData = requests.get(endPoints("userData"), headers={'Authorization': 'Bearer {0}'.format(token)})
jsonData = getUserData.json()
userName = jsonData['display_name']
userID = jsonData['id']
# check if pic is available
try:
userPic = jsonData['images'][0]['url']
except Exception:
userPic = "http://" # give it no host to catch error
subscrip = jsonData['product']
if subscrip == 'open':
subscrip = 'free'
return userName, userPic, subscrip, userID
def deleteData():
if (os.path.isfile(os.path.join('data', "code.txt")) and
os.path.isfile(os.path.join('data', "reftoken.txt")) and
os.path.isfile(os.path.join('data', "token.txt"))):
os.remove(os.path.join('data', "code.txt"))
os.remove(os.path.join('data', "refToken.txt"))
os.remove(os.path.join('data', "token.txt"))
print('Deleted')
else:
print('No Files to Delete')
def login():
if (os.path.isfile(os.path.join('data', "code.txt")) and
os.path.isfile(os.path.join('data', "reftoken.txt")) and
os.path.isfile(os.path.join('data', "token.txt"))):
# check if we have a valid code
codeFile = open(os.path.join('data', "code.txt"), 'r')
code = codeFile.read()
if (len(code) == 0):
print('Invalid Authorization code')
print('Attempting to grab another')
auth()
refreshToken()
prevLogin()
else:
createThread(run_server, "server_thread")
auth()
while not (os.path.isfile(os.path.join('data', "code.txt"))):
print("Please Login to Continue!!")
time.sleep(5)
requestToken(redirect, clientID, clientSecret)