Skip to content

Instantly share code, notes, and snippets.

@alanzchen
Created July 7, 2019 19:32
Show Gist options
  • Save alanzchen/db28bb9abad46d4a5a0bd3e288716c5b to your computer and use it in GitHub Desktop.
Save alanzchen/db28bb9abad46d4a5a0bd3e288716c5b to your computer and use it in GitHub Desktop.
Last.fm user feed to Apple Music
#!/usr/local/bin/python3
# coding=utf-8
"""
# <bitbar.title>Your Music</bitbar.title>
# <bitbar.version>v1</bitbar.version>
# <bitbar.author>alan</bitbar.author>
# <bitbar.author.github>alanzchen</bitbar.author.github>
# <bitbar.desc>
# I love you(r) (music).
# </bitbar.desc>
"""
import requests
import timeago
from datetime import datetime
import json
cache_loaded = False
cache_file = '/tmp/cache.json'
def get_url(song_name):
if song_name in cache:
return cache[song_name]
try:
response = requests.get(
url="https://itunes.apple.com/search",
params={
"term": song_name,
"entity": "song",
},
).json()
url = response['results'][0]['trackViewUrl']
cache[song_name] = url
json.dump(cache, open(cache_file, 'w'))
return url
except:
return None
try:
with open(cache_file, 'r') as f:
cache = json.loads(f.read())
cache_loaded = True
except:
cache = {}
r = requests.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=[ REPLACE USERNAME HERE ]&api_key=[ REPLACE YOUR API HERE ]&format=json").json()
now = datetime.now()
songs = r['recenttracks']['track'][:50]
print("❤️")
print("---")
for s in songs:
print(s['name'] + ", " + timeago.format(datetime.utcfromtimestamp(int(s['date']['uts'])), now) + " | href=" + (get_url(s['name'] + " " + s['album']['#text']) or s['url']))
print("---")
if cache_loaded:
print("Loaded cache with {} items".format(len(cache)))
else:
print("Did not load cache.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment