Exemplo n.º 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
Exemplo n.º 2
0
    def test_get_authorize_url_shows_dialog_when_requested(self):
        oauth = SpotifyOAuth("CLID", "CLISEC", "REDIR", show_dialog=True)

        url = oauth.get_authorize_url()

        parsed_url = urllibparse.urlparse(url)
        parsed_qs = urllibparse.parse_qs(parsed_url.query)
        self.assertTrue(parsed_qs['show_dialog'])
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
def get_connection(client_id, client_secret, send_auth_request, callback_url):
    scope = "user-library-modify,user-library-read,playlist-read-private,user-read-private,user-read-email"

    auth_manager = SpotifyOAuth(
        client_id, client_secret, callback_url, scope=scope, open_browser=False
    )

    url = auth_manager.get_authorize_url()
    click.echo(f"Auth URL: {url}")

    if auth_manager.get_cached_token() is None:
        send_auth_request(url)
        start_local_http_server(30001)

    return Spotify(auth_manager=auth_manager)
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)
Exemplo n.º 7
0
from spotipy import SpotifyOAuth
load_dotenv()
from collections import namedtuple

Playlist = namedtuple("Playlist", ["title", "tracks"])

scope = "playlist-read-private streaming user-read-email user-read-private user-read-playback-state user-modify-playback-state"

redirect_uri = os.getenv("REDIRECT_URI")


oauth = SpotifyOAuth(client_id=os.getenv("CLIENT_ID"), client_secret=os.getenv("CLIENT_SECRET"),
                                                    redirect_uri=redirect_uri, scope=scope, show_dialog=True,
                                                    open_browser=False)

sp_auth_link = oauth.get_authorize_url()

sp_main = spotipy.Spotify(auth_manager=oauth)

def format_playlists(json_data: [dict]) -> [dict]:
    formatted_playlists = []
    for playlist_data in json_data:
        key = playlist_data["name"]
        value = playlist_data["owner"]["display_name"]
        formatted_playlists.append(f"{key} by {value}")
    return formatted_playlists


def get_playlist_from_header(header: str, spot_playlist: [dict]) -> dict:
    for playlist in spot_playlist:
        if (header.startswith(playlist["name"])):