playlist.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from const import ITEMS, ID, TRACK, NAME
  2. from termoutput import Printer
  3. from track import download_track
  4. from utils import split_input
  5. from zspotify import ZSpotify
  6. MY_PLAYLISTS_URL = 'https://api.spotify.com/v1/me/playlists'
  7. PLAYLISTS_URL = 'https://api.spotify.com/v1/playlists'
  8. def get_all_playlists():
  9. """ Returns list of users playlists """
  10. playlists = []
  11. limit = 50
  12. offset = 0
  13. while True:
  14. resp = ZSpotify.invoke_url_with_params(MY_PLAYLISTS_URL, limit=limit, offset=offset)
  15. offset += limit
  16. playlists.extend(resp[ITEMS])
  17. if len(resp[ITEMS]) < limit:
  18. break
  19. return playlists
  20. def get_playlist_songs(playlist_id):
  21. """ returns list of songs in a playlist """
  22. songs = []
  23. offset = 0
  24. limit = 100
  25. while True:
  26. resp = ZSpotify.invoke_url_with_params(f'{PLAYLISTS_URL}/{playlist_id}/tracks', limit=limit, offset=offset)
  27. offset += limit
  28. songs.extend(resp[ITEMS])
  29. if len(resp[ITEMS]) < limit:
  30. break
  31. return songs
  32. def get_playlist_info(playlist_id):
  33. """ Returns information scraped from playlist """
  34. (raw, resp) = ZSpotify.invoke_url(f'{PLAYLISTS_URL}/{playlist_id}?fields=name,owner(display_name)&market=from_token')
  35. return resp['name'].strip(), resp['owner']['display_name'].strip()
  36. def download_playlist(playlist):
  37. """Downloads all the songs from a playlist"""
  38. playlist_songs = [song for song in get_playlist_songs(playlist[ID]) if song[TRACK][ID]]
  39. p_bar = Printer.progress(playlist_songs, unit='song', total=len(playlist_songs), unit_scale=True)
  40. enum = 1
  41. for song in p_bar:
  42. download_track('extplaylist', song[TRACK][ID], extra_keys={'playlist': playlist[NAME], 'playlist_num': str(enum).zfill(2)}, disable_progressbar=True)
  43. p_bar.set_description(song[TRACK][NAME])
  44. enum += 1
  45. def download_from_user_playlist():
  46. """ Select which playlist(s) to download """
  47. playlists = get_all_playlists()
  48. count = 1
  49. for playlist in playlists:
  50. print(str(count) + ': ' + playlist[NAME].strip())
  51. count += 1
  52. selection = ''
  53. print('\n> SELECT A PLAYLIST BY ID')
  54. print('> SELECT A RANGE BY ADDING A DASH BETWEEN BOTH ID\'s')
  55. print('> OR PARTICULAR OPTIONS BY ADDING A COMMA BETWEEN ID\'s\n')
  56. while len(selection) == 0:
  57. selection = str(input('ID(s): '))
  58. playlist_choices = map(int, split_input(selection))
  59. for playlist_number in playlist_choices:
  60. playlist = playlists[playlist_number - 1]
  61. print(f'Downloading {playlist[NAME].strip()}')
  62. download_playlist(playlist)
  63. print('\n**All playlists have been downloaded**\n')