Skip to content

Instantly share code, notes, and snippets.

@hexaflexahexagon
Created December 20, 2021 14:55
Show Gist options
  • Save hexaflexahexagon/e14c0e1620ae60b1b268a95fa8e0db1d to your computer and use it in GitHub Desktop.
Save hexaflexahexagon/e14c0e1620ae60b1b268a95fa8e0db1d to your computer and use it in GitHub Desktop.
# Retrieve a random song from Apple's iTunes API
#!/bin/bash
# Retrieve a random song from Apple's iTunes API
# https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/
load() {
# Echo, find key pair, strip to just value, remove leading and trailing "'s
echo $output | grep -o $1'":"[^"]*"' | cut -d':' -f2- | sed 's/^.\|.$//g'
}
# random number
high=3
low=1
randNum=$(python3 -c "import random; print(random.randint($low, $high))")
# random 2 letters
rand=$(echo $RANDOM | md5sum | head -c $randNum)
output=$(curl -s 'https://itunes.apple.com/search?term='"$rand"'&media=music&entity=song&limit=1')
# this doesn't work since I can't know the range that iTunes uses
#curl -s 'https://itunes.apple.com/lookup?id='"$rand"
if [[ $(load 'artistName') == "" ]]; then
# No response recieved from API, try again
$0
exit -1
fi
echo -n "Artist name: " && load 'artistName'
echo -n "Song name: " && load 'trackName'
echo -n "Song genre: " && load 'primaryGenreName'
echo -n "iTunes link: " && load 'trackViewUrl'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment