lastfm-backup/lastfm_backup.py

62 lines
2.0 KiB
Python
Raw Normal View History

2016-10-18 05:27:59 +03:00
#!/usr/bin/env python3
import json
import urllib.request
2017-04-23 20:35:19 +03:00
import os.path
2016-10-18 05:27:59 +03:00
__author__ = 'Alexander Popov'
__version__ = '1.0.1'
2016-10-18 05:27:59 +03:00
__license__ = 'Unlicense'
def get_pages(username, api_key):
response = urllib.request.urlopen(
'http://ws.audioscrobbler.com/2.0/'
2017-04-23 20:35:19 +03:00
'?method=user.getrecenttracks&user={0}&api_key={1}&format=json'
'&limit=200'.format(username, api_key)).read().decode("utf8")
2016-10-18 05:27:59 +03:00
pages = int(json.loads(response)['recenttracks']['@attr']['totalPages'])
return(pages)
2016-10-19 14:04:20 +03:00
def get_scrobbles(username, api_key, page):
2017-04-23 20:35:19 +03:00
response = json.loads(urllib.request.urlopen(
'http://ws.audioscrobbler.com/2.0/'
'?method=user.getrecenttracks&user={0}&api_key={1}&format=json'
2017-05-13 02:19:37 +03:00
'&limit=200&page={2}'.format(username, api_key, page)
2017-04-23 20:35:19 +03:00
).read().decode("utf8"))['recenttracks']['track']
2016-10-19 14:04:20 +03:00
return(response)
2016-10-18 05:27:59 +03:00
if __name__ == '__main__':
2017-04-23 20:35:19 +03:00
CFG = dict()
if os.path.exists('./config.json'):
with open('./config.json') as f:
CFG = json.loads(f.read())
else:
CFG['api_key'] = input('API Key: ')
CFG['username'] = input('Username: ')
PAGES = get_pages(CFG['username'], CFG['api_key'])
curPage = 1
tracks = []
while curPage <= PAGES:
print('\r{0}% [{1} of {2}]'.format((curPage * 100 / PAGES), curPage, PAGES), end='')
2017-04-23 20:35:19 +03:00
response = get_scrobbles(CFG['username'], CFG['api_key'], curPage)
2016-10-18 05:27:59 +03:00
for track in response:
2017-04-23 20:35:19 +03:00
tracks.append({'artist': track['artist']['#text'],
2016-10-18 05:27:59 +03:00
'name': track['name'],
'album': track['album']['#text'],
'date': track['date']['uts']})
2017-04-23 20:35:19 +03:00
curPage += 1
2016-10-18 05:27:59 +03:00
2017-04-23 20:35:19 +03:00
with open('%s.json' % (CFG['username']), 'w+', encoding='utf-8') as f:
2016-10-18 05:27:59 +03:00
f.write(
2017-04-23 20:35:19 +03:00
json.dumps(tracks, indent=4, sort_keys=True, ensure_ascii=False))
print('\n{0} tracks saved in {1}.json!'.format(
2017-04-23 20:35:19 +03:00
len(tracks), CFG['username'],))