Using the Lastfm API
Requirements:
- jq for parsing JSON data
1. Get an API key from Last.fm
2. Get request token - auth.getToken
2.1. Constructing API signatures
- sort all parameters and their values alphabetically by name and concatenate them in the form <name><value>, for auth.getToken:
api_keyYOUR_API_KEYmethodauth.getToken
For easier sorting, I use a python prompt
>>> sorted(['method', 'track', 'artist', 'api_key', 'api_sig', 'sk']) ['api_key', 'api_sig', 'artist', 'method', 'sk', 'track']
- append your shared secret to the end:
api_keyYOUR_API_KEYmethodauth.getTokenSHARED_SECRET
- generate MD5 hash
TOKEN_SIG=$(echo -n "api_keyYOUR_API_KEYmethodauth.getTokenSHARED_SECRET" | md5sum | cut -f1 -d ' ')**
2.2. Getting token
TOKEN=$(wget -q \ "https://ws.audioscrobbler.com/2.0/?method=auth.getToken&api_key=${LASTFM_API_KEY}&api_sig=${TOKEN_SIG}&format=json" -O - \ | jq -r '.token')
3. Getting session key - auth.getSession
3.1. Getting api_sig
SESSION_API_SIG=$(echo -n "api_key${LASTFM_API_KEY}methodauth.getSessiontoken${TOKEN}${SHARED_SECRET}" | md5sum | cut -f1 -d' ')
3.2. Authorizing token
firefox "http://www.last.fm/api/auth/?api_key=${LASTFM_API_KEY}&token=${TOKEN}"
This will open a browser and wait for authentication from user
3.3. Getting session key with authorized token
SESSION_KEY=$(wget -q "https://ws.audioscrobbler.com/2.0/?method=auth.getSession&api_key=${LASTFM_API_KEY}&api_sig=${SESSION_API_SIG}&token=${TOKEN}&format=json" -O - | jq -r '.session.key')
Save this session key somewhere and use it for future API calls. If you lose this key, you’ll have to make another token, authorize it and get a new session key.
4. Making an authorized API call
If a call requires a API sigature, make one as described in 2.1.
In this example I’ll be using track.love (the same goes for track.unlove)
$ LOVE_API_SIG="$(echo -n "api_key${LASTFM_API_KEY}artist${ARTIST}methodtrack.lovesk${SESSION_KEY}track${TRACK}${SHARED_SECRET}" | md5sum | cut -f 1 -d ' ')" $ curl -s -i -d \ 'method=track.love&track=${TRACK}&artist=${ARTIST}&api_key=${LASTFM_API_KEY}&sk=${SESSION_KEY}&api_sig=${LOVE_API_SIG}' \ -X POST http://ws.audioscrobbler.com/2.0/ \ | grep -q '<lfm status=\'ok\'' && echo 'Added $(mpc current) to loved tracks.'uploaded: Thu, 07 Apr 2022
tags: