#!python

from gmusicapi import Musicmanager
from os.path import expanduser, join


# Download all of a user's purchased and uploaded songs.

mm = Musicmanager()
if not mm.login():
    print('Login failed: did you run gpymusic-oauth-login?')
    exit(1)

songs = {}
for song in mm.get_purchased_songs():
    songs[song['id']] = ' - '.join(
        [song['title'], song['artist'], song['album']]
    )
for song in mm.get_uploaded_songs():
    songs[song['id']] = ' - '.join(
        [song['title'], song['artist'], song['album']]
    )

print('Downloading %d songs to ~/.local/share/gpymusic/songs. '
      'This might take a while...' % len(songs))

song_dir = join(expanduser('~'), '.local', 'share', 'gpymusic', 'songs')
i = 1

for i, id in enumerate(songs):
    print('%d/%d: %s' % (i+1, len(songs), songs[id]))
    # Since filenames cannot contain '/', we replace them with '---'.
    dl_path = join(song_dir, '%s.mp3' % songs[id].replace('/', '---'))
    with open(dl_path, 'wb') as f:
        f.write(mm.download_song(id)[1])
