album.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from const import ITEMS, ARTISTS, NAME, ID
  2. from termoutput import Printer
  3. from track import download_track
  4. from utils import fix_filename
  5. from zspotify import ZSpotify
  6. ALBUM_URL = 'https://api.spotify.com/v1/albums'
  7. ARTIST_URL = 'https://api.spotify.com/v1/artists'
  8. def get_album_tracks(album_id):
  9. """ Returns album tracklist """
  10. songs = []
  11. offset = 0
  12. limit = 50
  13. while True:
  14. resp = ZSpotify.invoke_url_with_params(f'{ALBUM_URL}/{album_id}/tracks', limit=limit, offset=offset)
  15. offset += limit
  16. songs.extend(resp[ITEMS])
  17. if len(resp[ITEMS]) < limit:
  18. break
  19. return songs
  20. def get_album_name(album_id):
  21. """ Returns album name """
  22. (raw, resp) = ZSpotify.invoke_url(f'{ALBUM_URL}/{album_id}')
  23. return resp[ARTISTS][0][NAME], fix_filename(resp[NAME])
  24. def get_artist_albums(artist_id):
  25. """ Returns artist's albums """
  26. (raw, resp) = ZSpotify.invoke_url(f'{ARTIST_URL}/{artist_id}/albums?include_groups=album%2Csingle')
  27. # Return a list each album's id
  28. album_ids = [resp[ITEMS][i][ID] for i in range(len(resp[ITEMS]))]
  29. # Recursive requests to get all albums including singles an EPs
  30. while resp['next'] is not None:
  31. (raw, resp) = ZSpotify.invoke_url(resp['next'])
  32. album_ids.extend([resp[ITEMS][i][ID] for i in range(len(resp[ITEMS]))])
  33. return album_ids
  34. def download_album(album):
  35. """ Downloads songs from an album """
  36. artist, album_name = get_album_name(album)
  37. tracks = get_album_tracks(album)
  38. for n, track in Printer.progress(enumerate(tracks, start=1), unit_scale=True, unit='Song', total=len(tracks)):
  39. download_track('album', track[ID], extra_keys={'album_num': str(n).zfill(2), 'artist': artist, 'album': album_name, 'album_id': album}, disable_progressbar=True)
  40. def download_artist_albums(artist):
  41. """ Downloads albums of an artist """
  42. albums = get_artist_albums(artist)
  43. for album_id in albums:
  44. download_album(album_id)