Very brittle command-line frontend

This commit is contained in:
Ritiek Malhotra
2020-04-11 22:03:47 +05:30
parent 14104e6870
commit 9afd14282a
16 changed files with 167 additions and 220 deletions

View File

@@ -4,52 +4,37 @@ from spotdl.authorize.exceptions import SpotifyAuthorizationError
import spotipy
import spotipy.oauth2 as oauth2
# This global_client is used to keep the last logged-in client
# This masterclient is used to keep the last logged-in client
# object in memory for for persistence. If credentials aren't
# provided when creating further objects, the last authenticated
# client object with correct credentials is returned when
# `AuthorizeSpotify().authorize()` is called.
global_client = None
masterclient = None
class AuthorizeSpotify(AuthorizeBase):
def __init__(self):
global global_client
self._client = global_client
class AuthorizeSpotify(spotipy.Spotify):
def __init__(self, client_id=None, client_secret=None):
global masterclient
def _generate_token(self, client_id, client_secret):
""" Generate the token. """
credentials = oauth2.SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret,
)
token = credentials.get_access_token()
return token
credentials_provided = client_id is not None \
and client_secret is not None
valid_input = credentials_provided or masterclient is not None
def authorize(self, client_id=None, client_secret=None):
no_credentials_provided = client_id is None and client_secret is None
not_valid_input = no_credentials_provided and self._client is None
if not_valid_input:
if not valid_input:
raise SpotifyAuthorizationError(
"You must pass in client_id and client_secret to this method "
"when authenticating for the first time."
)
if no_credentials_provided:
return self._client
try:
token = self._generate_token(client_id, client_secret)
except spotipy.SpotifyOauthError:
raise SpotifyAuthorizeError(
"Failed to retrieve token. Perhaps you provided invalid credentials?"
if masterclient:
# Use cached client instead of authorizing again
# and thus wasting time.
self.__dict__.update(masterclient.__dict__)
else:
credential_manager = oauth2.SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret
)
spotify = spotipy.Spotify(auth=token)
self._client = spotify
global global_client
global_client = spotify
return spotify
super().__init__(client_credentials_manager=credential_manager)
# Cache current client
masterclient = self