spotify 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #!/usr/bin/env bash
  2. function spotify() {
  3. # Copyright (c) 2012--2018 Harish Narayanan <mail@harishnarayanan.org>
  4. #
  5. # Contains numerous helpful contributions from Jorge Colindres, Thomas
  6. # Pritchard, iLan Epstein, Gabriele Bonetti, Sean Heller, Eric Martin
  7. # and Peter Fonseca.
  8. # Permission is hereby granted, free of charge, to any person
  9. # obtaining a copy of this software and associated documentation files
  10. # (the "Software"), to deal in the Software without restriction,
  11. # including without limitation the rights to use, copy, modify, merge,
  12. # publish, distribute, sublicense, and/or sell copies of the Software,
  13. # and to permit persons to whom the Software is furnished to do so,
  14. # subject to the following conditions:
  15. # The above copyright notice and this permission notice shall be
  16. # included in all copies or substantial portions of the Software.
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  21. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  22. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  23. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. # SOFTWARE.
  25. USER_CONFIG_DEFAULTS="CLIENT_ID=\"\"\nCLIENT_SECRET=\"\"";
  26. USER_CONFIG_FILE="${HOME}/.shpotify.cfg";
  27. if ! [[ -f "${USER_CONFIG_FILE}" ]]; then
  28. touch "${USER_CONFIG_FILE}";
  29. echo -e "${USER_CONFIG_DEFAULTS}" > "${USER_CONFIG_FILE}";
  30. fi
  31. source "${USER_CONFIG_FILE}";
  32. showAPIHelp() {
  33. echo;
  34. echo "Connecting to Spotify's API:";
  35. echo;
  36. echo " This command line application needs to connect to Spotify's API in order to";
  37. echo " find music by name. It is very likely you want this feature!";
  38. echo;
  39. echo " To get this to work, you need to sign up (or in) and create an 'Application' at:";
  40. echo " https://developer.spotify.com/my-applications/#!/applications/create";
  41. echo;
  42. echo " Once you've created an application, find the 'Client ID' and 'Client Secret'";
  43. echo " values, and enter them into your shpotify config file at '${USER_CONFIG_FILE}'";
  44. echo;
  45. echo " Be sure to quote your values and don't add any extra spaces!";
  46. echo " When done, it should look like this (but with your own values):";
  47. echo ' CLIENT_ID="abc01de2fghijk345lmnop"';
  48. echo ' CLIENT_SECRET="qr6stu789vwxyz"';
  49. }
  50. showHelp () {
  51. echo "Usage:";
  52. echo;
  53. echo " `basename $0` <command>";
  54. echo;
  55. echo "Commands:";
  56. echo;
  57. echo " play # Resumes playback where Spotify last left off.";
  58. echo " play <song name> # Finds a song by name and plays it.";
  59. echo " play album <album name> # Finds an album by name and plays it.";
  60. echo " play artist <artist name> # Finds an artist by name and plays it.";
  61. echo " play list <playlist name> # Finds a playlist by name and plays it.";
  62. echo " play uri <uri> # Play songs from specific uri.";
  63. echo;
  64. echo " next # Skips to the next song in a playlist.";
  65. echo " prev # Returns to the previous song in a playlist.";
  66. echo " replay # Replays the current track from the begining.";
  67. echo " pos <time> # Jumps to a time (in secs) in the current song.";
  68. echo " pause # Pauses (or resumes) Spotify playback.";
  69. echo " stop # Stops playback.";
  70. echo " quit # Stops playback and quits Spotify.";
  71. echo;
  72. echo " vol up # Increases the volume by 10%.";
  73. echo " vol down # Decreases the volume by 10%.";
  74. echo " vol <amount> # Sets the volume to an amount between 0 and 100.";
  75. echo " vol [show] # Shows the current Spotify volume.";
  76. echo;
  77. echo " status # Shows the current player status.";
  78. echo;
  79. echo " share # Displays the current song's Spotify URL and URI."
  80. echo " share url # Displays the current song's Spotify URL and copies it to the clipboard."
  81. echo " share uri # Displays the current song's Spotify URI and copies it to the clipboard."
  82. echo;
  83. echo " toggle shuffle # Toggles shuffle playback mode.";
  84. echo " toggle repeat # Toggles repeat playback mode.";
  85. showAPIHelp
  86. }
  87. cecho(){
  88. bold=$(tput bold);
  89. green=$(tput setaf 2);
  90. reset=$(tput sgr0);
  91. echo $bold$green"$1"$reset;
  92. }
  93. showStatus () {
  94. state=`osascript -e 'tell application "Spotify" to player state as string'`;
  95. cecho "Spotify is currently $state.";
  96. artist=`osascript -e 'tell application "Spotify" to artist of current track as string'`;
  97. album=`osascript -e 'tell application "Spotify" to album of current track as string'`;
  98. track=`osascript -e 'tell application "Spotify" to name of current track as string'`;
  99. duration=`osascript -e 'tell application "Spotify"
  100. set durSec to (duration of current track / 1000) as text
  101. set tM to (round (durSec / 60) rounding down) as text
  102. if length of ((durSec mod 60 div 1) as text) is greater than 1 then
  103. set tS to (durSec mod 60 div 1) as text
  104. else
  105. set tS to ("0" & (durSec mod 60 div 1)) as text
  106. end if
  107. set myTime to tM as text & ":" & tS as text
  108. end tell
  109. return myTime'`;
  110. position=`osascript -e 'tell application "Spotify"
  111. set pos to player position
  112. set nM to (round (pos / 60) rounding down) as text
  113. if length of ((round (pos mod 60) rounding down) as text) is greater than 1 then
  114. set nS to (round (pos mod 60) rounding down) as text
  115. else
  116. set nS to ("0" & (round (pos mod 60) rounding down)) as text
  117. end if
  118. set nowAt to nM as text & ":" & nS as text
  119. end tell
  120. return nowAt'`;
  121. echo -e $reset"Artist: $artist\nAlbum: $album\nTrack: $track \nPosition: $position / $duration";
  122. }
  123. if [ $# = 0 ]; then
  124. showHelp;
  125. else
  126. if [ ! -d /Applications/Spotify.app ] && [ ! -d $HOME/Applications/Spotify.app ]; then
  127. echo "The Spotify application must be installed."
  128. exit 1
  129. fi
  130. if [ $(osascript -e 'application "Spotify" is running') = "false" ]; then
  131. osascript -e 'tell application "Spotify" to activate' || exit 1
  132. sleep 2
  133. fi
  134. fi
  135. while [ $# -gt 0 ]; do
  136. arg=$1;
  137. case $arg in
  138. "play" )
  139. if [ $# != 1 ]; then
  140. # There are additional arguments, so find out how many
  141. array=( $@ );
  142. len=${#array[@]};
  143. SPOTIFY_SEARCH_API="https://api.spotify.com/v1/search";
  144. SPOTIFY_TOKEN_URI="https://accounts.spotify.com/api/token";
  145. if [ -z "${CLIENT_ID}" ]; then
  146. cecho "Invalid Client ID, please update ${USER_CONFIG_FILE}";
  147. showAPIHelp;
  148. exit 1;
  149. fi
  150. if [ -z "${CLIENT_SECRET}" ]; then
  151. cecho "Invalid Client Secret, please update ${USER_CONFIG_FILE}";
  152. showAPIHelp;
  153. exit 1;
  154. fi
  155. SHPOTIFY_CREDENTIALS=$(printf "${CLIENT_ID}:${CLIENT_SECRET}" | base64 | tr -d "\n"|tr -d '\r');
  156. SPOTIFY_PLAY_URI="";
  157. getAccessToken() {
  158. cecho "Connecting to Spotify's API";
  159. SPOTIFY_TOKEN_RESPONSE_DATA=$( \
  160. curl "${SPOTIFY_TOKEN_URI}" \
  161. --silent \
  162. -X "POST" \
  163. -H "Authorization: Basic ${SHPOTIFY_CREDENTIALS}" \
  164. -d "grant_type=client_credentials" \
  165. )
  166. if ! [[ "${SPOTIFY_TOKEN_RESPONSE_DATA}" =~ "access_token" ]]; then
  167. cecho "Autorization failed, please check ${USER_CONFG_FILE}"
  168. cecho "${SPOTIFY_TOKEN_RESPONSE_DATA}"
  169. showAPIHelp
  170. exit 1
  171. fi
  172. SPOTIFY_ACCESS_TOKEN=$( \
  173. printf "${SPOTIFY_TOKEN_RESPONSE_DATA}" \
  174. | grep -E -o '"access_token":".*",' \
  175. | sed 's/"access_token"://g' \
  176. | sed 's/"//g' \
  177. | sed 's/,.*//g' \
  178. )
  179. }
  180. searchAndPlay() {
  181. type="$1"
  182. Q="$2"
  183. getAccessToken;
  184. cecho "Searching ${type}s for: $Q";
  185. SPOTIFY_PLAY_URI=$( \
  186. curl -s -G $SPOTIFY_SEARCH_API \
  187. -H "Authorization: Bearer ${SPOTIFY_ACCESS_TOKEN}" \
  188. -H "Accept: application/json" \
  189. --data-urlencode "q=$Q" \
  190. -d "type=$type&limit=1&offset=0" \
  191. | grep -E -o "spotify:$type:[a-zA-Z0-9]+" -m 1
  192. )
  193. echo "play uri: ${SPOTIFY_PLAY_URI}"
  194. }
  195. case $2 in
  196. "list" )
  197. _args=${array[@]:2:$len};
  198. Q=$_args;
  199. getAccessToken;
  200. cecho "Searching playlists for: $Q";
  201. results=$( \
  202. curl -s -G $SPOTIFY_SEARCH_API --data-urlencode "q=$Q" -d "type=playlist&limit=10&offset=0" -H "Accept: application/json" -H "Authorization: Bearer ${SPOTIFY_ACCESS_TOKEN}" \
  203. | grep -E -o "spotify:user:[a-zA-Z0-9_]+:playlist:[a-zA-Z0-9]+" -m 10 \
  204. )
  205. count=$( \
  206. echo "$results" | grep -c "spotify:user" \
  207. )
  208. if [ "$count" -gt 0 ]; then
  209. random=$(( $RANDOM % $count));
  210. SPOTIFY_PLAY_URI=$( \
  211. echo "$results" | awk -v random="$random" '/spotify:user:[a-zA-Z0-9]+:playlist:[a-zA-Z0-9]+/{i++}i==random{print; exit}' \
  212. )
  213. fi;;
  214. "album" | "artist" | "track" )
  215. _args=${array[@]:2:$len};
  216. searchAndPlay $2 "$_args";;
  217. "uri" )
  218. SPOTIFY_PLAY_URI=${array[@]:2:$len};;
  219. * )
  220. _args=${array[@]:1:$len};
  221. searchAndPlay track "$_args";;
  222. esac
  223. if [ "$SPOTIFY_PLAY_URI" != "" ]; then
  224. if [ "$2" = "uri" ]; then
  225. cecho "Playing Spotify URI: $SPOTIFY_PLAY_URI";
  226. else
  227. cecho "Playing ($Q Search) -> Spotify URI: $SPOTIFY_PLAY_URI";
  228. fi
  229. osascript -e "tell application \"Spotify\" to play track \"$SPOTIFY_PLAY_URI\"";
  230. else
  231. cecho "No results when searching for $Q";
  232. fi
  233. else
  234. # play is the only param
  235. cecho "Playing Spotify.";
  236. osascript -e 'tell application "Spotify" to play';
  237. fi
  238. break ;;
  239. "pause" )
  240. state=`osascript -e 'tell application "Spotify" to player state as string'`;
  241. if [ $state = "playing" ]; then
  242. cecho "Pausing Spotify.";
  243. else
  244. cecho "Playing Spotify.";
  245. fi
  246. osascript -e 'tell application "Spotify" to playpause';
  247. break ;;
  248. "stop" )
  249. state=`osascript -e 'tell application "Spotify" to player state as string'`;
  250. if [ $state = "playing" ]; then
  251. cecho "Pausing Spotify.";
  252. osascript -e 'tell application "Spotify" to playpause';
  253. else
  254. cecho "Spotify is already stopped."
  255. fi
  256. break ;;
  257. "quit" ) cecho "Quitting Spotify.";
  258. osascript -e 'tell application "Spotify" to quit';
  259. exit 1 ;;
  260. "next" ) cecho "Going to next track." ;
  261. osascript -e 'tell application "Spotify" to next track';
  262. showStatus;
  263. break ;;
  264. "prev" ) cecho "Going to previous track.";
  265. osascript -e '
  266. tell application "Spotify"
  267. set player position to 0
  268. previous track
  269. end tell';
  270. showStatus;
  271. break ;;
  272. "replay" ) cecho "Replaying current track.";
  273. osascript -e 'tell application "Spotify" to set player position to 0'
  274. break ;;
  275. "vol" )
  276. vol=`osascript -e 'tell application "Spotify" to sound volume as integer'`;
  277. if [[ $2 = "" || $2 = "show" ]]; then
  278. cecho "Current Spotify volume level is $vol.";
  279. break ;
  280. elif [ "$2" = "up" ]; then
  281. if [ $vol -le 90 ]; then
  282. newvol=$(( vol+10 ));
  283. cecho "Increasing Spotify volume to $newvol.";
  284. else
  285. newvol=100;
  286. cecho "Spotify volume level is at max.";
  287. fi
  288. elif [ "$2" = "down" ]; then
  289. if [ $vol -ge 10 ]; then
  290. newvol=$(( vol-10 ));
  291. cecho "Reducing Spotify volume to $newvol.";
  292. else
  293. newvol=0;
  294. cecho "Spotify volume level is at min.";
  295. fi
  296. elif [[ $2 =~ ^[0-9]+$ ]] && [[ $2 -ge 0 && $2 -le 100 ]]; then
  297. newvol=$2;
  298. cecho "Setting Spotify volume level to $newvol";
  299. else
  300. echo "Improper use of 'vol' command"
  301. echo "The 'vol' command should be used as follows:"
  302. echo " vol up # Increases the volume by 10%.";
  303. echo " vol down # Decreases the volume by 10%.";
  304. echo " vol [amount] # Sets the volume to an amount between 0 and 100.";
  305. echo " vol # Shows the current Spotify volume.";
  306. break
  307. fi
  308. osascript -e "tell application \"Spotify\" to set sound volume to $newvol";
  309. break ;;
  310. "toggle" )
  311. if [ "$2" = "shuffle" ]; then
  312. osascript -e 'tell application "Spotify" to set shuffling to not shuffling';
  313. curr=`osascript -e 'tell application "Spotify" to shuffling'`;
  314. cecho "Spotify shuffling set to $curr";
  315. elif [ "$2" = "repeat" ]; then
  316. osascript -e 'tell application "Spotify" to set repeating to not repeating';
  317. curr=`osascript -e 'tell application "Spotify" to repeating'`;
  318. cecho "Spotify repeating set to $curr";
  319. fi
  320. break ;;
  321. "status" )
  322. showStatus;
  323. break ;;
  324. "info" )
  325. info=`osascript -e 'tell application "Spotify"
  326. set durSec to (duration of current track / 1000)
  327. set tM to (round (durSec / 60) rounding down) as text
  328. if length of ((durSec mod 60 div 1) as text) is greater than 1 then
  329. set tS to (durSec mod 60 div 1) as text
  330. else
  331. set tS to ("0" & (durSec mod 60 div 1)) as text
  332. end if
  333. set myTime to tM as text & "min " & tS as text & "s"
  334. set pos to player position
  335. set nM to (round (pos / 60) rounding down) as text
  336. if length of ((round (pos mod 60) rounding down) as text) is greater than 1 then
  337. set nS to (round (pos mod 60) rounding down) as text
  338. else
  339. set nS to ("0" & (round (pos mod 60) rounding down)) as text
  340. end if
  341. set nowAt to nM as text & "min " & nS as text & "s"
  342. set info to "" & "\nArtist: " & artist of current track
  343. set info to info & "\nTrack: " & name of current track
  344. set info to info & "\nAlbum Artist: " & album artist of current track
  345. set info to info & "\nAlbum: " & album of current track
  346. set info to info & "\nSeconds: " & durSec
  347. set info to info & "\nSeconds played: " & pos
  348. set info to info & "\nDuration: " & mytime
  349. set info to info & "\nNow at: " & nowAt
  350. set info to info & "\nPlayed Count: " & played count of current track
  351. set info to info & "\nTrack Number: " & track number of current track
  352. set info to info & "\nPopularity: " & popularity of current track
  353. set info to info & "\nId: " & id of current track
  354. set info to info & "\nSpotify URL: " & spotify url of current track
  355. set info to info & "\nArtwork: " & artwork url of current track
  356. set info to info & "\nPlayer: " & player state
  357. set info to info & "\nVolume: " & sound volume
  358. set info to info & "\nShuffle: " & shuffling
  359. set info to info & "\nRepeating: " & repeating
  360. end tell
  361. return info'`
  362. cecho "$info";
  363. break ;;
  364. "share" )
  365. uri=`osascript -e 'tell application "Spotify" to spotify url of current track'`;
  366. remove='spotify:track:'
  367. url=${uri#$remove}
  368. url="https://open.spotify.com/track/$url"
  369. if [ "$2" = "" ]; then
  370. cecho "Spotify URL: $url"
  371. cecho "Spotify URI: $uri"
  372. echo "To copy the URL or URI to your clipboard, use:"
  373. echo "\`spotify share url\` or"
  374. echo "\`spotify share uri\` respectively."
  375. elif [ "$2" = "url" ]; then
  376. cecho "Spotify URL: $url";
  377. echo -n $url | pbcopy
  378. elif [ "$2" = "uri" ]; then
  379. cecho "Spotify URI: $uri";
  380. echo -n $uri | pbcopy
  381. fi
  382. break;;
  383. "pos" )
  384. cecho "Adjusting Spotify play position."
  385. osascript -e "tell application \"Spotify\" to set player position to $2";
  386. break;;
  387. "help" | * )
  388. showHelp;
  389. break ;;
  390. esac
  391. done
  392. }