Merge pull request #97 from yiannisha/main

Added feature for changing limit and type of results closes#27 - rewrote for recent patch
This commit is contained in:
Footsiefat 2021-10-25 09:01:22 +13:00 committed by GitHub
commit 938b647753
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 158 additions and 59 deletions

View File

@ -4,8 +4,8 @@ from librespot.audio.decoders import AudioQuality
from tabulate import tabulate from tabulate import tabulate
from album import download_album, download_artist_albums from album import download_album, download_artist_albums
from const import TRACK, NAME, ID, ARTISTS, ITEMS, TRACKS, EXPLICIT, ALBUMS, OWNER, \ from const import TRACK, NAME, ID, ARTIST, ARTISTS, ITEMS, TRACKS, EXPLICIT, ALBUM, ALBUMS, \
PLAYLISTS, DISPLAY_NAME OWNER, PLAYLIST, PLAYLISTS, DISPLAY_NAME
from playlist import get_playlist_songs, get_playlist_info, download_from_user_playlist, download_playlist from playlist import get_playlist_songs, get_playlist_info, download_from_user_playlist, download_playlist
from podcast import download_episode, get_show_episodes from podcast import download_episode, get_show_episodes
from track import download_track, get_saved_tracks from track import download_track, get_saved_tracks
@ -89,64 +89,159 @@ def client() -> None:
def search(search_term): def search(search_term):
""" Searches Spotify's API for relevant data """ """ Searches Spotify's API for relevant data """
params = {'limit': '10', 'offset': '0', 'q': search_term, 'type': 'track,album,artist,playlist'} params = {'limit': '10',
'offset': '0',
'q': search_term,
'type': 'track,album,artist,playlist'}
# Parse args
splits = search_term.split()
for split in splits:
index = splits.index(split)
if split[0] == '-' and len(split) > 1:
if len(splits)-1 == index:
raise IndexError('No parameters passed after option: {}\n'.
format(split))
if split == '-l' or split == '-limit':
try:
int(splits[index+1])
except ValueError:
raise ValueError('Paramater passed after {} option must be an integer.\n'.
format(split))
if int(splits[index+1]) > 50:
raise ValueError('Invalid limit passed. Max is 50.\n')
params['limit'] = splits[index+1]
if split == '-t' or split == '-type':
allowed_types = ['track', 'playlist', 'album', 'artist']
passed_types = []
for i in range(index+1, len(splits)):
if splits[i][0] == '-':
break
if splits[i] not in allowed_types:
raise ValueError('Parameters passed after {} option must be from this list:\n{}'.
format(split, '\n'.join(allowed_types)))
passed_types.append(splits[i])
params['type'] = ','.join(passed_types)
if len(params['type']) == 0:
params['type'] = 'track,album,artist,playlist'
# Clean search term
search_term_list = []
for split in splits:
if split[0] == "-":
break
search_term_list.append(split)
if not search_term_list:
raise ValueError("Invalid query.")
params["q"] = ' '.join(search_term_list)
resp = ZSpotify.invoke_url_with_params(SEARCH_URL, **params) resp = ZSpotify.invoke_url_with_params(SEARCH_URL, **params)
counter = 1 counter = 1
tracks = resp[TRACKS][ITEMS] dics = []
if len(tracks) > 0:
print('### TRACKS ###') if TRACK in params['type'].split(','):
track_data = [] tracks = resp[TRACKS][ITEMS]
for track in tracks: if len(tracks) > 0:
if track[EXPLICIT]: print('### TRACKS ###')
explicit = '[E]' track_data = []
else: for track in tracks:
explicit = '' if track[EXPLICIT]:
track_data.append([counter, f'{track[NAME]} {explicit}', explicit = '[E]'
','.join([artist[NAME] for artist in track[ARTISTS]])]) else:
counter += 1 explicit = ''
total_tracks = counter - 1
print(tabulate(track_data, headers=['S.NO', 'Name', 'Artists'], tablefmt='pretty')) track_data.append([counter, f'{track[NAME]} {explicit}',
print('\n') ','.join([artist[NAME] for artist in track[ARTISTS]])])
dics.append({
ID : track[ID],
NAME : track[NAME],
'type' : TRACK,
})
counter += 1
total_tracks = counter - 1
print(tabulate(track_data, headers=['S.NO', 'Name', 'Artists'], tablefmt='pretty'))
print('\n')
del tracks
del track_data
else: else:
total_tracks = 0 total_tracks = 0
albums = resp[ALBUMS][ITEMS] if ALBUM in params['type'].split(','):
if len(albums) > 0: albums = resp[ALBUMS][ITEMS]
print('### ALBUMS ###') if len(albums) > 0:
album_data = [] print('### ALBUMS ###')
for album in albums: album_data = []
album_data.append([counter, album[NAME], ','.join([artist[NAME] for artist in album[ARTISTS]])]) for album in albums:
counter += 1 album_data.append([counter, album[NAME],
total_albums = counter - total_tracks - 1 ','.join([artist[NAME] for artist in album[ARTISTS]])])
print(tabulate(album_data, headers=['S.NO', 'Album', 'Artists'], tablefmt='pretty')) dics.append({
print('\n') ID : album[ID],
NAME : album[NAME],
'type' : ALBUM,
})
counter += 1
total_albums = counter - total_tracks - 1
print(tabulate(album_data, headers=['S.NO', 'Album', 'Artists'], tablefmt='pretty'))
print('\n')
del albums
del album_data
else: else:
total_albums = 0 total_albums = 0
artists = resp[ARTISTS][ITEMS] if ARTIST in params['type'].split(','):
if len(artists) > 0: artists = resp[ARTISTS][ITEMS]
print('### ARTISTS ###') if len(artists) > 0:
artist_data = [] print('### ARTISTS ###')
for artist in artists: artist_data = []
artist_data.append([counter, artist[NAME]]) for artist in artists:
counter += 1 artist_data.append([counter, artist[NAME]])
total_artists = counter - total_tracks - total_albums - 1 dics.append({
print(tabulate(artist_data, headers=['S.NO', 'Name'], tablefmt='pretty')) ID : artist[ID],
print('\n') NAME : artist[NAME],
'type' : ARTIST,
})
counter += 1
total_artists = counter - total_tracks - total_albums - 1
print(tabulate(artist_data, headers=['S.NO', 'Name'], tablefmt='pretty'))
print('\n')
del artists
del artist_data
else: else:
total_artists = 0 total_artists = 0
playlists = resp[PLAYLISTS][ITEMS] if PLAYLIST in params['type'].split(','):
print('### PLAYLISTS ###') playlists = resp[PLAYLISTS][ITEMS]
playlist_data = [] if len(playlists) > 0:
for playlist in playlists: print('### PLAYLISTS ###')
playlist_data.append([counter, playlist[NAME], playlist[OWNER][DISPLAY_NAME]]) playlist_data = []
counter += 1 for playlist in playlists:
print(tabulate(playlist_data, headers=['S.NO', 'Name', 'Owner'], tablefmt='pretty')) playlist_data.append([counter, playlist[NAME], playlist[OWNER][DISPLAY_NAME]])
print('\n') dics.append({
ID : playlist[ID],
NAME : playlist[NAME],
'type' : PLAYLIST,
})
counter += 1
total_playlists = counter - total_artists - total_tracks - total_albums - 1
print(tabulate(playlist_data, headers=['S.NO', 'Name', 'Owner'], tablefmt='pretty'))
print('\n')
del playlists
del playlist_data
else:
total_playlists = 0
if len(tracks) + len(albums) + len(playlists) == 0: if total_tracks + total_albums + total_artists + total_playlists == 0:
print('NO RESULTS FOUND - EXITING...') print('NO RESULTS FOUND - EXITING...')
else: else:
selection = '' selection = ''
@ -155,13 +250,15 @@ def search(search_term):
inputs = split_input(selection) inputs = split_input(selection)
for pos in inputs: for pos in inputs:
position = int(pos) position = int(pos)
if position <= total_tracks: for dic in dics:
track_id = tracks[position - 1][ID] print_pos = dics.index(dic) + 1
download_track(track_id) if print_pos == position:
elif position <= total_albums + total_tracks: if dic['type'] == TRACK:
download_album(albums[position - total_tracks - 1][ID]) download_track(dic[ID])
elif position <= total_artists + total_tracks + total_albums: elif dic['type'] == ALBUM:
download_artist_albums(artists[position - total_tracks - total_albums - 1][ID]) download_album(dic[ID])
else: elif dic['type'] == ARTIST:
download_playlist(playlists, position - total_tracks - total_albums - total_artists) download_artist_albums(dic[ID])
else:
download_playlist(dic)

View File

@ -54,6 +54,8 @@ ERROR = 'error'
EXPLICIT = 'explicit' EXPLICIT = 'explicit'
PLAYLIST = 'playlist'
PLAYLISTS = 'playlists' PLAYLISTS = 'playlists'
OWNER = 'owner' OWNER = 'owner'

View File

@ -47,13 +47,13 @@ def get_playlist_info(playlist_id):
return resp['name'].strip(), resp['owner']['display_name'].strip() return resp['name'].strip(), resp['owner']['display_name'].strip()
def download_playlist(playlists, playlist_number): def download_playlist(playlist):
"""Downloads all the songs from a playlist""" """Downloads all the songs from a playlist"""
playlist_songs = [song for song in get_playlist_songs(playlists[int(playlist_number) - 1][ID]) if song[TRACK][ID]] playlist_songs = [song for song in get_playlist_songs(playlist[ID]) if song[TRACK][ID]]
p_bar = tqdm(playlist_songs, unit='song', total=len(playlist_songs), unit_scale=True) p_bar = tqdm(playlist_songs, unit='song', total=len(playlist_songs), unit_scale=True)
for song in p_bar: for song in p_bar:
download_track(song[TRACK][ID], sanitize_data(playlists[int(playlist_number) - 1][NAME].strip()) + '/', download_track(song[TRACK][ID], sanitize_data(playlist[NAME].strip()) + '/',
disable_progressbar=True) disable_progressbar=True)
p_bar.set_description(song[TRACK][NAME]) p_bar.set_description(song[TRACK][NAME])