示例#1
0
def get_track_and_artists_name_from_api():
    """
    you should set three environment variables:
     SPOTIPY_CLIENT_ID
     SPOTIPY_CLIENT_SECRET
     SPOTIPY_REDIRECT_URI
        you need to set this value in your development dashboard
        this can be set this to http://127.0.0.1
        and in the first time execute you have to authenticate

     you can get these from Spotify development dashboard
    """
    auth_manager = SpotifyOAuth(scope='user-read-currently-playing')
    token = auth_manager.get_access_token(as_dict=False)

    sp = spotipy.Spotify(auth=token)

    current_track = sp.current_user_playing_track()

    if current_track:
        artists = []
        for i in current_track['item']['artists']:
            artists.append(i['name'])  # append name of artist to artists list

        playing_track_name = current_track['item']['name']
        artists = ','.join(artists)
        return artists, playing_track_name
    return False, False
示例#2
0
 def __init__(self):
     super().__init__()
     self.auth_manager = SpotifyOAuth(
         cache_handler=self.get_cache_handler(),
         scope=current_app.config['SPOTIFY_SCOPE'],
         client_id=current_app.config['SPOTIFY_CLIENT_ID'],
         client_secret=current_app.config['SPOTIFY_CLIENT_SECRET'],
         redirect_uri=current_app.config['SPOTIFY_REDIRECT_URI'])
示例#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)
示例#4
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'])
示例#5
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)
示例#6
0
    def refresh_access_token(self, spotify_credentials: SpotifyOAuth) -> str:
        cached_token: dict = spotify_credentials.get_cached_token()
        refreshed_token: str = cached_token.get('refresh_token')
        new_token: dict = spotify_credentials.refresh_access_token(
            refreshed_token)
        new_access_token = new_token.get('access_token')

        spotify_instance = Spotify(auth=new_access_token)
        self._spotify_instance = spotify_instance
        return new_access_token
示例#7
0
    def test_saves_to_cache_path(self, opener):
        scope = "playlist-modify-private"
        path = ".cache-username"
        tok = _make_fake_token(1, 1, scope)

        fi = _fake_file()
        opener.return_value = fi

        spot = SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", scope, path)
        spot._save_token_info(tok)

        opener.assert_called_with(path, 'w')
        self.assertTrue(fi.write.called)
示例#8
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)
示例#9
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--setup', action='store_true', default=False)
    parser.add_argument('--mode',
                        '-m',
                        default=list(modes)[0],
                        choices=modes.keys())

    args = parser.parse_args()

    if args.setup:
        setup()
    else:
        client_conf = get_client_conf()
        oauth = SpotifyOAuth(
            client_id=client_conf['client_id'],
            client_secret=client_conf['client_secret'],
            redirect_uri='http://localhost:8080/',
            scope=
            'user-modify-playback-state app-remote-control streaming user-read-playback-state user-library-read',
            cache_path=os.path.join(DIR_CONF, 'auth.json'))
        sp = Spotify(oauth_manager=oauth)
        rofi_client = rofi.Rofi(rofi_args=['-i'])

        try:
            modes[args.mode](sp, rofi_client).run()
        except UserCancel:
            print('Cancel...')
示例#10
0
def handler(event, context):

    CLIENT_USERNAME = os.environ['SPOTIPY_CLIENT_USERNAME']
    PLAYLIST_ID = os.environ['RECENT_LIKES_PLAYLIST_ID']
    PLAYLIST_LEN = int(os.environ['RECENT_LIKES_PLAYLIST_LEN'])

    print("Authenticating to Spotify")
    scope = "user-library-read playlist-modify-public"
    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
    print("Authenticated to Spotify")

    print("Getting playlist tracks.")
    results = sp.user_playlist_tracks(user=CLIENT_USERNAME,
                                      playlist_id=PLAYLIST_ID)
    current_tracks = []
    for track in results['items']:
        current_tracks.append(track['track']['uri'])

    print("Clearing playlist.")
    sp.user_playlist_remove_all_occurrences_of_tracks(user=CLIENT_USERNAME,
                                                      playlist_id=PLAYLIST_ID,
                                                      tracks=current_tracks)

    print("Get liked tracks.")
    results = sp.current_user_saved_tracks(limit=PLAYLIST_LEN)
    recent_likes = []
    for idx, item in enumerate(results['items']):
        track = item['track']
        print(idx, track['artists'][0]['name'], " – ", track['name'])
        recent_likes.append(track['uri'])

    print("Add liked tracks.")
    sp.user_playlist_add_tracks(user=CLIENT_USERNAME,
                                playlist_id=PLAYLIST_ID,
                                tracks=recent_likes)
 def __init__(self, user_scopes):
     self.client = Spotify(
         auth_manager=SpotifyOAuth(client_id=sp_client_id,
                                   client_secret=sp_client_secret,
                                   redirect_uri=sp_redirect_uri,
                                   scope=user_scopes))
     self.user_id = self.client.current_user()["id"]
示例#12
0
 def __init__(self):
     # feedly setup
     self.feedly_access_token = self._get_feedly_access_token()
     # spotify setup
     self.cache_path = Path(__file__).parent / f".cache-{self.spotify_username}"
     self.sp_oauth = SpotifyOAuth(
         SPOTIPY_CLIENT_ID,
         SPOTIPY_CLIENT_SECRET,
         SPOTIPY_REDIRECT_URI,
         scope=self.scopes,
         cache_path=self.cache_path,
         username=self.spotify_username
     )
     self.token_info = self.sp_oauth.get_cached_token()
     self.token = self.token_info["access_token"]
     self.spotify = spotipy.Spotify(auth=self.token)
     self.titles, self.tracks, self.current_tracks, self.tracks_to_add = None, None, None, None
示例#13
0
 def init(self):
     auth_manager = SpotifyOAuth(client_id=self.client_id,
                                 client_secret=self.client_secret,
                                 redirect_uri=self.redirect_uri,
                                 scope="user-read-currently-playing",
                                 username=self.username)
     self._client = Spotify(auth_manager=auth_manager)
     return self._client
示例#14
0
def get_auth_manager():
    scope = 'user-library-read user-top-read'  # Rights given to the app from Spotify
    auth_manager = SpotifyOAuth(os.environ['SPOTIPY_CLIENT_ID'],
                                os.environ['SPOTIPY_CLIENT_SECRET'],
                                os.environ['SPOTIPY_REDIRECT_URI'],
                                scope=scope,
                                cache_path=os.environ['CACHE_PATH'])
    return auth_manager
示例#15
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
示例#16
0
def main(args):
    # Auth with spotify
    auth_manager = SpotifyOAuth(scope=SCOPE,
                                client_id=args.client_id,
                                client_secret=args.client_secret,
                                redirect_uri=args.redirect_uri)
    sp = spotipy.Spotify(auth_manager=auth_manager)
    user_uri = sp.me()['id']

    # load file contents or stdin
    with open(args.file, "r") if not args.stdin else sys.stdin as f_in:
        file_contents = f_in.readlines()

    # Match lines against regex, trim whitespace
    if not args.pre_formatted:
        lines_trimmed = [
            re.match(SEARCH_REGEX, line)[1].strip() for line in file_contents
        ]
    else:
        lines_trimmed = [line.strip() for line in file_contents]
    logging.debug(lines_trimmed)

    # Create new playlist
    new_playlist_name = "Mixcloud tracklist output"
    playlist_response = sp.user_playlist_create(
        user_uri,
        new_playlist_name,
        description=f"From {args.file if args.file else 'stdin'}")
    logging.info(f"Created playlist: {new_playlist_name}")

    # search for song and add it to the playlist
    uris = []
    dnf = []
    for track_name in lines_trimmed:

        if track_name == "ID - ID":
            continue

        query = track_name.lower().replace("&", " ").replace(" ", "+")
        logging.info(f"Searching for {track_name}... (query: {query})")
        results = sp.search(query, limit=1, type='track')

        if len(results['tracks']['items']) > 0:
            track = results['tracks']['items'][0]
            uris.append(track['uri'])
            logging.info(
                f"Found {track['name']} by {track['artists'][0]['name']}")
        else:
            dnf.append(track_name)
            logging.info("No search results found")

    sp.playlist_add_items(playlist_response['uri'], uris)
    logging.info(f"Added {len(uris)} songs to playlist.")

    logging.info("Could not find these tracks:")
    for track_name in dnf:
        logging.info(track_name)
示例#17
0
def spotify_auth():
    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id,
                                                   client_secret,
                                                   redirect_uri="http://127.0.0.1:8008",
                                                   scope="user-library-read"))

    results = sp.current_user_saved_tracks()
    for idx, item in enumerate(results['items']):
        track = item['track']
        print(idx, track['artists'][0]['name'], " – ", track['name'])
示例#18
0
 def get_authorize_url(self, permissions: Sequence[str]):
     """ Returns a spotipy OAuth instance that can be used to authenticate with spotify.
     Args:
         permissions: List of permissions needed by the OAuth instance
     """
     scope = ' '.join(permissions)
     return SpotifyOAuth(self.client_id,
                         self.client_secret,
                         redirect_uri=self.redirect_url,
                         scope=scope).get_authorize_url()
示例#19
0
 def connect_spotify_api(self):
     """
     This method uses spotipy's client to connect to a user.
     """
     auth = SpotifyOAuth(client_secret=CLIENT_SECRET,
                         client_id=CLIENT_ID,
                         username="******",
                         scope=SCOPE,
                         redirect_uri=LOCAL_SERVER
                         )
     return auth
示例#20
0
    def auth(self):
        """
        Get a spotipy SpotifyOAuth object from this database object.

        :return: a spotipy SpotifyOAuth object
        """
        return SpotifyOAuth(
            client_id=self.client_id,
            client_secret=self.client_secret,
            redirect_uri=self.redirect_uri,
            cache_path=self.cache_path,
            scope=self.SCOPE,
        )
def generate_object():
    scope = (
        "playlist-modify-public user-read-currently-playing user-read-playback-state"
    )
    token = SpotifyOAuth(
        client_id=client_id,
        client_secret=client_sectet,
        redirect_uri=redirect_uri,
        scope=scope,
        username=username,
    )
    spotify_object = spotipy.Spotify(auth_manager=token)

    return spotify_object
示例#22
0
    def __init__(self, *args, **kwargs):
        client_id = getenv('SPOTIFY_client_id')
        client_secret = getenv('SPOTIFY_client_secret')
        self.username = getenv('SPOTIFY_username')
        redirect_uri = getenv('SPOTIFY_redirect_uri')
        scope = 'playlist-modify-private user-library-modify'

        # login
        logging.info("Starting Spotify client")
        auth_manager = SpotifyOAuth(client_id=client_id,
                                    client_secret=client_secret,
                                    scope=scope,
                                    redirect_uri=redirect_uri,
                                    username=self.username)
        self.sp_client = Spotify(auth_manager=auth_manager)
示例#23
0
def get_sp_oauth():
    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 or not client_secret or not redirect_uri:
        raise ValueError("You must set SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI")

    sp_oauth = SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=SCOPE
    )
    return sp_oauth
示例#24
0
def main():

    # Dictionary of all songs from all playlists {song['id']: song['name']}
    allSongsDict = {}

    trackList = []

    USERNAME = os.environ.get('SPOTIFY_USER')
    CLIENT_ID = os.environ.get('SPOTIFY_CLIENT_ID')
    CLIENT_SECRET = os.environ.get('SPOTIFY_CLIENT_SECRET')
    REDIRECT_URI = 'http://localhost/'
    SCOPE = 'user-library-read,playlist-modify-private,user-read-private,playlist-modify-public,user-read-currently-playing'

    playlistID = '72L1ruRcxPEBWBbkC3pN17'


    # Connect to Spotify API with credentials declared above
    auth = SpotifyOAuth(username=USERNAME, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope=SCOPE)
    sp = spotipy.Spotify(auth_manager=auth)

    result = sp.current_user_playing_track()
    if(result == None or (('context' in result) and ('href' in result['context']) and (type(result['context']['href']) == str) and (playlistID not in result['context']['href']))):
        print('You are on my playlist!')
示例#25
0
文件: util.py 项目: jrddp/PlayMenu
def get_spotify():
    global _spotify
    if not _spotify:
        from spotipy import Spotify, SpotifyOAuth

        scopes = {
            "user-read-playback-state", "user-modify-playback-state",
            "user-follow-modify", "user-library-read", "user-library-modify",
            "user-modify-playback-state", "playlist-modify-public",
            "playlist-modify-private"
        }

        config = get_config()
        client_id = config["Authentication"]["clientId"]
        client_secret = config["Authentication"]["clientSecret"]

        o_auth = SpotifyOAuth(client_id=client_id,
                              client_secret=client_secret,
                              redirect_uri="http://localhost:8080/callback",
                              scope=" ".join(scopes),
                              cache_path=oauth_file)
        _spotify = Spotify(oauth_manager=o_auth)
    return _spotify
示例#26
0
    def write(self, username):

        chunk_size = 100

        token = SpotifyOAuth(scope='playlist-modify-public', username=username)
        spotify = spotipy.Spotify(auth_manager=token)

        rearranged_playlist = spotify.user_playlist_create(user=username,
                                                           name=self.name,
                                                           public=True)
        playlist_id = rearranged_playlist['id']
        track_ids = [t.create_spotify_uri() for t in self.tracks]

        chunks = [
            track_ids[i:i + chunk_size]
            for i in range(0, len(track_ids), chunk_size)
        ]
        for chunk in chunks:
            spotify.user_playlist_add_tracks(user=username,
                                             playlist_id=playlist_id,
                                             tracks=chunk)

        return
示例#27
0
def individual_post(request):
    # using configparser to import [SPOTIFY] CLIENT_ID and CLIENT_SECRET from a file called config.cfg
    config = configparser.ConfigParser()
    config.read('/usr/src/app/grinder_api/config.cfg')
    client_id = config.get('SPOTIFY', 'CLIENT_ID')
    client_secret = config.get('SPOTIFY', 'CLIENT_SECRET')
    username = '******'  #grinderuser.objects.filter(username='******')#print(username) =<QuerySet [<grinderuser: m7roking>]>
    scope = 'user-library-read'
    cachePath = '/usr/src/app/grinder_api/'
    redirect_uri = 'http://localhost:8000/grinder_api/'

    creds = SpotifyOAuth(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope='user-read-recently-played',
        username='******',
    )

    sp = spotipy.Spotify(client_credentials_manager=creds)
    user = sp.user('m7roking')
    print(sp.current_user_recently_played())

    return render('index.html')
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)
示例#29
0
def _make_oauth(*args, **kwargs):
    return SpotifyOAuth("CLID", "CLISEC", "REDIR", "STATE", *args, **kwargs)
示例#30
0
    def test_get_auth_response_with_inconsistent_state(self, webbrowser_mock,
                                                       get_user_input_mock):
        oauth = SpotifyOAuth("CLID", "CLISEC", "redir.io", state='wxyz')

        with self.assertRaises(SpotifyStateError):
            oauth.get_auth_response()