727cfc9a14
No real output to terminal yet, but spotify api works. mostly.
46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
import requests
|
|
import os
|
|
from datetime import datetime, timedelta
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
class SpotifyFactory():
|
|
def __init__(self):
|
|
self.token = None
|
|
self.valid_until = None
|
|
|
|
def token_valid(self):
|
|
if self.token and self.valid_until and (datetime.now() < self.valid_until):
|
|
return True
|
|
return False
|
|
|
|
def get_token(self):
|
|
if self.token_valid():
|
|
print("Token still valid")
|
|
return self.token
|
|
print("New token")
|
|
url = 'https://accounts.spotify.com/api/token'
|
|
headers = {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
'Authorization': 'Basic ' + os.getenv('SPOTIFY_ENCODED_ID')
|
|
}
|
|
data = {
|
|
'grant_type': 'client_credentials'
|
|
}
|
|
r = requests.post(url, headers=headers, data=data)
|
|
data = r.json()
|
|
self.token = data["access_token"]
|
|
self.valid_until = datetime.now() + timedelta(seconds=data["expires_in"]-300)
|
|
return self.token
|
|
|
|
def get_song_info(self, spotify_id):
|
|
token = self.get_token()
|
|
url = 'https://api.spotify.com/v1/tracks/' + spotify_id
|
|
headers = {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': 'Bearer ' + token
|
|
}
|
|
r = requests.get(url, headers=headers)
|
|
return r.json()
|