#!/bin/bash
# Retrieves actual mp3 from soundcloud song or playlist link
# June 2014


read -p "Enter song or playlist link: " link
isPlaylist=`echo $link | egrep -o sets`
if [ "$isPlaylist" == "sets" ]
then
	trackName=$(basename $link)
	#rm -R playlist-$trackName
	#create a directory and enter it
	if [ -d playlist-"$trackName" ]; then
		echo "\nDirectory exists, switching to it now...\n"
		cd playlist-$trackName
	else
		mkdir playlist-$trackName && cd $_
	fi
	curl $link -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so html.txt
	newLink=${link#*//}
echo $newLink
	#get the AppVersion string from the response
	appVersion=`egrep -o "A.start\('[a-z0-9]+'" html.txt | egrep -o "[a-z0-9]{6,}"`
echo $appVersion
	#get the clientId to make the request for the proper js file (if the name is dynamic)
	
	#clientIdRequest=`egrep -o 'src="https://a-v2.sndcdn.com/assets/\S+\s*class="sssr-js"' html.txt | egrep -o "https:\S+\.js"`
	clientIdRequest=`cat html.txt | egrep -o 'https://a-v2.sndcdn.com/assets/sc-[^"]+'`
echo $clientIdRequest
	curl $clientIdRequest -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so clientid_response.txt
	
	#extract clientId
	clientId=`egrep -o 'applyTo\([a-z]\),r="[a-z0-9]{20,}' clientid_response.txt | egrep -o '[a-z0-9]{20,}'`
echo $clientId
	#get the playlistId
	curl "https://api.soundcloud.com/resolve?url=https%3A//$newLink&_status_code_map%5B302%5D=200&_status_format=json&client_id=$clientId&app_version=$appVersion" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so playlistId.txt

	playlistNumber=`egrep -o "/playlists/[0-9]+" playlistId.txt | egrep -o [0-9]+`
echo "playlistNumber is $playlistNumber"
	
	curl "https://api.soundcloud.com/playlists/$playlistNumber?client_id=$clientId" -so playlistInfo.txt

	trackCount=`cat playlistInfo.txt | egrep -c '<kind>track</kind>'`
	echo "\nThere are $trackCount tracks in the playlist. Downloading now...\n"
	
	cat playlistInfo.txt | egrep -o '<uri>https://api.soundcloud.com/tracks/[0-9]+</uri>' | egrep -o [0-9]+ > playlistNumbers.txt
	cat playlistInfo.txt | egrep -o '\s{6}<permalink-url>https?://soundcloud.com/(?:\w+-?)+/\S+</permalink-url>' | egrep -o 'http://soundcloud.com/(\w+-?/?)+' > playlistLinks.txt

	#array with playlist track numbers
	playlistItems=($(egrep -o [0-9]+ playlistNumbers.txt))
	
	#array with playlist track URLs
	playlistLinks=($(egrep -o 'soundcloud.com/(\w+-?/?)+' playlistLinks.txt))

	counter=0
	while [ "$counter" -lt "$trackCount" ]
	do
	
	#iterate through each track in array and dl it
	curl "https://api.soundcloud.com/i1/tracks/${playlistItems[$counter]}/streams?client_id=$clientId&app_version=$appVersion" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so trackLocation.txt
	
	#extract trackLocation from server
	trackLocation=`egrep -o ':"\S+"}' trackLocation.txt | egrep -o 'https[^"]+'`
	
	#the name of the track on file will be the basename of the original link (counter in array)
	trackName=$(basename ${playlistLinks[$counter]})
	
	isRTMP=`cat trackLocation.txt | egrep -o 'rtmp://'`
		if [ "$isRTMP" == "rtmp://" ];then
		
			
			#send request to anything2mp3.com to convert rtmp protocol files
			curl "http://anything2mp3.com/" --output anything_html.txt -c cookies.txt
			#generate request to anything2mp3 containing original link to RTMP-ed song
			curl -d "url=https%3A%2F%2F${playlistLinks[$counter]}&op=Convert&form_id=videoconverter_form" "http://anything2mp3.com/" -H "Content-Type:application/x-www-form-urlencoded" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -b cookies.txt -c newcookies.txt -L -o success.txt
			rtmpURL=`grep "system/temporary" success.txt | egrep -o "http:\S+download=1"`
			
			curl $rtmpURL -b cookies.txt -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -s --output "00"$counter+$trackName.mp3
		
		else
			
			#remove \u0026 from URLS that have it
			trackURL=$(sed -e "s/\\\\u0026/\\&/g" <<< $trackLocation)
	
			curl $trackURL -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -s --output "00"$counter+$trackName.mp3
		
		fi
		counter=$((counter+1))
		sleep 1
	done
	echo "\nPlease check folder with playlist title\n"
	rm *.txt
	
		
else
	curl $link -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so html.txt
	newLink=${link#*//}
	trackName=$(basename $link)

	#get the AppVersion string from the response
	appVersion=`egrep -o "A.start\('[a-z0-9]+'" html.txt | egrep -o "[a-z0-9]{6,}"`

	#get the clientId to make the request for the proper js file (if the name is dynamic)
	clientIdRequest=`cat html.txt | egrep -o 'https://a-v2.sndcdn.com/assets/sc-[^"]+'`

	curl $clientIdRequest -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so clientid_response.txt

	#extract clientID
	clientId=`egrep -o 'applyTo\([a-z]\),r="[a-z0-9]{20,}' clientid_response.txt | egrep -o '[a-z0-9]{20,}'`

	#get the trackNumber
	curl "https://api.soundcloud.com/resolve?url=https%3A//$newLink&_status_code_map%5B302%5D=200&_status_format=json&client_id=$clientId&app_version=$appVersion" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so trackId.txt

	trackNumber=`egrep -o '/tracks/[0-9]+' trackId.txt | egrep -o '[0-9]+'`
	#echo $trackNumber

	#make the request with all three extracted items
	curl "https://api.soundcloud.com/i1/tracks/$trackNumber/streams?client_id=$clientId&app_version=$appVersion" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -so trackLocation.txt

	isRTMP=`cat trackLocation.txt | egrep -o 'rtmp://'`
	if [ "$isRTMP" == "rtmp://" ];then
		
		echo $newLink
		#send request to anything2mp3.com to convert rtmp protocol files
		curl "http://anything2mp3.com/" --output anything_html.txt -c cookies.txt
		#form_build_id=`egrep -o 'edit-submit--2.+' anything_html.txt | egrep -o 'value="form-.+' | egrep -o 'form[^"]+'`
		curl -d "url=https%3A%2F%2F$newLink&op=Convert&form_id=videoconverter_form" "http://anything2mp3.com/" -H "Content-Type:application/x-www-form-urlencoded" -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" -b cookies.txt -c newcookies.txt -L -o success.txt
		rtmpURL=`grep "system/temporary" success.txt | egrep -o "http:\S+download=1"`
		curl $rtmpURL -b cookies.txt -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" --output $trackName.mp3
		
	else
	
		#extract trackLocation from server
		trackLocation=`egrep -o ':"\S+"}' trackLocation.txt | egrep -o 'https[^"]+'`
	
		#remove \u0026 from URLS that have it
		trackURL=$(sed -e "s/\\\\u0026/\\&/g" <<< $trackLocation)

		cd tracks
		curl $trackURL -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0" --output $trackName.mp3
		echo "\nCheck folder for mp3 file\n"
	fi
fi

# Major changes this version - egrep instead of grep,
# so using os x specific grep (egrep -o) mostly
# also adding details that other versions of grep and curl let slide
# like not specifying an output file for rtmp download