Example #1
0
    def __init__(self,
                 client_id=None,
                 client_secret=None,
                 redirect_uri=None,
                 state=None,
                 scope=None,
                 cache_path=None,
                 username=None,
                 proxies=None,
                 show_dialog=False,
                 requests_session=True,
                 requests_timeout=None,
                 open_browser=True,
                 cache_handler=None):
        """
        Creates a SpotifyOAuth object

        Parameters:
             * client_id: Must be supplied or set as environment variable
             * client_secret: Must be supplied or set as environment variable
             * redirect_uri: Must be supplied or set as environment variable
             * state: May be supplied, no verification is performed
             * scope: May be supplied, intuitively converted to proper format
             * cache_handler: An instance of the `CacheHandler` class to handle
                              getting and saving cached authorization tokens.
                              May be supplied, will otherwise use `CacheFileHandler`.
                              (takes precedence over `cache_path` and `username`)
             * cache_path: May be supplied, will otherwise be generated
                           (takes precedence over `username`)
             * username: May be supplied or set as environment variable
                         (will set `cache_path` to `.cache-{username}`)
             * proxies: Proxy for the requests library to route through
             * show_dialog: Interpreted as boolean
             * requests_timeout: Tell Requests to stop waiting for a response after a given number
                                 of seconds
             * open_browser: Whether or not the web browser should be opened to authorize a user
        """

        super(SpotifyOAuth, self).__init__(requests_session)

        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect_uri = redirect_uri
        self.state = state
        self.scope = self._normalize_scope(scope)
        if cache_handler:
            assert issubclass(cache_handler.__class__, CacheHandler), \
                "cache_handler must be a subclass of CacheHandler: " + str(type(cache_handler)) \
                + " != " + str(CacheHandler)
            self.cache_handler = cache_handler
        else:
            self.cache_handler = CacheFileHandler(
                username=(username or os.getenv(
                    CLIENT_CREDS_ENV_VARS["client_username"])),
                cache_path=cache_path)
        self.proxies = proxies
        self.requests_timeout = requests_timeout
        self.show_dialog = show_dialog
        self.open_browser = open_browser
    def decorated_function(*args, **kwargs):
        cache_handler = CacheFileHandler(cache_path=session_cache_path())
        auth_manager = SpotifyOAuth(cache_handler=cache_handler)
        if not auth_manager.validate_token(cache_handler.get_cached_token()):
            return redirect(url_for('index'))

        sp = spotipy.Spotify(auth_manager=auth_manager)

        return f(sp, *args, **kwargs)
Example #3
0
    def __init__(self,
                 client_id=None,
                 redirect_uri=None,
                 state=None,
                 scope=None,
                 cache_path=None,
                 username=None,
                 show_dialog=False,
                 cache_handler=None):
        """ Creates Auth Manager using the Implicit Grant flow

        **See help(SpotifyImplictGrant) for full Security Warning**

        Parameters
        ----------
        * client_id: Must be supplied or set as environment variable
        * redirect_uri: Must be supplied or set as environment variable
        * state: May be supplied, no verification is performed
        * scope: May be supplied, intuitively converted to proper format
        * cache_handler: An instance of the `CacheHandler` class to handle
                              getting and saving cached authorization tokens.
                              May be supplied, will otherwise use `CacheFileHandler`.
                              (takes precedence over `cache_path` and `username`)
        * cache_path: May be supplied, will otherwise be generated
                      (takes precedence over `username`)
        * username: May be supplied or set as environment variable
                    (will set `cache_path` to `.cache-{username}`)
        * show_dialog: Interpreted as boolean
        """
        logger.warning("The OAuth standard no longer recommends the Implicit "
                       "Grant Flow for client-side code. Use the SpotifyPKCE "
                       "auth manager instead of SpotifyImplicitGrant. For "
                       "more details and a guide to switching, see "
                       "help(SpotifyImplictGrant).")

        self.client_id = client_id
        self.redirect_uri = redirect_uri
        self.state = state
        if cache_handler:
            assert issubclass(type(cache_handler), CacheHandler), \
                "type(cache_handler): " + str(type(cache_handler)) + " != " + str(CacheHandler)
            self.cache_handler = cache_handler
        else:
            self.cache_handler = CacheFileHandler(
                username=(username or os.getenv(
                    CLIENT_CREDS_ENV_VARS["client_username"])),
                cache_path=cache_path)
        self.scope = self._normalize_scope(scope)
        self.show_dialog = show_dialog
        self._session = None  # As to not break inherited __del__
    def init(cls, client_id: str, client_secret: str,
             user_auth: bool) -> "Singleton":
        """
        `str` `client_id` : client id from your spotify account

        `str` `client_secret` : client secret for your client id

        `bool` `user_auth` : Determines if the Authorization Code Flow or
                   the Client Credentials Flow is used

        creates and caches a spotify client if a client doesn't exist. Can only be called
        once, multiple calls will cause an Exception.
        """

        # check if initialization has been completed, if yes, raise an Exception
        if isinstance(cls._instance, cls):
            raise Exception("A spotify client has already been initialized")

        credential_manager = None
        cache_handler = CacheFileHandler(cache_path=".spotdl-cache")

        # Use SpotifyOAuth as auth manager
        if user_auth:
            credential_manager = SpotifyOAuth(
                client_id=client_id,
                client_secret=client_secret,
                redirect_uri="http://127.0.0.1:8080/",
                scope="user-library-read",
                cache_handler=cache_handler,
            )
        # Use SpotifyClientCredentials as auth manager
        else:
            credential_manager = SpotifyClientCredentials(
                client_id=client_id,
                client_secret=client_secret,
                cache_handler=cache_handler,
            )

        # Create instance
        cls._instance = super().__call__(
            auth_manager=credential_manager,
            status_forcelist=(429, 500, 502, 503, 504, 404),
        )

        # Return instance
        return cls._instance
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 user_playlist_tracks(cache_path, playlist_id):
    cache_handler = CacheFileHandler(cache_path=cache_path)
    auth_manager = SpotifyOAuth(cache_handler=cache_handler)
    sp = spotipy.Spotify(auth_manager=auth_manager)
    print('getting tracks for: ', playlist_id)
    return sp.playlist_tracks(playlist_id=playlist_id)['items']
def login():
    cache_handler = CacheFileHandler(cache_path=session_cache_path())
    auth_manager = SpotifyOAuth(cache_handler=cache_handler)
    resp = redirect(auth_manager.get_authorize_url())
    return resp