Beispiel #1
0
def find_artists_recommendations(token, seed_artists_ids=[]):
    """
    Using recommendations API get a list of recommended artists using seed_artists as seed

    :param token: User auth token
    :param seed_artists_ids: list with artists ids to be used as seed
    :return: a list of artists
    """

    artists = []

    limit = 100
    offset = 0
    max_seed_artists = 5
    while True:
        seed = seed_artists_ids[offset:offset + max_seed_artists]
        if not seed:
            break
        # The seed must be a list with 5 artists ids
        seed = "seed_artists=" + ",".join(seed)
        recommend_url = SPOTIFY_API + "/recommendations?limit=%i&%s" % (limit,
                                                                        seed)
        tracks = query_api(token, recommend_url)

        # Now we need to extract the artists from the tracks
        # The artist object included is the simplified one, so no followers info
        for track in tracks['tracks']:
            artists.append(track['artists'][0])
        offset += max_seed_artists

    return artists
Beispiel #2
0
def search_artist_tracks(token, artist):
    """
    Search tracks for an artist

    :param token: Auth token
    :param artist: Name of the artist to be searched
    :return: A tracks list
    """

    tracks = []
    offset = 0

    limit = 50
    max_items = limit * 5  # Max number of result items to retrieve
    # Maximum offset: 100.000.
    while True:
        time.sleep(0.1)
        search_url = SPOTIFY_API + "/search?type=track&q=artist:%s&limit=%i&offset=%i" % (
            artist, limit, offset)
        items = query_api(token, search_url)
        if not items['tracks']['items'] or offset >= max_items:
            break
        tracks += items['tracks']['items']
        offset += limit

    return tracks
Beispiel #3
0
def create_playlist(token, name, description=""):
    """
    Creates a new playlist with one song for all the artists

    :param token: User auth token
    :param name: name of the playlist to create
    :return: the playlist created
    """

    playlists = find_user_playlists(token)
    playlist_id = None

    for playlist in playlists:
        if playlist['name'] == name:
            playlist_id = playlist['id']
            break

    if not description:
        description = "Spoting playlist: https://github.com/acs/spoting."

    if not playlist_id:
        # Next create the new mailing list
        create_url = SPOTIFY_API + "/users/%s/playlists" % SPOTIFY_USER
        playlist_data = {"name": name, "description": description}

        playlist = query_api(token,
                             create_url,
                             method="POST",
                             data=json.dumps(playlist_data))
        recommender_list_id = playlist['id']

    return playlist
Beispiel #4
0
def find_playlists(token):
    """
    Get the playlists for the user

    :param token: Auth token
    :return: A playlists list
    """
    url = SPOTIFY_API_ME + "/playlists"

    playlists = query_api(token, url)

    return playlists['items']
Beispiel #5
0
def find_recently_played_tracks(token):
    """
    Find the last 50 find_recently_played_tracks tracks by the user

    :param token: Auth token
    :return: A tracks list
    """

    # Right now the API from Spotify only allows to get the 50 tracks last played
    limit = "50"
    history_url = SPOTIFY_API_ME + "/player/recently-played?limit=%s" % limit
    recent_tracks = query_api(token, history_url)

    return recent_tracks['items']
Beispiel #6
0
def find_related_artists(token, seed_artists_ids=[]):
    """
    Using the related API get a list of related artists to seed_artists

    :param token: User auth token
    :param seed_artists_ids: list with artists ids to be used as seed
    :return: a list of artists
    """

    artists = []

    for artist_id in seed_artists_ids:
        related_url = SPOTIFY_API + "/artists/%s/related-artists" % (artist_id)
        related_artists = query_api(token, related_url)
        artists += related_artists['artists']

    return artists
Beispiel #7
0
def fetch_tracks_ids_from_playlist(playlist_id):

    url_playlist = SPOTIFY_API + "/users/%s/playlists/%s/tracks" % (
        SPOTIFY_USER, playlist_id)

    already_tracks_ids = []

    # Get the tracks that already exists to not duplicate data
    already_tracks_ids = []
    offset = 0
    limit = 100
    while True:
        url_tracks = url_playlist + "?limit=%i&offset=%i" % (limit, offset)
        tracks = query_api(token, url_tracks)
        if not tracks['items']:
            break
        already_tracks_ids += [
            track['track']['id'] for track in tracks['items']
        ]
        offset += limit

    return already_tracks_ids
Beispiel #8
0
def find_user_saved_tracks(token):
    """
    Get a list of the songs saved in the current Spotify user’s “Your Music” library.

    :param token: Auth token
    :return: A tracks list
    """

    tracks = []
    offset = 0

    limit = 50
    max_items = limit * 10  # Max number of result items to retrieve
    while True:
        time.sleep(0.1)
        saved_url = SPOTIFY_API_ME + "/tracks?limit=%i&offset=%i" % (limit,
                                                                     offset)
        items = query_api(token, saved_url)
        if not items['items'] or offset >= max_items:
            break
        tracks += items['items']
        offset += limit

    return tracks
Beispiel #9
0
def find_user_playlists(token):
    """
    Find all user playlists using scrolling

    :param token: User auth token
    :return: list of playlists
    """

    # Check that the list does not exists yet
    offset = 0
    max_items = 300
    limit = 20
    playlists = []

    while True:
        playlists_url = SPOTIFY_API_ME + "/playlists?limit=%i&offset=%i" % (
            limit, offset)
        playlists_res = query_api(token, playlists_url)
        if not playlists_res['items'] or offset >= max_items:
            break
        playlists += playlists_res['items']
        offset += limit

    return playlists
Beispiel #10
0
def add_artists_top_track(token, playlist, artists):
    """
    Add the top track from artists to the playlist with id playlist_id

    :param token: User auth token
    :param playlist_id: Id of the playlist in which to add the tracks
    :param artists: List of artists from which to get the tracks
    :return: None
    """

    playlist_id = playlist['id']

    max_artists = 500  # Safe limit
    max_tracks_pack = 100  # Max number of tracks that can be added per call to a playlist

    if DEBUG:
        max_artists = 5

    # To avoid adding duplicate tracks get the current ones
    print("Finding the tracks that are already in the playlist",
          playlist['name'])
    already_tracks_ids = fetch_tracks_ids_from_playlist(playlist_id)

    # Get first the tracks to be added to the playlist
    print(
        "Finding the tracks to add to the playlist %s from %i artists (one call per each)"
        % (playlist['name'], len(artists)))
    selected_tracks = []
    for artist in artists[0:max_artists]:
        url_top = SPOTIFY_API + "/artists/%s/top-tracks?country=%s" % (
            artist['id'], SPOTIFY_MARKET)
        tracks = query_api(token, url_top)
        # Get the first track from the top list
        try:
            if tracks['tracks'][0]['id'] not in already_tracks_ids:
                selected_tracks.append(tracks['tracks'][0])
        except IndexError:
            print("%s does not have top tracks" % artist['name'])

    # Add the tracks found to the playlist in 100 packs
    offset = 0
    print("Adding the tracks to the playlist", playlist['name'])

    while offset < len(selected_tracks):
        data = {}
        data["uris"] = [
            track["uri"]
            for track in selected_tracks[offset:offset + max_tracks_pack]
        ]
        offset += max_tracks_pack
        url_playlist = SPOTIFY_API + "/users/%s/playlists/%s/tracks" % (
            SPOTIFY_USER, playlist_id)
        if data["uris"]:
            res = query_api(token,
                            url_playlist,
                            method='POST',
                            data=json.dumps(data))
        else:
            print("No more tracks to add to %s playlist" % playlist['name'])

    print("Added %i tracks to the playlist %s" %
          (len(selected_tracks), playlist['name']))