Example #1
0
def authenticate():
    class RequestHandler(BaseHTTPRequestHandler):
        callbackUri = None

        def do_GET(self):
            self.send_response(200, "OK")
            self.end_headers()

            self.wfile.write(
                pkg_resources.resource_string(__name__, "html/success.html"))
            RequestHandler.callbackUri = self.path

    config = get_config()

    oauth = SpotifyOAuth(
        client_id=config["client_id"],
        client_secret=config["client_secret"],
        redirect_uri="http://localhost:8000",
        scope=scope,
        cache_path=dirs.user_cache_dir,
    )

    token_info = oauth.get_cached_token()

    if not token_info:
        url = oauth.get_authorize_url()
        webbrowser.open(url)

        server = HTTPServer(('', 8000), RequestHandler)
        server.handle_request()

        code = oauth.parse_response_code(RequestHandler.callbackUri)
        oauth.get_access_token(code, as_dict=False)
    return oauth
def login() -> Spotify:
    """
    Attempt to log in to Spotify as the current user
    These OS Env variables must be set:
        SPOTIPY_CLIENT_ID
        SPOTIPY_CLIENT_SECRET
        SPOTIPY_REDIRECT_URI

    :return:                Spotify session
    """
    scope = 'user-library-read ' \
            'playlist-read-private ' \
            'playlist-modify-private ' \
            'playlist-modify-public ' \
            'user-library-modify ' \
            'user-read-recently-played'

    auth = SpotifyOAuth(scope=scope,
                        username=USERNAME,
                        cache_path=os.path.join(CACHE_DIR, 'auth_token.json'))

    token_info = auth.get_cached_token()
    if token_info:
        logging.info('Using cached token for login')
        return _get_login_session(token_info['access_token'])

    code = auth.parse_response_code(RESPONSE_URL)
    if code:
        logging.info('Found response URL. Getting an access token...')
        token_info = auth.get_access_token(code)
        return _get_login_session(token_info['access_token'])

    logging.warning(
        'Access token not found. Please use the below URL to authorize this '
        'application and then set the RESPONSE_URL env variable to the URL '
        'spotify responds with and run this application again')
    logging.warning(auth.get_authorize_url())
    sys.exit(0)