def get_featured_tracks(self, token, max_number_of_tracks): """ Get featured tracks. Args: token (str): Spotify access token. max_number_of_tracks (int): Maximum number of tracks. Returns: Array: Featured tracks. """ print(colors.BLUE + "Getting featured tracks" + colors.ENDC) sp = client.Spotify(token) featured_playlists = sp.featured_playlists( limit=50)['playlists']['items'] featured_tracks = [] index = 0 while index < len(featured_playlists): tracks = self.get_tracks_from_playlist( token, featured_playlists[index], max_number_of_tracks - len(featured_tracks)) for track in tracks: featured_tracks.append(track) index += 1 featured_tracks = random.sample(featured_tracks, max_number_of_tracks) print(colors.OK + "Sucessfully got " + str(len(featured_tracks)) + " featured tracks" + colors.ENDC) return featured_tracks
def get_tracks_from_playlist(self, token, playlist, max_number_of_tracks): """ Get tracks from a playlist. Args: token (str): Spotify access token. playlist (obj): Spotify playlist. Returns: Array: Playlist tracks. """ sp = client.Spotify(token) user_id = playlist['owner']['id'] playlist_id = playlist['id'] saved_tracks = [] offset = 0 while len(saved_tracks) < max_number_of_tracks: input_tracks = sp.user_playlist_tracks( user_id, playlist_id, limit=min(max_number_of_tracks - len(saved_tracks), 100)) for track in input_tracks['items']: saved_tracks.append(track) if (input_tracks['next'] is None): break offset += 100 return saved_tracks
def get_tracks_audio_features(self, token, tracks): """ Get tracks audio features. Args: token (str): Spotify access token. tracks (arr): Array of tracks. Returns: Array: Tracks audio features. """ audio_features = [] sp = client.Spotify(token) print(colors.BLUE + "Getting " + str(len(tracks)) + " tracks audio features" + colors.ENDC) for index in range(0, len(tracks), 100): tracks_ids = [] for internal_index in range(index, min(index + 100, len(tracks))): tracks_ids.append(tracks[internal_index]['track']['id']) audio_feature = sp.audio_features(tracks_ids) for internal_index in range(0, len(audio_feature)): if audio_feature[internal_index] is not None: audio_features.append(audio_feature[internal_index]) print(colors.OK + "Sucessfully got " + str(len(audio_features)) + " tracks audio features" + colors.ENDC) return audio_features
def get_current_user_saved_tracks(self, token, max_number_of_tracks): """ Get user saved tracks. Args: token (str): Spotify access token. max_number_of_tracks (int): Maximum number of tracks to retrieve. Returns: Array: User saved tracks. """ sp = client.Spotify(token) print(colors.BLUE + "Getting saved tracks" + colors.ENDC) saved_tracks = [] offset = 0 while len(saved_tracks) < max_number_of_tracks: input_tracks = sp.current_user_saved_tracks( min(max_number_of_tracks - len(saved_tracks), 50), offset) for track in input_tracks['items']: saved_tracks.append(track) if (input_tracks['next'] is None): break offset += 50 print(colors.OK + "Sucessfully got " + str(len(saved_tracks)) + " saved tracks" + colors.ENDC) return saved_tracks
def main(): username = os.environ['SPOTIFY_USERNAME'] client_id = os.environ['SPOTIFY_CLIENT_ID'] client_secret = os.environ['SPOTIFY_CLIENT_SECRET'] save_path = 'output.png' update_seconds = 5 current_album_uri = None while True: token = util.prompt_for_user_token(username, scope='user-read-playback-state', client_id=client_id, client_secret=client_secret, redirect_uri='http://localhost/') if token: sp_client = client.Spotify(auth=token) currently_playing = sp_client.currently_playing() current_album_uri = get_album_cover( currently_playing=currently_playing, current_album_uri=current_album_uri, save_path=save_path) time.sleep(update_seconds)
def dashboard(request): # Query Params now = datetime.datetime.utcnow().isoformat() + '-07:00' #California tz offset # Spotify Requests # spotifyCred = get_cred('Jorge Rojas', 'spotify_cred') # print spotifyCred # DEBUG spotifyClient = client.Spotify( auth = spotifyCred ) playlists = spotifyClient.user_playlists( user = '******') # spotify:user:122632253 # print playlists # DEBUG # Calendar Requests # calendarCredJson = get_cred('Jorge Rojas', 'calendar_cred') calendarCred = OAuth2Credentials.from_json(calendarCredJson) http = httplib2.Http() http = calendarCred.authorize(http) service = build('calendar', 'v3', http = http) events = service.events().list( calendarId = '*****@*****.**', orderBy = "startTime", singleEvents = True, maxResults = 10, timeMin = now ).execute() # print events # DEBUG currenttime = datetime.datetime.now() print currenttime context = {'playlists': playlists['items'], 'events':events['items'], 'now':currenttime} return render(request, "dashboard.html", context)
def __init__(self): self.config = ConfigParser() self.config.read('spotify.cfg') credentials = dict(self.config['DEFAULT']) token = util.prompt_for_user_token(**credentials) self.sp = client.Spotify(auth=token) self.device_id = self.__find_device() self.sp.transfer_playback(device_id=self.device_id, force_play=False) self.current = None
def welcome_user(self, token): """ Welcome user in the terminal using their spotify user id. Args: token (str): Spotify access token. """ sp = client.Spotify(token) user = sp.me() print(colors.BITALIC + 'Nice to meet you ' + user['id'] + ', let\'s create your fluent playlist.' + colors.ENDC)
def get_user_id(self, token): """ Get user id. Args: token (str): Spotify access token. Returns: string: User id. """ sp = client.Spotify(token) user = sp.me() return user['id']
def main(argv): token = util.prompt_for_user_token(steve_spotify_id, 'playlist-modify-public') spot = client.Spotify(token) songs = {} stats = {} if use_cache: songs = load_cache() stats = load_metrics() else: songs = fetch_song_data() write_cache(songs) for season in songs: print 'Analyzing season: ' + season stats[season] = compute_stats(songs[season]) write_metrics(stats) new_songs = get_new_songs('summer', stats) make_playlist(spot, new_songs, 'Spiffy: Fall New')
def create_playlist(self, token, playlist, playlist_name): """ Creates a spotify playlist. Args: token (str): Spotify access token. playlist (obj): Spotify playlist. playlist_name (str): Playlist name. """ sp = client.Spotify(token) me_id = sp.me()['id'] playlist_id = sp.user_playlist_create(me_id, playlist_name, False)['id'] playlist_tracks_id = [] for track in playlist: playlist_tracks_id.append(track['uri']) sp.user_playlist_add_tracks(me_id, playlist_id, playlist_tracks_id)
def __init__(self): self.playlist_id_to_tracks = dict() self.track_uri_to_playlist_ids = dict() self.playlist_name_to_playlist_id = dict() self.playlist_id_to_playlist_name = dict() self.track_uri_to_track = dict() # track_name, track object self.playlist_id_to_playlist = dict() self.playlists = [] token = util.prompt_for_user_token(username=self.USERNAME, scope=self.SCOPE, client_id=self.CLIENT_ID, client_secret=self.CLIENT_SECRET, redirect_uri=self.REDIRECT_URI) if token: self.token = token self.spotify = client.Spotify(auth=self.token) else: raise ValueError("Can't get token for {}".format(self.USERNAME))
parser.add_argument('--uid', help='Spotify user ID', default=None) parser.add_argument('--max-matches', help='Max matches', default=8) parser.add_argument('--output', help='Path to output files', default='') args = parser.parse_args() if (not args.playlist or not args.uid): print("Playlist URI e/ou Spotify user não informados!") exit() max_matches = args.max_matches username = args.uid token = get_token(username, client_id, client_secret, redirect_url) client_credentials_manager = SpotifyClientCredentials( client_id=client_id, client_secret=client_secret) spotifyObject = client.Spotify( auth=token, client_credentials_manager=client_credentials_manager) print("Capturando informações da playlist...") playlist_id = get_playlist_id(args.playlist) playlist_info = spotifyObject.playlist_information(playlist_id, "name") playlist_name = normalize_unicodes(playlist_info['name']) all_track_info = spotifyObject.playlist_all_tracks(playlist_id) print("Criando diretório da playlist: " + playlist_name) output_path = args.output playlist_path = os.path.join(output_path, playlist_name) if not os.path.exists(playlist_path): os.makedirs(playlist_path)