Merge branch 'search_options'

This commit is contained in:
yiannisha 2021-10-23 17:22:19 +03:00
commit 6050630407

View File

@ -334,91 +334,188 @@ def search(search_term): # pylint: disable=too-many-locals,too-many-branches
""" Searches Spotify's API for relevant data """ """ Searches Spotify's API for relevant data """
token = SESSION.tokens().get("user-read-email") token = SESSION.tokens().get("user-read-email")
params = {
"limit" : "10",
"q" : search_term,
"type" : set(),
}
# Block for parsing passed arguments
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"]
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)))
params["type"].add(splits[i])
if len(params["type"]) == 0:
params["type"] = {"track", "album", "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 = requests.get( resp = requests.get(
"https://api.spotify.com/v1/search", "https://api.spotify.com/v1/search",
{ {
"limit": "10", "limit": params["limit"],
"offset": "0", "offset": "0",
"q": search_term, "q": params["q"],
"type": "track,album,artist,playlist" "type": ",".join(params["type"])
}, },
headers={"Authorization": f"Bearer {token}"}, headers={"Authorization": f"Bearer {token}"},
) )
# print(resp.json()) # print(resp.json())
i = 1 enum = 1
tracks = resp.json()["tracks"]["items"] dics = []
if len(tracks) > 0:
print("### TRACKS ###") # add all returned tracks to dics
for track in tracks: if "track" in params["type"]:
if track["explicit"]: tracks = resp.json()["tracks"]["items"]
explicit = "[E]" if len(tracks) > 0:
else: print("### TRACKS ###")
explicit = "" for track in tracks:
print(f"{i}, {track['name']} {explicit} | {','.join([artist['name'] for artist in track['artists']])}") if track["explicit"]:
i += 1 explicit = "[E]"
total_tracks = i - 1 else:
explicit = ""
# collect needed data
dic = {
"id" : track["id"],
"name" : track["name"],
"artists/owner" : [artist["name"] for artist in track["artists"]],
"type" : "track",
}
dics.append(dic)
print("{}, {} {} | {}".format(
enum,
dic["name"],
explicit,
",".join(dic["artists/owner"]),
))
enum += 1
total_tracks = enum - 1
print("\n") print("\n")
# free up memory
del tracks
else: else:
total_tracks = 0 total_tracks = 0
albums = resp.json()["albums"]["items"] if "album" in params["type"]:
if len(albums) > 0: albums = resp.json()["albums"]["items"]
print("### ALBUMS ###") if len(albums) > 0:
for album in albums: print("### ALBUMS ###")
print(f"{i}, {album['name']} | {','.join([artist['name'] for artist in album['artists']])}") for album in albums:
i += 1 # collect needed data
total_albums = i - total_tracks - 1 dic = {
"id" : album["id"],
"name" : album["name"],
"artists/owner" : [artist["name"] for artist in album["artists"]],
"type" : "album",
}
dics.append(dic)
print("{}, {} | {}".format(
enum,
dic["name"],
",".join(dic["artists/owner"]),
))
enum += 1
total_albums = enum - total_tracks - 1
print("\n") print("\n")
# free up memory
del albums
else: else:
total_albums = 0 total_albums = 0
artists = resp.json()["artists"]["items"] if "playlist" in params["type"]:
if len(artists) > 0: playlists = resp.json()["playlists"]["items"]
print("### ARTISTS ###") if len(playlists) > 0:
for artist in artists: print("### PLAYLISTS ###")
print("%d, %s" % ( for playlist in playlists:
i, # collect needed data
artist["name"], dic = {
)) "id" : playlist["id"],
i += 1 "name" : playlist["name"],
total_artists = i - total_tracks - total_albums - 1 "artists/owner" : [playlist["owner"]["display_name"]],
"type" : "playlist",
}
dics.append(dic)
print("{}, {} | {}".format(
enum,
dic["name"],
",".join(dic['artists/owner']),
))
enum += 1
total_playlists = enum - total_tracks - total_albums - 1
print("\n") print("\n")
# free up memory
del playlists
else: else:
total_artists = 0 total_playlists = 0
playlists = resp.json()["playlists"]["items"] if total_tracks + total_albums + total_playlists == 0:
print("### PLAYLISTS ###")
for playlist in playlists:
print(f"{i}, {playlist['name']} | {playlist['owner']['display_name']}")
i += 1
print("\n")
if len(tracks) + len(albums) + len(playlists) == 0:
print("NO RESULTS FOUND - EXITING...") print("NO RESULTS FOUND - EXITING...")
else: else:
selection = str(input("SELECT ITEM(S) BY ID: ")) selection = str(input("SELECT ITEM(S) BY ID: "))
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"] # find dictionary
download_track(track_id) print_pos = dics.index(dic) + 1
elif position <= total_albums + total_tracks: if print_pos == position:
download_album(albums[position - total_tracks - 1]["id"]) # if request is for track
elif position <= total_artists + total_tracks + total_albums: if dic["type"] == "track":
download_artist_albums(artists[position - total_tracks - total_albums -1]["id"]) download_track(dic["id"])
else: # if request is for album
playlist_choice = playlists[position - if dic["type"] == "album":
total_tracks - total_albums - total_artists - 1] download_album(dic["id"])
playlist_songs = get_playlist_songs( # if request is for playlist
token, playlist_choice["id"]) if dic["type"] == "playlist":
for song in playlist_songs: playlist_songs = get_playlist_songs(token, dic["id"])
if song["track"]["id"] is not None: for song in playlist_songs:
download_track(song["track"]["id"], sanitize_data( if song["track"]["id"] is not None:
playlist_choice["name"].strip()) + "/") download_track(song["track"]["id"],
print("\n") sanitize_data(dic["name"].strip()) + "/")
print("\n")
def get_song_info(song_id): def get_song_info(song_id):