def get(self, request): now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) new_cache = str(uuid.uuid4()) print('New UUID: ' + new_cache) try: cache = request.session['cache_id'] print('cache exists') except KeyError: print('new cache') request.session['cache_id'] = new_cache cache = request.session['cache_id'] cache_path = spotify_cache_folder + cache print('cache_path: ' + cache_path) if os.path.exists(cache_path): print('cache file exists') else: print('cache file does not exist') scope = 'user-read-email, user-top-read' auth_manager = SpotifyOAuth(scope=scope, cache_path=cache_path, show_dialog=True) code = self.request.query_params.get('code') print(code) if code: print('code: ' + code) auth_manager.get_access_token(code=code) print('redirecting..') redirect_url = prod_url + '/success.html' return HttpResponseRedirect(redirect_to=redirect_url) if not auth_manager.get_cached_token(): url = {'url': auth_manager.get_authorize_url()} serializer = UrlSerializer(url) return Response(serializer.data, status=status.HTTP_200_OK) else: url = {'url': auth_manager.get_authorize_url()} serializer = UrlSerializer(url) return Response(serializer.data, status=status.HTTP_200_OK) return Response("ERROR", status=status.HTTP_400_BAD_REQUEST)
def spot_login(request): if 'cache_id' not in request.session: #create random cache request.session['cache_id'] = get_random_alphanumeric_string(14) auth_manager = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri='http://localhost:8000/login/', scope=scope, cache_path=get_cache_path( request.session['cache_id']), show_dialog=True) if 'code' in request.GET: print('Getting code') token = auth_manager.get_access_token(request.GET.get('code')) # print(token) return redirect('/') print(f'token: {auth_manager.get_cached_token()}') if not auth_manager.get_cached_token(): print('Checking for Cache') url = auth_manager.get_authorize_url() return redirect(url) spotify_object = spotipy.Spotify(auth_manager=auth_manager) print('redirecting to login') # return HttpResponse(f'<h2><a href="{url}">Sign in</a></h2>') # spot = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id= client_id, client_secret=client_secret)) return redirect('Login')
def __init__(self, args, key_path): """ Spotify API Constructor :param client_id: client id provided by Spotify :param client_secret: client secret provided by Spotify :param redirect_uri: redirect uri provided by Spotify :param sp: spotipy API handler. """ self.save_location = args.save_location self.song_format = args.format self.overwrite = args.overwrite self.verbose = args.verbose self.username = args.username self.scope = "playlist-read-private" with open(key_path) as json_file: data = json.load(json_file) self.client_id = data['SPOTIPY_CLIENT_ID'] self.client_secret = data['SPOTIPY_CLIENT_SECRET'] self.redirect_uri = data['SPOTIPY_REDIRECT_URI'] sp_oauth = SpotifyOAuth(scope=self.scope, username=self.username, client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) self.auth_url = sp_oauth.get_authorize_url() self.last_auth_url = " " self.sp = spotipy.Spotify(auth_manager=sp_oauth)
def index(request): if not request.session.get('uuid'): request.session['uuid'] = str(uuid.uuid4()) auth_manager = SpotifyOAuth( scope='user-read-currently-playing', cache_path=session_cache_path(request.session), show_dialog=True) if request.method == 'GET': if request.GET.get("code"): # Step 3. Being redirected from Spotify auth page request.session['token_info'] = auth_manager.get_access_token( request.GET.get("code")) return redirect(index) if not auth_manager.get_cached_token(): auth_url = auth_manager.get_authorize_url() return HttpResponse(f'<h2><a href="{auth_url}">Sign in</a></h2>') if auth_manager.is_token_expired(request.session.get('token_info')): request.session['token_info'] = auth_manager.refresh_access_token( request.session.get('token_info')) spotify = Spotify(auth_manager=auth_manager) request.session['username'] = spotify.me()['id'] request.session['token'] = auth_manager.get_cached_token() return redirect(visview, request.session.get('username'))
def spotifyLogin(): cache_handler = spotipy.cache_handler.CacheFileHandler( cache_path='data/.cache') auth_manager = SpotifyOAuth(client_id=os.environ["CLIENT_ID"], client_secret=os.environ["CLIENT_SECRET"], redirect_uri=request.host_url + "login", scope="user-modify-playback-state " "user-read-playback-state " "user-read-recently-played", cache_handler=cache_handler) if request.args.get("code"): # Step 3. Being redirected from Spotify auth page auth_manager.get_access_token(request.args.get("code")) loggingWrite("Logged In", "System") print("Need to login Redirecting") return redirect('/') if not auth_manager.validate_token(cache_handler.get_cached_token()): # Step 2. Display sign in link when no token auth_url = auth_manager.get_authorize_url() print("Need to login Redirecting") print("Redirect URL is: " + request.host_url + "login") loggingWrite("REDIRECT URL is: " + request.host_url + "login", "System") loggingWrite("Need to login Redirecting", "System") return redirect(auth_url) loggingWrite("Already Login Passing on", "System") return redirect('/')
async def read_login_url( spotipy_oauth: SpotifyOAuth = Depends(get_spotipy_oauth)): """ Get login url for SpotifyApi """ url = spotipy_oauth.get_authorize_url() return LoginUrl(login_url=url)
class SpotifyAuthenticator: def __init__(self): self.scopes = 'user-read-private user-read-email playlist-read-private playlist-read-collaborative ' \ 'user-top-read user-library-read' self.sp_oauth = None self.sp = None self._init_oauth( "0.0.0.0" ) # init with stand in redirect_uri so update_token_info can be called def _init_oauth(self, redirect_uri): self.sp_oauth = SpotifyOAuth( scope=self.scopes, client_id=os.getenv("SPOTIFY_CLIENT_ID"), client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"), redirect_uri=redirect_uri) return self.sp_oauth.get_authorize_url() def initialize_auth(self, request): redirect_uri = request.build_absolute_uri('/') + 'login' return HttpResponseRedirect(self._init_oauth(redirect_uri)) def get_initial_token_info(self, initial_token): return self.sp_oauth.get_access_token(initial_token) def update_token_info(self, token_info): if self.sp_oauth.is_token_expired(token_info): return self.sp_oauth.refresh_access_token( token_info["refresh_token"]) return token_info def connect_user(self, token_info): self.sp = Spotify(token_info['access_token']) return self.sp.current_user()
def test_get_authorize_url_shows_dialog_when_requested(self): oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR") url = oauth.get_authorize_url(show_dialog=True) parsed_url = urllibparse.urlparse(url) parsed_qs = urllibparse.parse_qs(parsed_url.query) self.assertTrue(parsed_qs['show_dialog'])
def login_user(request): spotify_oauth = SpotifyOAuth( settings.SPOTIPY_CLIENT_ID, settings.SPOTIPY_CLIENT_SECRET, settings.SPOTIPY_REDIRECT_URI, scope='user-read-email playlist-modify-public user-follow-modify') authorize_url = spotify_oauth.get_authorize_url() return HttpResponseRedirect(authorize_url)
def test_get_authorize_url_does_not_show_dialog_by_default(self): oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR") url = oauth.get_authorize_url() parsed_url = urllibparse.urlparse(url) parsed_qs = urllibparse.parse_qs(parsed_url.query) self.assertNotIn('show_dialog', parsed_qs)
def test_get_authorize_url_passes_state_from_func_call(self): state = "STATE" oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR", "NOT STATE") url = oauth.get_authorize_url(state=state) parsed_url = urllibparse.urlparse(url) parsed_qs = urllibparse.parse_qs(parsed_url.query) self.assertEqual(parsed_qs['state'][0], state)
def login(): global state global oauth state = generate_random_string(RANDOM_STRING_LENGTH) oauth = SpotifyOAuth( state=state, scope=scope, cache_path='./token_cache' ) return redirect(oauth.get_authorize_url())
def verify(): auth = SpotifyOAuth(client_id=cid, client_secret=secret, redirect_uri=uri, cache_path=cache, scope=scope) auth_url = auth.get_authorize_url() return redirect(auth_url)
def login(): # Obtém as credenciais da aplicação cliente (cadastrada no dashboard do Spotify Developers) cred = SpotifyClientCredentials() # Obtém o objeto de autenticação OAuth2 url = SpotifyOAuth(cred.client_id, cred.client_secret, environ['SPOTIPY_REDIRECT_URI'], scope=scope) # Obtém a URL de autorização do Spotify e redireciona o usuário para esta return redirect(url.get_authorize_url())
def login(): """ Routes user to unique authorization URL. Redirects back to app via redirect_uri """ auth_manager = SpotifyOAuth( client_id=app.config["SPOTIPY_CLIENT_ID"], client_secret=app.config["SPOTIPY_CLIENT_SECRET"], redirect_uri=app.config["SPOTIPY_REDIRECT_URI"], scope=app.config["SCOPE"]) url = auth_manager.get_authorize_url() # Code is the result of the redirect return redirect(url, code=302)
class SpotifyActions: def __init__(self, client_id, client_secret, scope, redirect_uri): self.sp_oauth = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scope) @staticmethod def create_playlist(party): sp = party.spotify return sp.user_playlist_create(user=party.user, name=party.party_name) @staticmethod def add_song_to_playlist(party, song_id): sp = party.spotify sp.user_playlist_add_tracks(user=party.user, playlist_id=party.playlist_id, tracks=[song_id]) def get_authorize_url(self): return self.sp_oauth.get_authorize_url() def get_access_token(self, code): return self.sp_oauth.get_access_token(code)["access_token"] @staticmethod def find_song(party, song_name, artist_name=None): sp = party.spotify search_results = sp.search(song_name) if artist_name: song_dict = list( filter( lambda x: x['album']['artists'][0]['name'] == artist_name, search_results['tracks']['items']))[0] return song_dict['id'] return search_results['tracks']["items"][0]["id"] @staticmethod def parse_link_to_uri(link): start = link.rindex('/') + 1 stop = link.index('?') track = link[start:stop] spotify_uri = "spotify:track:{}".format(track) return spotify_uri
def auth(request): if not request.session.get('uuid'): request.session['uuid'] = str(uuid.uuid4()) auth_manager = SpotifyOAuth( scope='user-read-currently-playing user-top-read', cache_path=session_cache_path(request.session), show_dialog=True) if request.GET.get('code'): auth_manager.get_access_token(request.GET.get('code')) return redirect('index') if not auth_manager.get_cached_token(): auth_url = auth_manager.get_authorize_url() return Response({"auth_url": auth_url}) spotify = Spotify(auth_manager=auth_manager) return Response({"name": spotify.me()["display_name"]})
def auth_page(): # hacky way to store token in database # 1. use a MemoryCacheHandler to temporarily store token in ram # 2. use the api to retrieve the username # 3. transfer the token data from MemoryCacheHandler to DatabaseCacheHandler # with username attached to the token tokenData = MemoryCacheHandler() oauth = SpotifyOAuth( scope=constant.SCOPE, cache_handler=tokenData, client_id=config.client_id, client_secret=config.client_secret, redirect_uri=config.redirect_uri + "/login" ) # ask the user for authorization here if ("code" not in request.args): return redirect(oauth.get_authorize_url()) else: # TODO: backend logic probably doesn't belong here # we got the code here, use it to create a token print("Response Code: " + request.args["code"]) try: # called for no reason other than to trigger a save_token_to_cache() # call inside the cache handler oauth.get_access_token(request.args["code"], as_dict=False) except SpotifyOauthError: return render_template("auth_fail.html", url=config.redirect_uri) # hacky database caching client = spotipy.Spotify(auth_manager=oauth) user = client.me()['id'] # create and store user in the Users table database.add_user(client.me()['id']) # transfer data from MemoryCacheHandler to DatabaseCacheHandler db = DatabaseCacheHandler(user) db.save_token_to_cache(tokenData.get_cached_token()) # create new playlist for user update_playlist(client) return render_template("auth_success.html") return render_template("auth_success.html")
def authorize_application(token_path, scopes): cached_data_path = os.path.join(os.path.split(__file__)[0], 'cached_data') if not os.path.isdir(cached_data_path): os.mkdir(cached_data_path) oauth = SpotifyOAuth(CLIENT_ID, APP_SECRET, REDIRECT_URI, cache_path=token_path, scope=scopes) authorization_url = oauth.get_authorize_url() webbrowser.open(authorization_url) authorization_response = input("Enter the full callback URL: ") code = oauth.parse_response_code(authorization_response) token = oauth.get_access_token(code) print("Authorization was successful!") return token
def get_token(username, client_id, client_secret, redirect_uri, scope): sp_oauth = SpotifyOAuth(username=username, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scope, cache_path=getenv("HOME") + "/.cache/soapify-" + username) token_info = sp_oauth.get_cached_token() token = None if not token_info: auth_url = sp_oauth.get_authorize_url() webbrowser.open(auth_url) pool = ThreadPool(processes=1) code = pool.apply_async(CallbackServer).get().get_token() token_info = sp_oauth.get_access_token(code) if token_info: token = token_info['access_token'] return token
def login(): if request.method == 'POST': try: sp_oauth = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=REDIRECT_URI, scope=scope, cache_path=session_cache_path(), show_dialog=True) # So if we have a token(which means we are logged in) # and the login button is clicked then we need to sign out if not sp_oauth.get_cached_token(): # Authorization Code Flow Step 1 auth_url = sp_oauth.get_authorize_url() return redirect(auth_url) return redirect("/sign_out") except TypeError: pass return redirect("spotify_login")
def get(self, request): new_cache = str(uuid.uuid4()) cache = request.session.get('cache_id', new_cache) cache_path = spotify_cache_folder + cache print('cache_path:' + cache_path) scope = 'user-read-email, user-top-read' auth_manager = SpotifyOAuth(scope=scope, cache_path=cache_path, show_dialog=True) code = self.request.query_params.get('code') if code: print('code: ' + code) auth_manager.get_access_token(code=code) print('redirecting..') return HttpResponseRedirect( redirect_to='http://localhost:8080/index3.html') if not auth_manager.get_cached_token(): auth_url = auth_manager.get_authorize_url() data = f'<h2><a href="{auth_url}">Sign in</a></h2>' return Response(data) spotify = spotipy.Spotify(auth_manager=auth_manager) user_result = spotify.current_user() display_name = user_result['display_name'] client_url = 'https://chopshop-client.herokuapp.com/' data = '<html><body><h1>Hello ' + display_name + '. You are connected to Spotify :) </h1>' data += f'<h2><a href="{client_url}">Now click here!</a></h2>' data += '</body></html>' return Response(data)
def authenticate(n_clicks, username): if n_clicks: # add spotify username to .env file if it's not already there if not os.getenv('SPOTIFY_USERNAME'): f = open('.env', 'a') f.write('\nSPOTIFY_USERNAME={}'.format(username)) f.close() load_dotenv() # Get clientID and clientSecret from .env file client_id = os.getenv("CLIENT_ID") client_secret = os.getenv("CLIENT_SECRET") user_id = os.getenv("SPOTIFY_USERNAME") scope = 'user-read-private user-read-playback-state user-modify-playback-state user-top-read user-library-read playlist-modify-public playlist-modify-private' auth = SpotifyOAuth(client_id, client_secret, 'http://localhost:8050/callback', cache_path=f".cache-{user_id}", scope=scope) return None, auth.get_authorize_url()
def spotify_login(request): assert isinstance(request, HttpRequest) scope = "user-read-private user-read-birthdate user-read-recently-played user-read-playback-state user-follow-read playlist-read-collaborative user-top-read" client_credentials_manager = SpotifyOAuth( client_id='e31546dc73154ddaab16538209d8526e', client_secret='f12c6904e491409bbc5834aaa86d14c0', scope=scope, redirect_uri='http://localhost:8000/spotify_login/') spotipy.Spotify(client_credentials_manager=client_credentials_manager) authorize_url = client_credentials_manager.get_authorize_url() if request.method == 'GET': if "code" in request.GET: code = request.GET.get("code") token = client_credentials_manager.get_access_token(code) token = token["access_token"] response = HttpResponseRedirect("/") response.set_cookie("SpotifyToken", token) return response else: return HttpResponseRedirect(authorize_url)
def spotify_connect(session_id, code=''): ''' Connect to the Spotify API using the token associated with the given session ID, generating one if it does not already exist. ''' token = None cache_path = CACHE + session_id sp_oauth = SpotifyOAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, scope=SCOPE, cache_path=cache_path) token_info = sp_oauth.get_cached_token() if token_info: token = token_info['access_token'] elif code: token_info = sp_oauth.get_access_token(code) token = token_info['access_token'] if token: return Spotify(token, requests_timeout=30, retries=1) else: return sp_oauth.get_authorize_url()
# Playlist counts LIMIT_SHORT = 10 LIMIT_MEDIUM = 25 LIMIT_LONG = 50 # Spotify API variables CLIENT_ID = os.getenv('SPOTIPY_CLIENT_ID', None) CLIENT_SECRET = os.getenv('SPOTIPY_CLIENT_SECRET', None) REDIRECT_URI = os.getenv('SPOTIPY_REDIRECT_URI', None) SCOPE = 'user-library-read user-read-recently-played user-top-read ' \ 'playlist-modify-private playlist-read-private ' \ 'playlist-read-collaborative user-read-private user-read-birthdate ' \ 'user-read-email' sp_oauth = SpotifyOAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, scope=SCOPE) auth_url = sp_oauth.get_authorize_url() # Flask setup PORT = os.getenv('SPOTIPY_PORT', 8888) SESSION_TYPE = 'filesystem' app = Flask(__name__) app.config.from_object(__name__) Session(app) @app.route("/") def index(): return 'My Spotipy App!'
token = token_info['access_token'] sp = spotipy.Spotify(auth=token) scope = 'playlist-modify-public' id = os.environ['ClientID'] secret = os.environ['ClientSecret'] # id = config.ClientID # secret = config.ClientSecret oauth = SpotifyOAuth(client_id=id, client_secret=secret, redirect_uri='http://localhost/', scope=scope) token_info = oauth.get_cached_token() if not token_info: auth_url = oauth.get_authorize_url() st.write(auth_url) response = st.text_input( 'Click the above link, then paste the redirect url here and hit enter: ' ) st.write( '*The BadAuth error below should go away after entering the redirect url' ) # response = input('Paste the above link into your browser, then paste the redirect url here: ') if response == "": time.sleep(5) code = oauth.parse_response_code(response) token_info = oauth.get_access_token(code) token = token_info['access_token'] sp = spotipy.Spotify(auth=token)
import pandas as pd # spotify authentication and initialization of client object client_id = '##########' client_secret = '#############' redirect_uri = '############' username = '******' scopes = 'playlist-modify-private' sp_oauth = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes) token_info = sp_oauth.get_cached_token() if not token_info: auth_url = sp_oauth.get_authorize_url(show_dialog=True) print(auth_url) response = input( 'Paste the above link into your browser, then paste the redirect url here: ' ) code = sp_oauth.parse_response_code(response) token_info = sp_oauth.get_access_token(code) token = token_info['access_token'] sp = spotipy.Spotify(auth=token) # refresh function def refresh():
class SpotifyAuthManager(): """ A class used to handle Spotify Oauth. Refreshable user authentication. Owned by Playlist & ArtistManager. Args: Instance Attributes Class Attributes: """ username = os.environ['SPOTIFY_USERNAME'] client_id = os.environ['SPOTIFY_CLIENT_ID'] client_secret = os.environ['SPOTIFY_CLIENT_SECRET'] scope = os.environ['SPOTIFY_SCOPE'] redirect_uri = os.environ['SPOTIFY_REDIRECT_URI'] def __init__(self, session=None): self.token_info = None self.response_code = None self.client_mgr = None self.session = session # use same session # self.session = session def create_client_mgr(self): """ Create SpotifyOauth object. Args: client_id client_secret redirect_uri scope cache_path """ cache_path = WindowsPath("__pycache__") / fr'.cache-{self.username}' self.client_mgr = SpotifyOAuth(self.client_id, self.client_secret, self.redirect_uri, scope=self.scope, cache_path=cache_path) return self def get_auth_token(self): """ Get oauth token from cache or prompt for new token. """ try: self.token_info = self.client_mgr.get_cached_token() logger.info( f"Token expires at {time.strftime('%c', time.localtime(self.token_info['expires_at']))}" ) return self # TODO: add specific exceptions except Exception: logger.info("No token in cache. Getting new token.", exc_info=True) auth_url = self.client_mgr.get_authorize_url() user_auth = self.session.get(auth_url).url response_code = input(f'Use Browser to authenticate: {user_auth}') code = self.client_mgr.parse_response_code(response_code) self.token_info = self.client_mgr.get_access_token(code) with open(self.client_mgr.cache_path, 'w') as f: f.write(json.dumps(self.token_info)) def refresh_auth_token(self): """ Refresh authentication token. Same spotify obect used throughout. How to call from owning classes. """ self.client_mgr.refresh_access_token(self.token_info['refresh_token']) logger.info( f"Token refreshed, expires at: {time.strftime('%c', time.localtime(self.token_info['expires_at']))}" ) def create_spotify(self): """ Create Spotify object for Authorization Code flow. Args: token, session, client_mgr """ try: auth_info = { 'auth': self.token_info['access_token'], 'requests_session': self.session, 'client_credentials_manager': self.client_mgr } return catch(spotipy.Spotify, auth_info) except TypeError: # Why TypeError? logger.error("Token error.", exc_info=True)
def main(): st.title('Nodata.tv Spotify Playlist Maker') st.header('By Xristos Katsaros') st.subheader( 'This app utilizes web scraping to find releases covered by Nodata.tv and places them in a Spotify playlist' ) st.header('Connect to Spotify') #defining spotify oauth parameters scope = 'playlist-modify-public' client_id = os.environ['client_id'] client_secret = os.environ['client_secret'] #initializing spotify oauth oauth = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri='http://localhost:8080/', scope=scope) auth_url = oauth.get_authorize_url() st.write(auth_url) response = st.text_input( 'Click the link above, then copy the URL from the new tab, paste it here, and press enter: ' ) #defining variables genres = pickle.load(open('genres.pkl', 'rb')) years = list(range(1990, 2022)) st.header('Select playlist preferences') st.text('Number of pages to scrape on the Nodata blog') pages = st.selectbox('Pages', list(range(1, 1800))) user_genre1 = st.selectbox('Genre 1', sorted(list(genres))) user_genre2 = st.selectbox('Genre 2', sorted(list(genres))) user_genres = [user_genre1, user_genre2] username = st.text_input('Spotify username') playlist_name = st.text_input('Name of new or existing playlist') year = str(st.selectbox('Year', sorted(years, reverse=True))) if st.button('Make playlist'): #connect to spotify code = oauth.parse_response_code(response) token_info = oauth.get_access_token(code) token = token_info['access_token'] sp = spotipy.Spotify(auth=token) #get the names of of all the user's playlists playlists = [ x['name'].lower() for x in sp.current_user_playlists()['items'] ] #determine playlist ID if playlist_name not in playlists: sp.user_playlist_create(user=username, name=playlist_name) #create a new playlist playlist_id = sp.current_user_playlists()['items'][0][ 'id'] #grab new playlist ID elif playlist_name in playlists: playlist_id = sp.current_user_playlists()['items'][playlists.index( playlist_name)]['id'] #find ID of existing playlist #the 2 main functions for scraping & searching spotify scrape_results = scraper.scrape(int(pages), user_genres, year) #scrapes nodata.tv spotify_results = search_spotify( scrape_results, sp) #inserts scraped results into search function confirm_and_add(spotify_results, username, playlist_id, sp)