Ejemplo n.º 1
0
def _api_error(response):
    try:
        msg = response.json()['error']['message']
    except (ValueError, KeyError, TypeError):
        msg = 'unknown error'

    return spotipy.SpotifyException(response.status_code,
                                    -1,
                                    response.url + ':\n ' + msg,
                                    headers=response.headers)
Ejemplo n.º 2
0
def get_cached_token(username,
                     scope=None,
                     client_id=None,
                     client_secret=None,
                     redirect_uri=None,
                     cache_path=None):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor
        Parameters:
         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
    '''

    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:
            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = cache_path or ".cache-" + username
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, return an authorization url

    token_info = sp_oauth.get_cached_token()
    if not token_info:
        return (None, sp_oauth.get_authorize_url())
    else:
        return (token_info['access_token'], None)
Ejemplo n.º 3
0
def get_token():
    scope = 'playlist-modify-private'
    cache_path = '.spotify_cache'
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)
    token_info = sp_oauth.get_cached_token()
    if token_info:
        return token_info['access_token']
    else:
        raise spotipy.SpotifyException(550, -1, 'no credentials set')
Ejemplo n.º 4
0
def save_token_for_user_code(username, scope, code):

    client_id = os.getenv('SPOTIPY_CLIENT_ID')
    client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
    redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=".cache-" + username)

    token_info = sp_oauth.get_access_token(code)
    return token_info
Ejemplo n.º 5
0
def generate_token(code, scope):
    client_id = os.getenv('SPOTIPY_CLIENT_ID')
    client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')
    redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:
            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope)
    return sp_oauth.get_access_token(code)['access_token']
Ejemplo n.º 6
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None,
                          cache_path=None):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens

    '''

    if not client_id:
        client_id = os.getenv('SPOTIFY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIFY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = cache_path or ".cache-" + username
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        print('''

            User authentication requires interaction with your
            web browser. Once you enter your credentials and
            give authorization, you will be redirected to
            a url.  Paste that url you were directed to to
            complete the authorization.

        ''')
        auth_url = sp_oauth.get_authorize_url()
        try:
            import webbrowser
            webbrowser.open(auth_url)
            print("Opened %s in your browser" % auth_url)
        except:
            print("Please navigate here: %s" % auth_url)

        print()
        print()
        try:
            response = raw_input("Enter the URL you were redirected to: ")
        except NameError:
            response = input("Enter the URL you were redirected to: ")

        print()
        print()

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)
    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None
Ejemplo n.º 7
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None,
                          cache_path=None,
                          oauth_manager=None,
                          show_dialog=False):
    warnings.warn(
        "'prompt_for_user_token' is deprecated."
        "Use the following instead: "
        "    auth_manager=SpotifyOAuth(scope=scope)"
        "    spotipy.Spotify(auth_manager=auth_manager)", DeprecationWarning)
    """ prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
         - oauth_manager - Oauth manager object.
         - show_dialog - If true, a login prompt always shows

    """
    if not oauth_manager:
        if not client_id:
            client_id = os.getenv("SPOTIPY_CLIENT_ID")

        if not client_secret:
            client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

        if not redirect_uri:
            redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

        if not client_id:
            LOGGER.warning("""
                You need to set your Spotify API credentials.
                You can do this by setting environment variables like so:

                export SPOTIPY_CLIENT_ID='your-spotify-client-id'
                export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
                export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

                Get your credentials at
                    https://developer.spotify.com/my-applications
            """)
            raise spotipy.SpotifyException(550, -1, "no credentials set")

        cache_path = cache_path or ".cache-" + username

    sp_oauth = oauth_manager or spotipy.SpotifyOAuth(client_id,
                                                     client_secret,
                                                     redirect_uri,
                                                     scope=scope,
                                                     cache_path=cache_path,
                                                     show_dialog=show_dialog)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        code = sp_oauth.get_auth_response()
        token = sp_oauth.get_access_token(code, as_dict=False)
    else:
        return token_info["access_token"]

    # Auth'ed API request
    if token:
        return token
    else:
        return None
Ejemplo n.º 8
0
    def post(self):
        token = request.headers.get("API_Key", None)
        if not token:
            loggingWrite("No token provided", "System")
            return {'message': "No API Token Provided"}, 401
        if validateTokenValue(token):
            name = request.form.get("name", None)
            messageVal = request.form.get("message", None)
            try:
                if name and messageVal:
                    cache_handler = spotipy.cache_handler.CacheFileHandler(cache_path='data/.cache')
                    auth_manager = spotipy.oauth2.SpotifyOAuth(client_id=os.environ["CLIENT_ID"],
                                                               client_secret=os.environ["CLIENT_SECRET"],
                                                               redirect_uri=request.host_url + "login",
                                                               cache_handler=cache_handler)
                    if not auth_manager.validate_token(cache_handler.get_cached_token()):
                        loggingWrite("Need to login", "System")
                        return {'message': "Please Login to :" + request.host_url + "login"}, 309

                    sp = spotipy.Spotify(auth_manager=auth_manager)

                    message = messageVal
                    if message.startswith("!"):
                        temp = message[1:].strip().lower()
                        if temp != "!" and temp != "" and temp != "!!":
                            try:
                                if temp.startswith("!"):
                                    text = temp[1:].strip().lower()
                                    command = text.split(" ")[0]
                                    notcommand = text.replace(command, "").strip()
                                    if command == "next":
                                        nexttrack(sp)
                                        loggingWrite("Moved to next Song", name)
                                        return {'message': "Moved to next song"}, 200
                                    elif command == "back":
                                        backtrack(sp)
                                        loggingWrite("Moved to previous Song", name)
                                        return {'message': "Moved to previous song"}, 200
                                    elif command == "fplay":
                                        playReturn = searchAndPlaySpot(notcommand, sp, forcePlay)
                                        if playReturn:
                                            track = playReturn[0]
                                            Artist = playReturn[1]
                                            loggingWrite("Forced Played: " + track[
                                                "name"] + " By:" + Artist + " -------------- Link: " +
                                                         track["external_urls"]["spotify"], name)
                                            return {'message': "Forced Played: " + track[
                                                "name"] + "\nBy:" + Artist + "\nLink: " + \
                                                               track["external_urls"]["spotify"]}, 200
                                        else:
                                            loggingWrite("Force Play: No results for " + temp, name)
                                            return {'message': "Did not play: There were no results"}, 200
                                    elif command == "vol" or command == "volume":
                                        try:
                                            vol = int(notcommand)
                                            if vol >= 0 and vol <= 100:
                                                changeVolume(sp, vol)
                                                loggingWrite("Volume changed to " + str(vol), name)
                                                return {'message': "Volume Changed to " + str(vol)}, 200
                                            else:
                                                raise ValueError
                                        except ValueError as e:
                                            loggingWrite(
                                                "Error: " + notcommand + " was not a valid number, must be between 0 and 100",
                                                name)
                                            return {
                                                       'message': "Error: Not a Valid Number, must be between 0 and 100"}, 200
                                    elif command == "queue":
                                        if len(queue) != 0:
                                            previoussongs = previoussong(sp, int(songdetails[queue[0]][3]))
                                            for item in previoussongs["items"]:
                                                if item["track"]["id"] in queue:
                                                    queue.remove(item["track"]["id"])
                                                    if item["track"]["id"] in songdetails:
                                                        songdetails.pop(item["track"]["id"])
                                        currentsong = currentlyplaying(sp)
                                        if currentsong != None:
                                            if currentsong["item"]["id"] in queue:
                                                queue.remove(currentsong["item"]["id"])
                                                if currentsong["item"]["id"] in songdetails:
                                                    songdetails.pop(currentsong["item"]["id"])
                                            currentArtist = ""
                                            found = False
                                            for index, artists in enumerate(currentsong["item"]["artists"]):
                                                currentArtist += artists["name"] + ", "
                                                found = True
                                            if not found:
                                                currentArtist = "No found artist"
                                            else:
                                                currentArtist = currentArtist[0:-2]
                                            returnmessage = "Current Song: " + currentsong["item"][
                                                "name"] + " By: " + currentArtist
                                            returnmessage += "\n----------------------------\nQueue:"
                                            number = 1
                                            if len(queue) == 0:
                                                returnmessage += "\nNothing in Queue"
                                            for item in queue:
                                                songdet = songdetails[item]
                                                returnmessage += "\n" + str(number) + ". " + songdet[1] + " By: " + \
                                                                 songdet[2] + " -- Queued By:" + songdet[0]
                                                number += 1
                                            loggingWrite("Return Queue", name)
                                            return {'message': returnmessage}, 200

                                        else:
                                            raise spotipy.SpotifyException(http_status=404,
                                                                           code=-1,
                                                                           msg="!!queue\nPlayer command failed: No active device found",
                                                                           reason="NO_ACTIVE_DEVICE")


                                    else:
                                        return {'message': "Command not found"}, 200

                                else:
                                    playReturn = searchAndPlaySpot(temp, sp, addQueue)
                                    if playReturn:
                                        track = playReturn[0]
                                        Artist = playReturn[1]
                                        if not playReturn[2]:
                                            queue.append(track["id"])
                                            songdetails[track["id"]] = [name, track["name"], Artist, time.time()]
                                            loggingWrite(
                                                "Added " + track["name"] + " By:" + Artist + " ---------- Link: " + \
                                                track["external_urls"]["spotify"], name)
                                            return {'message': "Added " + track[
                                                "name"] + "\nBy:" + Artist + "\nLink: " + \
                                                               track["external_urls"]["spotify"]}, 200
                                        else:
                                            loggingWrite("Already added " + track[
                                                "name"] + " By:" + Artist + " ---------- Link: " + \
                                                         track["external_urls"]["spotify"] + "\nSkipped", name)
                                            return {'message': "Already added " + track[
                                                "name"] + "\nBy:" + Artist + "\nLink: " + \
                                                               track["external_urls"]["spotify"] + "\nSkipped"}, 200

                                    else:
                                        loggingWrite("Queue: No results for " + temp, name)
                                        return {'message': "Did not add: There were no results"}, 200
                            except spotipy.SpotifyException as error:
                                if error.reason == "NO_ACTIVE_DEVICE":
                                    queue.clear()
                                    songdetails.clear()
                                    loggingWrite("Error: Spotify not active: " + str(error), name)
                                    return {'message': "Error: Spotify not active"}, 428
                                elif error.reason == "VOLUME_CONTROL_DISALLOW":
                                    loggingWrite("Error: Volume Cannot Be Controlled: " + str(error), name)
                                    return {'message': "Volume Cannot Be Controlled"}, 200
                                else:
                                    raise error
                        else:
                            loggingWrite("Nothing was provided", name)
                            return {'message': "Error: There was nothing provided"}, 404
                    else:
                        loggingWrite("Did not have a message that started with !", name)
                        return {'message': "Must start with !"}, 422
                else:
                    loggingWrite("Did not provide phone number or message", "unknown")
                    return {'message': "Must have \'name\' and \'message\'"}, 422
            except Exception as e:
                loggingWrite("Error: " + str(e) + " --- Command is: " + str(messageVal), name)
                return {'message': "Error Occurred "}, 400
            loggingWrite("Error: Nothing was matched How is that possible. The command is : " + str(messageVal),
                         "Unknown")
            return {'message': "Error: Nothing was matched"}, 400
        else:
            loggingWrite("Error: Token Invalid", "System")
            return {"message": "Error: Token must be valid"}, 401
Ejemplo n.º 9
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app

    '''

    if not os.path.exists(TOKEN_CACHE_PATH):
        os.makedirs(TOKEN_CACHE_PATH)

    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        sys.stderr.write('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = os.path.join(TOKEN_CACHE_PATH, ".cache-" + username)

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        sys.stderr.write('''

            User authentication requires interaction with your
            web browser. Once you enter your credentials and
            give authorization, you will be redirected to
            a url.  Paste that url you were directed to to
            complete the authorization.

        ''')
        auth_url = sp_oauth.get_authorize_url()
        try:
            subprocess.call(["open", auth_url])
            sys.stderr.write("Opening {} in your browser\n".format(auth_url))
        except:
            try:
                subprocess.call(["cygstart", auth_url])
                sys.stderr.write(
                    "Opening {} in your browser\n".format(auth_url))
            except:
                sys.stderr.write("Please navigate here: {}\n".format(auth_url))

        sys.stderr.write("\n\n")
        response = raw_input("Enter the URL you were redirected to: ")
        sys.stderr.write("\n\n")
        sys.stderr.write("\n\n")

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)
    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None
Ejemplo n.º 10
0
def spotlogin(request):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor
        Parameters:
         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app    
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
    '''
    client_id = '327541285c7343afbf4822dc9d30ef7f'
    client_secret = '713dbe89b2ea4bd382fb0a7b366a63bb'
    redirect_uri = 'http://smalldata411.web.illinois.edu/redirect'
    cache_path = None
    username = '******'  #hardcoded now...change for later
    scope = 'user-library-read'
    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:
            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
            Get your credentials at
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = cache_path or ".cache-" + username
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        print('''
            User authentication requires interaction with your
            web browser. Once you enter your credentials and
            give authorization, you will be redirected to
            a url.  Paste that url you were directed to to
            complete the authorization.
        ''')

        auth_url = sp_oauth.get_authorize_url()
        #attempt to open the authorize url. This will redirect to our redirect page upon login
        try:
            # import webbrowser
            # webbrowser.open_new_tab(auth_url)
            #return HttpResponse("OPENED: " + str(auth_url))
            return HttpResponseRedirect(str(auth_url))

        except:
            return HttpResponse("FAILED")
Ejemplo n.º 11
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None):
    """
    prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
    """

    if not client_id:
        client_id = os.getenv("SPOTIPY_CLIENT_ID")

    if not client_secret:
        client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

    if not redirect_uri:
        redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI",
                                 "http://localhost:8080")

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=get_cache_path(username))

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        redirect_uri_parsed = urlparse(redirect_uri)

        run_server(redirect_uri_parsed.hostname, redirect_uri_parsed.port)

        auth_url = sp_oauth.get_authorize_url()
        try:
            import webbrowser
            webbrowser.open(auth_url)
        except:
            print("Please navigate here: %s" % auth_url)

        response = "%s?code=%s" % (redirect_uri, auth_token_queue.get())
        event_queue.put("done")

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)
    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None
Ejemplo n.º 12
0
def obtain_token_localhost(username,
                           scope=None,
                           client_id=None,
                           client_secret=None,
                           redirect_uri=None,
                           cache_path=None):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens

    '''

    cache_path = cache_path or ".cache-" + username

    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    token_info = sp_oauth.get_cached_token()

    if token_info:
        return token_info['access_token']

    print("Proceeding with user authorization")
    auth_url = sp_oauth.get_authorize_url()
    try:
        import webbrowser
        webbrowser.open(auth_url)
        print("Opened %s in your browser" % auth_url)
    except:
        print("Please navigate here: %s" % auth_url)

    url_info = urlparse(redirect_uri)
    netloc = url_info.netloc
    if ":" in netloc:
        port = int(netloc.split(":", 1)[1])
    else:
        port = 80

    server = start_local_http_server(port)
    server.handle_request()

    if server.auth_code:
        token_info = sp_oauth.get_access_token(server.auth_code)
        return token_info['access_token']
 def func():
     raise spotipy.SpotifyException(http_status=http_status,
                                    code=-1,
                                    msg=message)
Ejemplo n.º 14
0
def prompt_for_user_token_mod(username,
                              scope=None,
                              client_id=None,
                              client_secret=None,
                              redirect_uri=None,
                              cache_path=None,
                              oauth_manager=None,
                              show_dialog=False):
    if not oauth_manager:
        if not client_id:
            client_id = os.getenv("SPOTIPY_CLIENT_ID")

        if not client_secret:
            client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

        if not redirect_uri:
            redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI")

        if not client_id:
            print("""
                You need to set your Spotify API credentials.
                You can do this by setting environment variables like so:
                export SPOTIPY_CLIENT_ID='your-spotify-client-id'
                export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
                export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
                Get your credentials at
                    https://developer.spotify.com/my-applications
            """)
            raise spotipy.SpotifyException(550, -1, "no credentials set")

        cache_path = cache_path or ".cache-" + username

    sp_oauth = oauth_manager or spotipy.SpotifyOAuth(client_id,
                                                     client_secret,
                                                     redirect_uri,
                                                     scope=scope,
                                                     cache_path=cache_path,
                                                     show_dialog=show_dialog)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:

        server_address = ('', 8420)
        httpd = OAuthHTTPServer(server_address)

        import webbrowser

        webbrowser.open(sp_oauth.get_authorize_url())
        httpd.server.handle_request()

        if httpd.server.url:
            url = httpd.server.url

            code = sp_oauth.parse_response_code(url)
            token = sp_oauth.get_access_token(code, as_dict=False)
    else:
        return token_info["access_token"]

    # Auth'ed API request
    if token:
        return token
    else:
        return None
Ejemplo n.º 15
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None,
                          cache_path=None,
                          direction='source'):
    """ prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
    """

    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = cache_path or ".cache-" + username
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        print(f'''
            #####################################################
            
            Need to authenticate the Spotify user:
                {username}
            for login type: {direction.upper()}
            
            Login type SOURCE means, that we need to
            authenticate for an account which will be used to
            read collections and items from (READ only).
            
            Login type DESTINATION means, that we need to
            authenticate for an account which will be used to
            copy collections and items from the SOURCE
            accounts TO (READ/WRITE).
            
            We will accuire the following permissions:
            ''')

        for s in scope.split():
            print(f'               {s}')

        print(f'''
            Please login to Spotify as this user in the web
            browser which just should have been opened.

            Once you enter your credentials and give
            authorization, you will be redirected to a url.
            
            IMPORTANT:
            Even if the page is not displayed or indicates an
            error (like "Could not be found" or similar), copy
            the url you were directed to from your browser's
            address bar and paste it to this shell to 
            complete the authorization.
            
            !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            Please make sure to close the browser window after
            you have copied the URL (and before pasting it to
            this window) to make sure the next instances are
            launched in a new private session.
            !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        ''')
        auth_url = sp_oauth.get_authorize_url()
        try:
            _inkognito_wrap_browsers(webbrowser)
            webbrowser.open(auth_url)
            print("Opened %s in your browser" % auth_url)
        except webbrowser.Error:
            print("Please navigate here: %s" % auth_url)

        print()
        print()
        response = input("Enter the URL you were redirected to: ")
        print()
        print()

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)

    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None