예제 #1
0
    def getArtistGenreFromSpotify(self, artist):
        try_again = True
        if artist.find("(") != -1:
            artist = artist[0:artist.find("(") - 1]
        genres = []

        #added since spotify has errors for too many requests, but im not sure how what error that would be
        while try_again == True:
            try:
                try_again = False
                # get rid of wiki formatting if it is there
                spotClass = SpotifyClient("DJ?Does this do anything")
                # can through "bad search parameters" SpotifyException and needs to be caught when this called
                artist_id = spotClass.search_item(artist, "artist")
                artist_json_data = spotClass.get_artist(artist_id)
                for x in artist_json_data['genres']:
                    genres.append(x)
                return genres
            except SpotifyException:
                raise SpotifyException
            except:
                try_again = True
                print(
                    artist +
                    ":   getArtistGenreFromSpotify Error. Trying again in 3 seconds"
                )
                time.sleep(3)
예제 #2
0
def run():
    youtube_client = YoutubeClient('client_secret.json')
    spotify_client = SpotifyClient(
        'BQCZQpa6N1lnjZtdNdkSZpG-Vwxk4zAwXG_DLGN2rOa_D6Ddq7_S6jdUOwalI2J_rU4IUaZwgZ-dVrGLfEKT1_L2WsyVR6PieIxcgOBkD1OFAE6J7OeMk-mXGKdH5Njww__7eA8lkfKDZAAV7OSRjg'
    )
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f'{index}: {playlist.title}')

    choice = int(input('Enter a corresponding number: '))
    chosen = playlists[choice]
    print(f'You selected {chosen.title}')

    songs = youtube_client.get_videos(chosen.id)
    print(f'Attempting to read {len(songs)}')

    for song in songs:
        sid = spotify_client.search_song(song.artist, song.track)

        if sid:
            added_song = spotify_client.add_song(sid)

            if added_song():
                print('Successful')
예제 #3
0
def run():
    os.environ['SPOTIFY_AUTH_TOKEN'] = 'put spotify token here '

    # Get a list of our playlists from youtube
    youtube_client = YoutubeClient('./credentials/client_secret.json')
    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    playlists = youtube_client.get_playlists()

    # Ask whcih playlists we want to get the video from
    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")

    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    # For each video in the playlist, get the song information form youtube
    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add {len(songs)} ")

    # Search for the song on spotify
    for song in songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                print(f" Added {song.artist} ")

    # If we find the song add it to our Spotify liked songs

    pass
예제 #4
0
def run():
    with open('creds/spotify_auth.json') as sp:
        data = sp.read()
    spotify_cred = json.loads(data)

    image_converter = ImgConverter()
    read_text_file = ReadText()
    spotify_client = SpotifyClient(spotify_cred["spotify_token"])

    img_location = input("Enter location of image file: ")
    txt_file = "sample.txt"  # make a dump file
    txt_location = image_converter.extract_text(img_location, txt_file)
    playlist_name = input("Enter a name for your new playlist: ")
    playlist_id = spotify_client.create_new_playlist(playlist_name)

    songs_arr = read_text_file.read_txt(txt_location)
    songs = read_text_file.find_artist_track(songs_arr)
    print(songs)
    print(f"Attept to add {len(songs)} songs")

    uris = []
    for song in songs:
        spotify_song_uri = spotify_client.search_song(song.artist, song.track)
        if spotify_song_uri:
            uris.append(spotify_song_uri)
        added_song = spotify_client.add_song_to_spotify(uris, playlist_id)
    print(f"Successfully added songs in your {playlist_name} playlist")
def run():
    """
    main driver code
    """
    youtube_client = YoutubeClient('./creds/client_secret.json')
    spotify_client = SpotifyClient(SPOTIFY_API_KEY)
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")

    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected {chosen_playlist.title}")

    collected_songs = youtube_client.get_videos_from_playlist(
        chosen_playlist.id)
    print(f"Attempting to add {len(collected_songs)} to the spotify library")

    for song in collected_songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)

        if spotify_song_id:
            added_flag = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_flag:
                print(f"Successfully added {song.artist} - {song.track}")
예제 #6
0
def run():
    #get list of playlists
    youtube_client = YouTubeClient(
        './client_secret_876125188595-la35iddi3u0vnuejhksmaf4tnma4tgcp.apps.googleusercontent.com.json'
    )
    spotify_client = SpotifyClient(
        'BQAaHHx8oX1TR3CKCIsy4mrTCmf72-Sfq_9XadFMr61VnoxYAlc6OqwoqFFD5QIpCTUuO4bDIskRjkVvnEc3Cmp1s3AURkFp3E5Kq0OJLyzvvBGVn-EKdd_TBqU2D44rCaKGX5CF5csp1dVgnCWAbSfQmemTv6VhOm83UAJ5yTOFTDJgMIRvSdSKX299XdJTfQ'
    )

    playlists = youtube_client.get_playlists()
    for index, playlist_title in enumerate(playlists):
        print(f'{index}: {playlist_title}')
    print(len(playlists))
    resp = int(input("Enter your choice: "))
    chosen_playlist = playlists[resp]
    print(f"You selected: {chosen_playlist.title}")
    #get songs from playlist
    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add: {len(songs)}")
    #search for songs in playlist
    for song in songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                print(f"Added {song.artist}")
예제 #7
0
def run():

    # Youtube credentials
    youtube_client = YouTubeClient('./creds/client_secret.json')

    #Spotify authentication token
    spotify_client = SpotifyClient('SPOTIFY_AUTH_TOKEN')

    #Get the list of playlists
    playlists = youtube_client.get_playlists()

    #Print the name of playlists
    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")

    #Choose the playlist you want
    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    #Get the list of songs
    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add {len(songs)}")

    #Search and add the song
    for song in songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                print(
                    f"Added {song.artist} - {song.track} to your Spotify Liked Songs"
                )
예제 #8
0
def main():
    # get playlists from our youtube
    youtube_client = YoutubeClient('./creds/client_secret.json')
    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    playlists = youtube_client.get_playlist()

    # ask which playlist we want the music video from, make it more interactive
    for index, playlist in enumerate(playlists):
        print(f"{index}:{playlist.title}")

    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    # for each video in the playlist get the song information from youtube
    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add {len(songs)}")

    # search for song on spotify
    for song in songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)

        # if we find the song, add it to our liked song
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify_liked(
                spotify_song_id)

            # if the song is added then let the user know!
            if added_song:
                print(f"Added {song.artist}")
예제 #9
0
def run():
    with open('creds/spotify_auth.json') as sp:
        data = sp.read()
    spotify_cred = json.loads(data)
    youtube_client = YouTubeClient()

    spotify_client = SpotifyClient(spotify_cred["spotify_token"])
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")
    choice = int(input("Enter you choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    playlist_name = input("Enter a name for your new playlist: ")
    playlist_id = spotify_client.create_new_playlist(playlist_name)
    print(playlist_id)

    songs = youtube_client.get_songs_from_playlist(chosen_playlist.id)
    print(songs)
    print(f"Attept to add {len(songs)} songs")

    uris = []
    for song in songs:
        spotify_song_uri = spotify_client.search_song(song.artist, song.track)
        uris.append(spotify_song_uri)
        print(uris)
        count = len(uris)
    added_song = spotify_client.add_song_to_spotify(uris, playlist_id)
    print(f"added {count} songs in your {playlist_name} playlist")
예제 #10
0
def run():

    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    main_music_folder = os.getenv('DIR_MUSIC')
    playlist_id = os.getenv('PLAYLIST_ID')

    # searches and finds all mp3s in the file struture of the given dir
    os.chdir(main_music_folder)
    song_list = []
    for root, dirs, files in os.walk(main_music_folder, topdown=True):
        for name in files:
            if name.endswith('.mp3'):
                song_list.append(os.path.join(root, name))

    # temp: will remove the usage of pandas
    songs = pd.DataFrame(song_list, columns=['path'])
    songs['song_info'] = songs['path'].apply(lambda x: song_info(x))
    songs[['artist', 'track']] = songs['song_info'].apply(pd.Series)
    songs = songs[~((songs['artist'].isin([None, ' ', ''])) | (songs['track'].isin([None, ' ', ''])))].reset_index(drop=True)
    songs = songs['song_info'].tolist()

    for song in songs:
        spotify_song_id = spotify_client.search_song(song['artist'], song['track'])
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id, playlist_id)
            if added_song:
                print(f"Added {song['artist']} - {song['track']} to your Spotify Playlist.")
예제 #11
0
def run():
    # 1. Get a list of the user's playlists from YouTube
    youtube_client = YouTubeClient('./credentials/client_secret.json')
    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    playlists = youtube_client.get_playlists()

    # 2. Ask which playlist the user wants to retrieve music from
    for index, playlist in enumerate(playlists):
        print(str(index) + ": " + playlist.title)
    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print("You selected: " + chosen_playlist.title)

    # 3. For each video in the chosen playlist, get the song info from YouTube
    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print("Attempting to add " + str(len(songs)) + " items")

    # 4. Search for the song on Spotify and add to Spotify Liked Songs list
    for song in songs:
        # spotify_song_id = spotify_client.search_song(song.artist, song.track)
        spotify_song_id = spotify_client.search_song("music", song)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                # print("Added "+song.track+" ("+song.artist+")")
                print("Added " + song)
예제 #12
0
def run():
    #Take user inputs
    username = input("Enter your Spotify Username: "******"Enter your Spotify token: ")
    playlist_name = input("Enter desired playlist title: ")
    youtube_client = YouTubeClient('./creds/client_secret.json')
    spotify_client = SpotifyClient(sToken)
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")
    choice = int(input("Enter your choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id, sToken)
    playlist_id = spotify_client.create_playlist(username, sToken,
                                                 playlist_name)
    print(f"Attempting to add {len(songs)}")

    uris = [info["spotify_uri"] for song, info in songs.items()]
    uris = list(filter(None, uris))
    request_data = json.dumps(uris)
    query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
        playlist_id)

    response = requests.post(query,
                             data=request_data,
                             headers={
                                 "Content-Type": "application/json",
                                 "Authorization": "Bearer {}".format(sToken)
                             })
    print(f"Succefully added {len(uris)} songs!")
예제 #13
0
def run():

    youtube_client = YoutubeClient('./creds/client_secret.json')
    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    playlists = youtube_client.get_playlists()

    # ask which playlist we want to get music vids from
    for index, playlist in enumerate(playlists):
        print(f'{index} : {playlist.title}')

    choice = int(
        input('Please select the playlist  want to get music vids from'))
    chosen_playlist = playlists[choice]
    print("You chose : ", chosen_playlist.title)

    # for each playlist get the songs info from youtube
    songs = youtube_client.get_vids_from_playlists(chosen_playlist.id)
    print(f'trying to add {len(songs)}')

    # search for a song in spotify if found add it to the playlist
    for song in songs:
        spotify_song_id = spotify_client.search_for_a_song(
            song.artist, song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_playlist(spotify_song_id)
            if added_song:
                print(f'{song.track} added successfully !! ')

            else:
                print("sorry could not add song : ( ")

        else:
            print("song not found on Spotify :( ")
예제 #14
0
def main():
    client = SpotifyClient("Default Name")
    recommendations = client.get_recommendations(t_energy=0.5,
                                                 t_valence=0.8,
                                                 t_tempo=120)
    id = client.search_item("The Piano Guys", "artist")
    # print(json.dumps(client.get_artist(id), indent=2))
    print(json.dumps(recommendations, indent=2))
    print(len(client.genres))
예제 #15
0
def run():
	spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
	random_tracks = spotify_client.get_random_tracks()
	track_ids = [track['id'] for track in random_tracks]

	was_added_to_library = spotify_client.add_tracks_to_library(track_ids)
	if was_added_to_library:
		for track in random_tracks:
			print(f"Added {track['name']} to your library")
예제 #16
0
def run():
    #Busca en Spotify por canciones Random
    #Una vez obtenidas agregarlas a nuestra biblioteca
    spotify_client = SpotifyClient(config('SPOTIFY_AUTH_TOKEN'))
    random_tracks = spotify_client.get_random_tracks()
    track_ids = [track['id'] for track in random_tracks]
    was_added = spotify_client.add_tracks_to_library(track_ids)
    if was_added:
        for track in random_tracks:
            print(f"Added {track['name']} to library")
예제 #17
0
def run(auth, pID, word, genre, limit):
    spotify_client = SpotifyClient(auth, pID)
    randomtracks = spotify_client.get_random_tracks(word, genre, limit)
    tracks_uri = [track['uri'] for track in randomtracks]

    addedtolib = spotify_client.added_to_lib(tracks_uri)
    if addedtolib:
        print("added tracks", file=sys.stdout)
        return True
    return False
예제 #18
0
    def run(self, spotify_code, username='******', *args, **kwargs):
        """
        Use Spotify API to fetch song data for a given song and save the song to the database

        :param spotify_code: (str) Spotify URI for the song to be created
        :param username: (str) [Optional] Username for the user that requested this song
        """
        trace_id = kwargs.get('trace_id', '')
        signature = 'spotify.tasks.FetchSongFromSpotifyTask-{}'.format(trace_id)

        # Early exit: if song already exists in our system don't do the work to fetch it
        if Song.objects.filter(code=spotify_code).exists():
            logger.info(
                'Song with code {} already exists in database'.format(spotify_code),
                extra={
                    'fingerprint': auto_fingerprint('song_already_exists', **kwargs),
                    'trace_id': trace_id,
                }
            )

            return

        client = SpotifyClient(identifier=signature)

        track_data = client.get_attributes_for_track(spotify_code)
        song_data = client.get_audio_features_for_tracks([track_data])[0]

        try:
            Song.objects.create(**song_data)

            logger.info(
                'Created song {} in database'.format(spotify_code),
                extra={
                    'fingerprint': auto_fingerprint('created_song', **kwargs),
                    'song_data': song_data,
                    'username': username,
                    'trace_id': trace_id,
                }
            )
        except ValidationError:
            logger.exception(
                'Failed to create song {}, already exists in database'.format(spotify_code),
                extra={
                    'fingerprint': auto_fingerprint('failed_to_create_song', **kwargs),
                    'trace_id': trace_id,
                }
            )

            raise
예제 #19
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        state = get_random_string(
            length=settings.SPOTIFY['session_state_length'])

        client = SpotifyClient()
        context['spotify_auth_url'] = client.build_spotify_oauth_confirm_link(
            state, settings.SPOTIFY['auth_user_scopes'],
            settings.SPOTIFY['auth_redirect_uri'])

        self.request.session['state'] = state
        self.request.session['redirect_url'] = self.request.GET.get(
            'redirect_url')

        return context
예제 #20
0
def main(*args):
    # Set parameter and create client
    spotify_playlist_id = "37i9dQZEVXbLRQDuF5jeBp"
    spotify_client = SpotifyClient(os.getenv("SPOTIFY_CLIENT_ID"),
                                   os.getenv("SPOTIFY_CLIENT_SECRET"))
    # Write temp file
    temp_file = write_top50_data(spotify_client, spotify_playlist_id)
    logging.info(f"Wrote file {temp_file}")

    # Upload file to blob
    gcs_client = storage.Client()
    try:
        upload_file_blob(gcs_client, "spotify-data", temp_file)
        logging.info(f"Wrote file {temp_file} to blob")
    except Exception as e:
        logging.error(e)

    # Load blob to BQ
    bq_client = bigquery.Client()
    blob_path = "gs://spotify-data/"
    try:
        load_bigquery(bq_client, "spotify", "top50_tracks_raw",
                      blob_path + temp_file)
        logging.info(f"{temp_file} loaded into BigQuery.")
    except Exception as e:
        logging.error(e)
예제 #21
0
    def run(self, auth_id, playlist_name, songs, cover_image_filename=None, *args, **kwargs):
        self.trace_id = kwargs.get('trace_id', '')
        auth = SpotifyAuth.get_and_refresh_spotify_auth_record(auth_id, trace_id=self.trace_id)

        # Check that user has granted proper scopes to export playlist to Spotify
        if not auth.has_scope(settings.SPOTIFY_PLAYLIST_MODIFY_SCOPE):
            logger.error(
                'User {} has not granted proper scopes to export playlist to Spotify'.format(auth.user.username),
                extra={
                    'fingerprint': auto_fingerprint('missing_scopes_for_playlist_export', **kwargs),
                    'auth_id': auth.pk,
                    'scopes': auth.scopes,
                    'trace_id': self.trace_id,
                }
            )

            raise InsufficientSpotifyScopesError('Insufficient Spotify scopes to export playlist')

        spotify = SpotifyClient(identifier='spotify.tasks.ExportSpotifyPlaylistFromSongsTask-{}'.format(self.trace_id))

        logger.info(
            'Exporting songs to playlist {} for user {} on Spotify'.format(playlist_name, auth.spotify_user_id),
            extra={
                'fingerprint': auto_fingerprint('start_export_playlist', **kwargs),
                'auth_id': auth.pk,
                'trace_id': self.trace_id,
            }
        )

        playlist_id = self.get_or_create_playlist(auth.access_token, auth.spotify_user_id, playlist_name, spotify)

        # Upload cover image for playlist if specified
        if auth.has_scope(settings.SPOTIFY_UPLOAD_PLAYLIST_IMAGE) and cover_image_filename:
            self.upload_cover_image(auth.access_token, playlist_id, cover_image_filename, spotify)

        self.delete_all_songs_from_playlist(auth.access_token, playlist_id, spotify)
        self.add_songs_to_playlist(auth.access_token, playlist_id, songs, spotify)

        # Delete cover image file from disk if present
        #
        # Do this after uploading songs to playlist to keep image file on disk
        # in case of errors with uploading songs to playlist to ensure that if
        # we need to retry because of errors with adding/deleting songs in playlist
        # that we still have the image file on disk for retries.
        if cover_image_filename:
            try:
                os.unlink(cover_image_filename)  # pragma: no cover
            except FileNotFoundError:
                pass

        logger.info(
            'Exported songs to playlist {} for user {} successfully'.format(playlist_name, auth.spotify_user_id),
            extra={
                'fingerprint': auto_fingerprint('success_export_playlist', **kwargs),
                'auth_id': auth.pk,
                'trace_id': self.trace_id,
            }
        )
예제 #22
0
def run():
    youtube_client = YoutubeClient()
    spotify_client = SpotifyClient('/secrets/secrets.spotify_token')
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")
    choice = int(input("Enter your Playlist choice: "))
    chosen_playlist = playlists[choice]
    print(f"You selected: {chosen_playlist.title}")

    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add {len(songs)}")

    for song in songs:
        spotify_song_id = spotify_client.search_song(song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                print(f"Added {song.track}")
예제 #23
0
def run():
    youtube_client = YoutubeClient('./creds/client_secret.json')
    spotify_client = SpotifyClient(os.getenv('SPOTIFY_AUTH_TOKEN'))
    playlists = youtube_client.get_playlists()

    for index, playlist in enumerate(playlists):
        print(f"{index}: {playlist.title}")
    choice = input("Enter your choice: ")
    chosen_playlist = playlists[choice]
    print(f"You selected : {chosen_playlist.title}")

    songs = youtube_client.get_videos_from_playlist(chosen_playlist.id)
    print(f"Attempting to add {len(songs)} songs")

    for song in songs:
        spotify_song_id = spotify_client.search_song(song.artist, song.track)
        if spotify_song_id:
            added_song = spotify_client.add_song_to_spotify(spotify_song_id)
            if added_song:
                print(f"Successfully added {song.artist}, {song.track}")
예제 #24
0
    def run(self, auth_id, *args, **kwargs):
        trace_id = kwargs.get('trace_id', '')
        auth = SpotifyAuth.get_and_refresh_spotify_auth_record(auth_id, trace_id=trace_id)

        # Check that user has granted proper scopes to fetch top artists from Spotify
        if not auth.has_scope(settings.SPOTIFY_TOP_ARTIST_READ_SCOPE):
            logger.error(
                'User {} has not granted proper scopes to fetch top artists from Spotify'.format(auth.user.username),
                extra={
                    'fingerprint': auto_fingerprint('missing_scopes_for_update_top_artists', **kwargs),
                    'auth_id': auth.pk,
                    'scopes': auth.scopes,
                    'trace_id': trace_id,
                }
            )

            raise InsufficientSpotifyScopesError('Insufficient Spotify scopes to fetch Spotify top artists')

        spotify_client_identifier = 'update_spotify_top_artists_{}'.format(auth.spotify_user_id)
        spotify = SpotifyClient(identifier=spotify_client_identifier)

        logger.info(
            'Updating top artists for {}'.format(auth.spotify_user_id),
            extra={
                'fingerprint': auto_fingerprint('update_spotify_top_artists', **kwargs),
                'trace_id': trace_id,
            }
        )

        artists = spotify.get_user_top_artists(auth.access_token, settings.SPOTIFY['max_top_artists'])
        spotify_user_data, _ = SpotifyUserData.objects.get_or_create(spotify_auth=auth)
        spotify_user_data.top_artists = artists
        spotify_user_data.save()

        logger.info(
            'Successfully updated top artists for {}'.format(auth.spotify_user_id),
            extra={
                'fingerprint': auto_fingerprint('success_update_spotify_top_artists', **kwargs),
                'trace_id': trace_id,
            }
        )
def run():
    # 0. Initialisation of Youtube and Spotify clients
    youtube_client = YouTubeClient('client_secret_desktop.json')
    # spotify_client = SpotifyClient(spotify_token, spotify_user_id)
    spotify_client = SpotifyClient(spotify_user_id, spotify_scope, spotify_client_id, spotify_client_secret,
                                   spotify_redirect_url)

    # 1. Get a list of our Youtube playlists
    playlists = youtube_client.get_playlists()
    for index, playlist in enumerate(playlists):
        print("{}: {}".format(index, playlist.title))

    # 2. Select the Youtube playlists we want the music videos from
    choices = list(
        map(int, input("Enter the indexes of the different playlists to select: ").split()))  # separated by a space
    print("List of Youtube playlists indexes entered: {}".format(choices))  # 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

    # 3. Define the name of the Spotify playlist to create
    spotify_playlist_name = input(
        "Define the name of the Spotify playlist to create: ")  # Tracks from Youtube Playlists

    # 4. For each video in each playlist selected, get the track information from Youtube
    # and search the track in spotify thanks to its uri
    spotify_track_uris = []
    for choice in choices:
        chosen_playlist = playlists[choice]
        print("You selected the playlist '{}'".format(chosen_playlist.title))
        songs = youtube_client.get_music_videos_from_playlist(chosen_playlist.id)

        print("Adding {} tracks from '{}'".format(len(songs), chosen_playlist.title))

        for song in songs:
            spotify_track_uri = spotify_client.search_spotify_tracks_uri(song.artist, song.track_name)
            if spotify_track_uri:
                # create a list of all uris
                spotify_track_uris.append(spotify_track_uri)

    # 5. If we found the track, add it to to the new Spotify playlist
    added_tracks = spotify_client.add_tracks_to_spotify_playlist(spotify_playlist_name, spotify_track_uris)
    if added_tracks:
        print("Tracks added successfully to your new Spotify playlist '{}'!".format(spotify_playlist_name))
예제 #26
0
def main():
    print("Enter Spotify client ID:")
    spotify_client_id = sys.stdin.readline().split(" ")[-1].strip("\n")
    print("Enter Spotify secret key:")
    spotify_secret_key = sys.stdin.readline().split(" ")[-1].strip("\n")

    print("Enter names of artists, separated by new-lines:")
    artist_metadata = _get_artist_metadata(
        SpotifyClient(spotify_client_id, spotify_secret_key), sys.stdin)

    print("Fetched info: ")
    pp.pprint(artist_metadata)
예제 #27
0
def run():
    #Load Credentials
    with open('creds\credentials.json') as data_file:
        data = json.load(data_file)
    AUTHTOKEN = data["spotify"]["authToken"]
    spotify_client = SpotifyClient(AUTHTOKEN)

    # user = spotify_client.get_user_profile()
    # show playlists
    list = spotify_client.get_playlists()
    print("Playlists:\n")
    for num, playlist in enumerate(list, start=1):
        print(f"{num}.\t{playlist['name']}")

    # have user select a playlist
    while (True):
        #TODO: Create Static Message
        playlistNum = input("Input playlist number:\n")
        if (checkInteger(playlistNum)):
            num = int(playlistNum)
            if ((num <= 0).__or__(num > len(list))):
                #TODO: Create Static Message
                print("Please input a valid number.")
            else:
                break
        else:
            #TODO: Create Static Message
            print("Please input a valid number.")
    playlistId = list[int(playlistNum) - 1]

    playlist = spotify_client.get_playlist_items(playlistId['id'], 0)
    for num, song in enumerate(playlist, start=1):
        print(f"{num}.\t{song.name}")
    songNum = input("Select Song:\n")
    songNum = int(songNum) - 1
    songRecs = spotify_client.get_song_recommendations(
        [playlist[songNum].song_id])
    for num, song in enumerate(songRecs, start=1):
        print(f"{num}.\t{song.name}")
예제 #28
0
def callback():
    print("Requesting access token...")
    code = request.args["code"]
    data = {
        "grant_type": "authorization_code",
        "code": str(code),
        "redirect_uri": redirect_uri,
        "client_id": client_id,
        "client_secret": client_secret
    }
    response = requests.post(spotify_token_url, data=data)
    response_json = response.json()
    access_token = response_json["access_token"]

    artists_limits, time_range, tracks_limit, playlist_name = get_preferences()

    # Access the Spotify API
    spotify_client = SpotifyClient(access_token, artists_limits, time_range,
                                   tracks_limit, playlist_name)
    spotify_client.add_tracks_to_playlist()
    print("Your new playlist is ready, enjoy!")
    return redirect("https://open.spotify.com/collection/playlists")
예제 #29
0
    def refresh_access_token(self, **kwargs):
        """Make a call to the Spotify API to refresh the access token for the SpotifyAuth record"""
        trace_id = kwargs.get('trace_id', '')
        spotify_client = SpotifyClient(identifier='refresh-access-token:{}'.format(self.spotify_user_id))

        try:
            access_token = spotify_client.refresh_access_token(self.refresh_token)

            self.access_token = access_token
            self.last_refreshed = timezone.now()

            self.save()

            logger.info(
                'Refreshed access token for {}'.format(self.spotify_user_id),
                extra={
                    'fingerprint': auto_fingerprint('success_refresh_access_token', **kwargs),
                    'spotify_username': self.spotify_user_id,
                    'auth_id': self.pk,
                    'user_id': self.user_id,
                    'trace_id': trace_id,
                }
            )

        except SpotifyException:
            logger.exception(
                'Unable to refresh access token for {}'.format(self.spotify_user_id),
                extra={
                    'fingerprint': auto_fingerprint('failed_refresh_access_token', **kwargs),
                    'spotify_username': self.spotify_user_id,
                    'auth_id': self.pk,
                    'user_id': self.user_id,
                    'trace_id': trace_id,
                }
            )

            raise
예제 #30
0
    def add_saved_spotify_track_to_sheet(self, id):
        spotify_client = SpotifyClient()
        spotify_client.spotify_access_token = spotify_client.refresh_access_token(
        )
        last_saved_track = spotify_client.get_last_saved_track()
        payload = {
            "majorDimension":
            "ROWS",
            "values": [[
                last_saved_track['name'], last_saved_track['artist'],
                last_saved_track['id']
            ]]
        }
        # if spreadsheet is empty
        if 'values' not in self.get_last_row_in_spreadsheet(id):
            return self.append_row_to_spreadsheet(id, payload)

        # if track doesn't already exist in spreadsheet
        if last_saved_track['id'] != self.get_last_row_in_spreadsheet(
                id)['values'][-1][2]:

            payload = {
                "majorDimension":
                "ROWS",
                "values": [[
                    last_saved_track['name'], last_saved_track['artist'],
                    last_saved_track['id']
                ]]
            }
            return self.append_row_to_spreadsheet(id, payload)

        # if track already exists
        else:
            # raise exception
            raise SaveTrackException(
                "Track \"{0}\" by \"{1}\" already exists in spreadsheet".
                format(last_saved_track['name'], last_saved_track['artist']))