Rewrote the search function

It still works in the same way and no
other functions need to be changed. Just
changed it to store needed data about each
track/album/playlist in a dictionary so
tracking it in the end is simpler.
This commit is contained in:
yiannisha 2021-10-23 16:06:34 +03:00
parent 3c3a2acf27
commit 7d81eb5cc6

View File

@ -351,20 +351,32 @@ def search(search_term):
""" 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" : ["track","album","playlist"]
}
# ADD BLOCK FOR READING OPTIONS AND CLEAN SEARCH_TERM
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,playlist" "type": ",".join(params["type"])
}, },
headers={"Authorization": "Bearer %s" % token}, headers={"Authorization": "Bearer %s" % token},
) )
# print(resp.json()) # print(resp.json())
i = 1 enum = 1
dics = []
# add all returned tracks to dics
if "track" in params["type"]:
tracks = resp.json()["tracks"]["items"] tracks = resp.json()["tracks"]["items"]
if len(tracks) > 0: if len(tracks) > 0:
print("### TRACKS ###") print("### TRACKS ###")
@ -373,65 +385,108 @@ def search(search_term):
explicit = "[E]" explicit = "[E]"
else: else:
explicit = "" explicit = ""
print("%d, %s %s | %s" % ( # collect needed data
i, dic = {
track["name"], "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, explicit,
",".join([artist["name"] for artist in track["artists"]]), ",".join(dic["artists/owner"]),
)) ))
i += 1 enum += 1
total_tracks = i - 1 total_tracks = enum - 1
print("\n") print("\n")
# free up memory
del tracks
else: else:
total_tracks = 0 total_tracks = 0
if "album" in params["type"]:
albums = resp.json()["albums"]["items"] albums = resp.json()["albums"]["items"]
if len(albums) > 0: if len(albums) > 0:
print("### ALBUMS ###") print("### ALBUMS ###")
for album in albums: for album in albums:
print("%d, %s | %s" % ( # collect needed data
i, dic = {
album["name"], "id" : album["id"],
",".join([artist["name"] for artist in album["artists"]]), "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"]),
)) ))
i += 1 enum += 1
total_albums = i - total_tracks - 1 total_albums = enum - total_tracks - 1
print("\n") print("\n")
# free up memory
del albums
else: else:
total_albums = 0 total_albums = 0
if "playlist" in params["type"]:
playlists = resp.json()["playlists"]["items"] playlists = resp.json()["playlists"]["items"]
print("### PLAYLISTS ###") print("### PLAYLISTS ###")
if len(playlists) > 0:
for playlist in playlists: for playlist in playlists:
print("%d, %s | %s" % ( # collect needed data
i, dic = {
playlist["name"], "id" : playlist["id"],
playlist['owner']['display_name'], "name" : playlist["name"],
)) "artists/owner" : [playlist["owner"]["display_name"]],
i += 1 "type" : "playlist",
print("\n") }
dics.append(dic)
if len(tracks) + len(albums) + len(playlists) == 0: print("{}, {} | {}".format(
enum,
dic["name"],
",".join(dic['artists/owner']),
))
enum += 1
total_playlists = enum - total_tracks - total_albums - 1
print("\n")
# free up memory
del playlists
else:
total_playlists = 0
if total_tracks + total_albums + total_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
else: if dic["type"] == "track":
playlist_choice = playlists[position - download_track(dic["id"])
total_tracks - total_albums - 1] # if request is for album
playlist_songs = get_playlist_songs( if dic["type"] == "album":
token, playlist_choice['id']) download_album(dic["id"])
# if request is for playlist
if dic["type"] == "playlist":
playlist_songs = get_playlist_songs(token, dic["id"])
for song in playlist_songs: for song in playlist_songs:
if song['track']['id'] is not None: if song["track"]["id"] is not None:
download_track(song['track']['id'], sanitize_data( download_track(song["track"]["id"],
playlist_choice['name'].strip()) + "/") sanitize_data(dic["name"].strip()) + "/")
print("\n") print("\n")