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('/')
class SpotifyApiClient(): def __init__(self, username, client_id, client_secret, redirect_uri, scope): # NOTE: # https://spotipy.readthedocs.io/en/2.18.0/#quick-start # client_id, client_secret, redirect_uri は環境変数を設定している場合、 # 引数を指定していなくても勝手に読み込んでくれるようになっているが、 # この挙動は時が経てば忘れてしまう気がするので明示的に指定する self.__auth_manager = SpotifyOAuth(username=username, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scope) self.__client = spotipy.Spotify(auth_manager=self.__auth_manager) def get_client(self): self.__auth_manager.get_access_token(as_dict=False) return self.__client def get_now_playing_track(self): track = self.get_client().current_user_playing_track() if track is None: return None title = track['item']['name'] singer = track['item']['artists'][0]['name'] return {'title': title, 'singer': singer}
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 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 get_access_token(self, code): """ Overrides get_access_token to store the token in an instance variable after creation. """ self.token_info = SpotifyOAuth.get_access_token(self, code) return self.token_info
def spotify_login(): # global session_counter # used for debugging # If a new user joins give random id to the user. if not session.get('uuid'): session['uuid'] = str(uuid.uuid4()) # session_counter +=1 # for debugging # print(f"Session counter: {session_counter}\n Session id: {session['uuid']}") # for debugging 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) # Authorization Code Flow Step 2 if request.args.get('code'): auth_code = request.args.get('code') # get the code from the url. sp_token = sp_oauth.get_access_token( auth_code) # use that code to get a token return redirect("/spotify_login") display = "Login to Spotify" if sp_oauth.get_cached_token(): # Authorization Code Flow Step 3 # NOTE here we can get data from the Spotify API. spotify = spotipy.Spotify(auth_manager=sp_oauth) display = "User: "******"display_name"] + " (Sign Out)" spotify_data = spotifyData.spotify_data(spotify) # pp(spotify_data) return render_template("spotify.html", display=display, playlists=spotify_data["playlists"]) return render_template("spotify_login.html", display=display)
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 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 add_to_playlists(): if request.method == "POST": req = request.get_json() print(req) print(type(req)) playlists = req["playlists"] tracks = req["tracks"] oauth = SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope=SCOPE, cache_path=CACHE_PATH, ) token = oauth.get_access_token() if token: sp = spotipy.Spotify(oauth_manager=oauth) for playlist in playlists: sp.user_playlist_add_tracks(sp.current_user()["id"], playlist, tracks, position=None) return {"added": "SUCCESS"} return {"added": "FAILURE"}
def display_page(pathname, fullpath): if pathname == '/login': return login_layout elif pathname == '/': return home_layout elif pathname == '/callback': if os.getenv('SPOTIFY_USERNAME'): 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) code = auth.parse_response_code(fullpath) # authenticate and get the access token try: # this is when the cache is written token = auth.get_access_token(code) return home_layout except spotipy.oauth2.SpotifyOauthError as e: return home_layout return index_page else: return index_page
def get_token(code, mode): key = keys() sp_oauth = SpotifyOAuth(key["uid"], key["usec"], uirs[mode], scope=scope) token_info = sp_oauth.get_access_token(code) if token_info: return token_info['access_token'] else: return None
def get_user_token(): """ Obtain an access token from Spotify """ oauth = SpotifyOAuth(username=os.environ.get("SPOTIPY_CLIENT_USERNAME"), scope='playlist-modify-private') user_token = oauth.get_access_token(as_dict=False, check_cache=True) return user_token
def getAuthorization(): clientID = os.environ.get('SPOTIPY_CLIENT_ID') clientSecret = os.environ.get('SPOTIPY_CLIENT_SECRET') uri = 'https://cschles.github.io/spotify-time-playlist/' scope = "user-read-playback-state user-top-read user-library-modify playlist-modify-private playlist-modify-public" auth=SpotifyOAuth(client_id=clientID,client_secret=clientSecret,redirect_uri=uri,scope=scope) tokenStr = auth.get_access_token() token = tokenStr['access_token'] return token
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 __init__(self): config = configparser.ConfigParser() config.read('config.cfg') scope = "user-read-playback-state,user-modify-playback-state,streaming" auth = SpotifyOAuth(client_id="2d0aa7b1e8e34e6db2bbcc9e35fd4db5", client_secret="", redirect_uri="http://google.com/", scope=scope) token = auth.get_access_token(as_dict=False) self.spotify = spotipy.Spotify(auth=token)
def get_token(self): sp_auth = SpotifyOAuth( client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri, scope=self.scope, ) try: token = sp_auth.get_cached_token() except: token = sp_auth.get_access_token() return token["access_token"]
def test3(): scope = "user-top-read" OAuth = SpotifyOAuth(scope=scope, redirect_uri='http://localhost:8080') token = OAuth.get_access_token() # receive the following warning # __main__:1: DeprecationWarning: You're using 'as_dict = True'.get_access_token will return the token string directly in future # versions. Please adjust your code accordingly, or use get_cached_token instead. # At this point, I am taken to the user authorization and grant access with the 'user-top-read' scope sp = spotipy.Spotify(auth_manager=OAuth) top_tracks = sp.current_user_top_tracks()
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 main(): spotify_user = os.environ.get("SPOTIPY_CLIENT_USERNAME") spotify_scope = "playlist-modify-private playlist-modify-public" oauth = SpotifyOAuth(username=spotify_user, scope=spotify_scope) user_token = oauth.get_access_token(as_dict=False) spotify = spotipy.Spotify(auth=user_token) id = "20TwbfnWDzKClpUOiCWQZs" playlist = spotify.playlist_items(playlist_id=id) ShowList = [ "https://open.spotify.com/show/1410RabA4XOqO6IV8p0gYF", # FT News Briefing "https://open.spotify.com/show/3dB6pl9tTWQiVlk96F4QOb", # Numbers by Barron's "https://open.spotify.com/show/5cOfqdkomvzyhPTR7n6KFa", # Thoughts on the Market "https://open.spotify.com/show/05uLjJxkVgQsRk8LWLCLpx", # Wall Street Breakfast klo 15 "https://open.spotify.com/show/1WOja8nmm4IuS9QK6rEyJI", # Marketplace Morning Report 3x päivässä "https://open.spotify.com/show/5D0lxDwv8xqBWgG2G95ysR", # Mad Money w/ Jim Cramer "https://open.spotify.com/show/4ysyyH8E37tOoes4jhLVAc", # Rahapodi "https://open.spotify.com/show/6A9Ckx3Mn521m1fAQXbYFD", # InderesPodi "https://open.spotify.com/show/7akL7A9jeT1QCJXtLnfk47", # Leadcast "https://open.spotify.com/show/08c8y61kd8eW68bNVzdb6H" # Stock Club ] oldlist = [] response = spotify.playlist_items(id, fields='items.track.uri') for x in range(len(response['items'])): try: asd = (response['items'][x]['track']['uri']) oldlist.append(asd) except TypeError: pass spotify.playlist_remove_all_occurrences_of_items(id, oldlist) print("MarketUpdate.py succesfully cleared old playlist tracks @ " + str(datetime.utcnow())) for i in range(len(ShowList)): print("Added playlist item: " + str(i) + " " + spotify.show_episodes(ShowList[i])['items'][0]['name'] + " at " + str(datetime.utcnow())) spotify.playlist_add_items( id, [spotify.show_episodes(ShowList[i])['items'][0]['uri']]) message = "Updated on: " + str(str(datetime.utcnow())) spotify.playlist_change_details(playlist_id=id, description=message) print(message) print( "--------------------------------------------------------------------------------" )
def login(): oauth = SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope=SCOPE, cache_path=CACHE_PATH, ) token = oauth.get_access_token() if token: return {"logged_in": "true"} else: return {"logged_in": "false"}
async def callback_for_spotify( code: str, spotipy_oauth: SpotifyOAuth = Depends(get_spotipy_oauth), db: Session = Depends(get_db)): """ Callback for spotify api Redirects to /dashboard on frontend Creates user if not exsists Returns pait of jwt tokens in cookies """ # auth_creds = requests.post( # 'https://accounts.spotify.com/api/token', # data={"grant_type": "authorization_code", "code": code, # "redirect_uri": os.getenv('REDIRECT_URL')}, # headers={ # "Authorization": # f"Basic YjMyMzcwNDExZTcwNGE1NzkxNDRlNTVmYjY3OTgyY2U6YmMwNzljOTllMjIzNDMxNWJjZjMxY2Y2NzE2ZTI3YmY="}).json() auth_creds = spotipy_oauth.get_access_token(code=code, check_cache=False) spotify_client = Spotify(auth=auth_creds["access_token"]) spotify_user = spotify_client.me() db_user = user_crud.get_user(db, spotify_id=spotify_user['id']) UserSchema = UserCreate if not db_user else UserUpdate if spotify_user and auth_creds: image = spotify_user['images'] user = UserSchema(email=spotify_user['email'], name=spotify_user['display_name'], image_url=image[0]['url'] if len(image) else '', spotify_id=spotify_user['id'], access_token=auth_creds['access_token'], refresh_token=auth_creds['refresh_token'], token_expires=datetime.now().timestamp() + float(auth_creds['expires_in'])) if db_user: user_crud.update_user(db, spotify_user['id'], cast(UserUpdate, user)) else: user_crud.create_user(db, cast(UserCreate, user)) frontend_url = os.getenv('FRONTEND_URL') if not spotify_user and not auth_creds: return RedirectResponse(url=f"{frontend_url}", status_code=500) access_token = create_access_token( data=TokenData(spotify_id=spotify_user['id'], spotify_expires=user.token_expires - 600).dict(), expires_delta=ACCESS_TOKEN_EXPIRE_MINUTES) return RedirectResponse(url=f"{frontend_url}/token?token={access_token}")
def index(): if not session.get('uuid'): # Step 1. Visitor is unknown, give random ID session['uuid'] = str(uuid.uuid4()) cache_handler = CacheFileHandler(cache_path=session_cache_path()) auth_manager = SpotifyOAuth( scope='user-read-private,playlist-read-private', cache_handler=cache_handler, show_dialog=True) if request.args.get("code"): # Step 3. Being redirected from Spotify auth page auth_manager.get_access_token(request.args.get("code")) return redirect(url_for('index')) if not auth_manager.validate_token(cache_handler.get_cached_token()): # Step 2. Display sign in link when no token return render_template('index.html') # Step 4. Signed in, display data sp = spotipy.Spotify(auth_manager=auth_manager) username = sp.me()['display_name'] return render_template('index.html', username=username)
def complete_auth(): auth_code = request.args.get("code") auth_obj = SpotifyOAuth(os.environ.get("SPOTIPY_CLIENT_ID"), os.environ.get("SPOTIPY_CLIENT_SECRET"), REDIRECT_URL, scope="playlist-read-private") token_info = auth_obj.get_access_token(auth_code) client = spotipy.Spotify(auth=token_info["access_token"]) result = client.user_playlists("metalnut4") playlist_names = [ playlist_item["name"] for playlist_item in result["items"] ] return "<br />".join(playlist_names)
def get_spotify_token(code): cid = secrets.cid secret = secrets.secret SPOTIFY_REDIRECT_URI = secrets.spotifyredirect SCOPE = 'user-read-email playlist-modify-public streaming user-read-private user-read-playback-state user-modify-playback-state user-library-read user-library-modify user-read-currently-playing' # CacheDBHandler is a custom class you need to write to store and retrieve cache in the DB, in cachedb.py auth_manager = SpotifyOAuth(cid, secret, SPOTIPY_REDIRECT_URI, scope=SCOPE, cache_path=None) # ignore cache until we make it work token_info = auth_manager.get_access_token(code, check_cache=False) return token_info
def auth(): # Authenticate with Spotify scope = ' '.join([ 'user-read-email', 'playlist-read-private', 'playlist-modify-private', 'playlist-modify-public', 'user-modify-playback-state', 'user-library-read' ]) code = request.args.get('code') auth = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scope) token = auth.get_access_token(code)['access_token'] session["token"] = token return redirect("/home")
def get_tokens(url): #Client ID cid ='f694f6f7a1584567948f99d653a9d070' #Client Secret secret = '0e05c9eeee094a5d8d506d0435a18ee9' #For avaliable scopes see https://developer.spotify.com/web-api/using-scopes/ #Current scope allows for modifying playback. scope = 'streaming user-read-birthdate user-read-email user-read-private user-library-read user-library-modify user-read-playback-state user-modify-playback-state' #Once you run the script, copy and paste the link you are redirected to into the terminal. redirect_uri="http://localhost:3000/callback" sp = SpotifyOAuth(cid, secret, redirect_uri, state=None, scope=scope, cache_path=None, proxies=None) token = sp.get_access_token(url) return token
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 access_spotify(): auth = SpotifyOAuth(client_id=cid, client_secret=secret, redirect_uri=uri, cache_path=cache, scope=scope) session.clear() code = request.args.get('code') token_info = auth.get_access_token(code) session["token_info"] = token_info session['token_info'], authorized = get_token(session) session.modified = True if not authorized: return redirect('/') return spotipy.Spotify(auth=session.get('token_info').get('access_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