Display iTunes Cover & Currently Playing Track

Here is my version of the code which downloads the artwork from Apple Music using the iTunes search API. I couldn't make it work otherwise.

What it does is basically taking the name, artist and album, sending the request as follows:

itunes.apple.com/search?term=Name+Artist+Album&limit=1

Note: It uses JSON Helper
http://www.mousedown.net/mouseware/JSONHelper.html

if application "iTunes" is running then
	tell application "BetterTouchTool" to set priorTrackId to get_number_variable "trackId"
	tell application "iTunes"
		if player state is playing and id of current track is not priorTrackId then
			tell current track
				if exists (every artwork) then
					tell artwork 1
						set srcBytes to raw data
						-- figure out the proper file extension
						if format is «class PNG » then
							set ext to ".png"
						else
							set ext to ".jpg"
						end if
					end tell
					set fileName to ((((path to application support folder from user domain) as text) & "BetterTouchTool:" as text) & "itunes_cover" & ext)
					-- write to file
					set outFile to open for access file fileName with write permission
					-- truncate the file
					set eof outFile to 0
					-- write the image bytes to the file
					write srcBytes to outFile
					close access outFile
				else
					set searchTerm to name & " " & artist & " " & album
					set responseJson to do shell script "curl --data-urlencode \"term=" & searchTerm & "\" --data-urlencode \"limit=1\" https://itunes.apple.com/search"
					tell application "JSON Helper"
						set responseData to read JSON from responseJson
						set resultCount to resultCount of responseData
						if (resultCount is not 0) then
							set previewUrl to artworkUrl60 of item 1 of results of responseData
							do shell script "curl " & previewUrl & " > $HOME/Library/Application\\ Support/BetterTouchTool/itunes_cover.jpg"
						end if
					end tell
					if (resultCount is not 0) then
						set fileName to ((((path to application support folder from user domain) as text) & "BetterTouchTool:" as text) & "itunes_cover" & ".jpg")
					else
						set fileName to (((path to application "iTunes") as text) & "Contents:Resources:iTunes.icns")
					end if
				end if
				set maxSize to 60
				set artistName to artist
				set albumName to album
				set trackName to name
				set trackInfo to artistName & " - " & trackName
				set trackId to id
				tell application "BetterTouchTool" to set_number_variable "trackId" to trackId
			end tell
			return "{\"text\":\"" & trackInfo & "\", \"icon_path\":\"" & (POSIX path of fileName as text) & "\"}"
		end if
	end tell
else
	return "{\"text\":\"\"}"
end if
1 Like