-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.py
143 lines (115 loc) · 4.61 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
import requests
import datetime
from urllib.parse import urlencode
import base64
from config import CLIENT_ID,CLIENT_SECRET
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
class SpotifyAPI(object):
access_token = None
access_token_expires = datetime.datetime.now()
access_token_did_expire = True
client_id = None
client_secret = None
token_url = "https://accounts.spotify.com/api/token"
def __init__(self, client_id, client_secret, *args, **kwargs):
super().__init__(*args, **kwargs)
self.client_id = client_id
self.client_secret = client_secret
def get_client_credentials(self):
"""
Returns a base64 encoded string
"""
client_id = self.client_id
client_secret = self.client_secret
if client_secret == None or client_id == None:
raise Exception("You must set client_id and client_secret")
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
return client_creds_b64.decode()
def get_token_headers(self):
client_creds_b64 = self.get_client_credentials()
return {
"Authorization": f"Basic {client_creds_b64}"
}
def get_token_data(self):
return {
"grant_type": "client_credentials"
}
def perform_auth(self):
token_url = self.token_url
token_data = self.get_token_data()
token_headers = self.get_token_headers()
r = requests.post(token_url, data=token_data, headers=token_headers)
if r.status_code not in range(200, 299):
return False
data = r.json()
now = datetime.datetime.now()
access_token = data['access_token']
expires_in = data['expires_in'] # seconds
expires = now + datetime.timedelta(seconds=expires_in)
self.access_token = access_token
self.access_token_expires = expires
self.access_token_did_expire = expires < now
return True
spotify = SpotifyAPI(client_id, client_secret)
spotify.perform_auth()
access_token = spotify.access_token
headers = {
"Authorization": f"Bearer {access_token}"
}
GET_ARTIST_ENDPOINT = 'https://api.spotify.com/v1/artists/{id}'
SEARCH_ENDPOINT = 'https://api.spotify.com/v1/search'
RELATED_ARTISTS_ENDPOINT = 'https://api.spotify.com/v1/artists/{id}/related-artists'
TOP_TRACKS_ENDPOINT = 'https://api.spotify.com/v1/artists/{id}/top-tracks'
audio_features = []
def search_audio_features(id):
SEARCH_ENDPOINT = 'https://api.spotify.com/v1/audio-features/{}'
SEARCH_ENDPOINT = SEARCH_ENDPOINT.format(id)
#resp = spotify.search(q="artist:{}".format(name) + " track:{}".format(track), type="track")
resp = requests.get(SEARCH_ENDPOINT, headers = headers)
return resp.json()
# https://developer.spotify.com/web-api/get-artist/
def get_artist(artist_id):
url = GET_ARTIST_ENDPOINT.format(id=artist_id)
resp = requests.get(url,headers = headers)
print()
return resp.json()
# https://developer.spotify.com/web-api/search-item/
def search_by_artist_name(name):
myparams = {'type': 'artist'}
myparams['q'] = name
resp = requests.get(SEARCH_ENDPOINT, params=myparams,headers = headers)
return resp.json()
def search_by_artist_name_to_get_id(name):
myparams = {'type': 'artist'}
myparams['q'] = name
resp = requests.get(SEARCH_ENDPOINT, params=myparams,headers = headers)
resp = resp.json().get('artists').get('items')[0]
for v_k, v_v in resp.items():
if v_k == "id":
return v_v
# https://developer.spotify.com/web-api/get-related-artists/
def get_related_artists(artist_id):
url = RELATED_ARTISTS_ENDPOINT.format(id=artist_id)
resp = requests.get(url,headers = headers)
return resp.json()
# https://developer.spotify.com/web-api/get-artists-top-tracks/
def get_artist_top_tracks(artist_id, country='US'):
url = TOP_TRACKS_ENDPOINT.format(id=artist_id)
myparams = {'country': country}
resp = requests.get(url, params=myparams,headers = headers)
return resp.json()
def get_spotify_connnection_stauts():
if spotify.perform_auth():
print("Connected!")
return True
print("Please connect your Spotify account to login")
return False
PLAYLIST_ENDPOINT = "https://api.spotify.com/v1/playlists/{playlist_id}"
# https://developer.spotify.com/web-api/get-artists-top-tracks/
def get_playlist(playlist_id, country='US'):
url = PLAYLIST_ENDPOINT.format(playlist_id=playlist_id)
myparams = {'country': country}
resp = requests.get(url, params=myparams,headers = headers)
return resp.json()