spotify 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. #!/usr/bin/env bash
  2. function spotify() {
  3. # Copyright (c) 2012--2017 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 [ $(osascript -e 'application "Spotify" is running') = "false" ]; then
  127. osascript -e 'tell application "Spotify" to activate'
  128. sleep 2
  129. fi
  130. fi
  131. while [ $# -gt 0 ]; do
  132. arg=$1;
  133. case $arg in
  134. "play" )
  135. if [ $# != 1 ]; then
  136. # There are additional arguments, so find out how many
  137. array=( $@ );
  138. len=${#array[@]};
  139. SPOTIFY_SEARCH_API="https://api.spotify.com/v1/search";
  140. SPOTIFY_TOKEN_URI="https://accounts.spotify.com/api/token";
  141. if [ -z "${CLIENT_ID}" ]; then
  142. cecho "Invalid Client ID, please update ${USER_CONFIG_FILE}";
  143. showAPIHelp;
  144. exit 1;
  145. fi
  146. if [ -z "${CLIENT_SECRET}" ]; then
  147. cecho "Invalid Client Secret, please update ${USER_CONFIG_FILE}";
  148. showAPIHelp;
  149. exit 1;
  150. fi
  151. SHPOTIFY_CREDENTIALS=$(printf "${CLIENT_ID}:${CLIENT_SECRET}" | base64 | tr -d "\n");
  152. SPOTIFY_PLAY_URI="";
  153. getAccessToken() {
  154. cecho "Connecting to Spotify's API";
  155. SPOTIFY_TOKEN_RESPONSE_DATA=$( \
  156. curl "${SPOTIFY_TOKEN_URI}" \
  157. --silent \
  158. -X "POST" \
  159. -H "Authorization: Basic ${SHPOTIFY_CREDENTIALS}" \
  160. -d "grant_type=client_credentials" \
  161. )
  162. if ! [[ "${SPOTIFY_TOKEN_RESPONSE_DATA}" =~ "access_token" ]]; then
  163. cecho "Autorization failed, please check ${USER_CONFG_FILE}"
  164. cecho "${SPOTIFY_TOKEN_RESPONSE_DATA}"
  165. showAPIHelp
  166. exit 1
  167. fi
  168. SPOTIFY_ACCESS_TOKEN=$( \
  169. printf "${SPOTIFY_TOKEN_RESPONSE_DATA}" \
  170. | grep -E -o '"access_token":".*",' \
  171. | sed 's/"access_token"://g' \
  172. | sed 's/"//g' \
  173. | sed 's/,.*//g' \
  174. )
  175. }
  176. searchAndPlay() {
  177. type="$1"
  178. Q="$2"
  179. getAccessToken;
  180. cecho "Searching ${type}s for: $Q";
  181. SPOTIFY_PLAY_URI=$( \
  182. curl -s -G $SPOTIFY_SEARCH_API \
  183. -H "Authorization: Bearer ${SPOTIFY_ACCESS_TOKEN}" \
  184. -H "Accept: application/json" \
  185. --data-urlencode "q=$Q" \
  186. -d "type=$type&limit=1&offset=0" \
  187. | grep -E -o "spotify:$type:[a-zA-Z0-9]+" -m 1
  188. )
  189. echo "play uri: ${SPOTIFY_PLAY_URI}"
  190. }
  191. case $2 in
  192. "list" )
  193. _args=${array[@]:2:$len};
  194. Q=$_args;
  195. getAccessToken;
  196. cecho "Searching playlists for: $Q";
  197. results=$( \
  198. 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}" \
  199. | grep -E -o "spotify:user:[a-zA-Z0-9_]+:playlist:[a-zA-Z0-9]+" -m 10 \
  200. )
  201. count=$( \
  202. echo "$results" | grep -c "spotify:user" \
  203. )
  204. if [ "$count" -gt 0 ]; then
  205. random=$(( $RANDOM % $count));
  206. SPOTIFY_PLAY_URI=$( \
  207. echo "$results" | awk -v random="$random" '/spotify:user:[a-zA-Z0-9]+:playlist:[a-zA-Z0-9]+/{i++}i==random{print; exit}' \
  208. )
  209. fi;;
  210. "album" | "artist" | "track" )
  211. _args=${array[@]:2:$len};
  212. searchAndPlay $2 "$_args";;
  213. "uri" )
  214. SPOTIFY_PLAY_URI=${array[@]:2:$len};;
  215. * )
  216. _args=${array[@]:1:$len};
  217. searchAndPlay track "$_args";;
  218. esac
  219. if [ "$SPOTIFY_PLAY_URI" != "" ]; then
  220. if [ "$2" = "uri" ]; then
  221. cecho "Playing Spotify URI: $SPOTIFY_PLAY_URI";
  222. else
  223. cecho "Playing ($Q Search) -> Spotify URI: $SPOTIFY_PLAY_URI";
  224. fi
  225. osascript -e "tell application \"Spotify\" to play track \"$SPOTIFY_PLAY_URI\"";
  226. else
  227. cecho "No results when searching for $Q";
  228. fi
  229. else
  230. # play is the only param
  231. cecho "Playing Spotify.";
  232. osascript -e 'tell application "Spotify" to play';
  233. fi
  234. break ;;
  235. "pause" )
  236. state=`osascript -e 'tell application "Spotify" to player state as string'`;
  237. if [ $state = "playing" ]; then
  238. cecho "Pausing Spotify.";
  239. else
  240. cecho "Playing Spotify.";
  241. fi
  242. osascript -e 'tell application "Spotify" to playpause';
  243. break ;;
  244. "stop" )
  245. state=`osascript -e 'tell application "Spotify" to player state as string'`;
  246. if [ $state = "playing" ]; then
  247. cecho "Pausing Spotify.";
  248. osascript -e 'tell application "Spotify" to playpause';
  249. else
  250. cecho "Spotify is already stopped."
  251. fi
  252. break ;;
  253. "quit" ) cecho "Quitting Spotify.";
  254. osascript -e 'tell application "Spotify" to quit';
  255. exit 1 ;;
  256. "next" ) cecho "Going to next track." ;
  257. osascript -e 'tell application "Spotify" to next track';
  258. showStatus;
  259. break ;;
  260. "prev" ) cecho "Going to previous track.";
  261. osascript -e '
  262. tell application "Spotify"
  263. set player position to 0
  264. previous track
  265. end tell';
  266. showStatus;
  267. break ;;
  268. "replay" ) cecho "Replaying current track.";
  269. osascript -e 'tell application "Spotify" to set player position to 0'
  270. break ;;
  271. "vol" )
  272. vol=`osascript -e 'tell application "Spotify" to sound volume as integer'`;
  273. if [[ $2 = "" || $2 = "show" ]]; then
  274. cecho "Current Spotify volume level is $vol.";
  275. break ;
  276. elif [ "$2" = "up" ]; then
  277. if [ $vol -le 90 ]; then
  278. newvol=$(( vol+10 ));
  279. cecho "Increasing Spotify volume to $newvol.";
  280. else
  281. newvol=100;
  282. cecho "Spotify volume level is at max.";
  283. fi
  284. elif [ "$2" = "down" ]; then
  285. if [ $vol -ge 10 ]; then
  286. newvol=$(( vol-10 ));
  287. cecho "Reducing Spotify volume to $newvol.";
  288. else
  289. newvol=0;
  290. cecho "Spotify volume level is at min.";
  291. fi
  292. elif [[ $2 =~ ^[0-9]+$ ]] && [[ $2 -ge 0 && $2 -le 100 ]]; then
  293. newvol=$2;
  294. cecho "Setting Spotify volume level to $newvol";
  295. else
  296. echo "Improper use of 'vol' command"
  297. echo "The 'vol' command should be used as follows:"
  298. echo " vol up # Increases the volume by 10%.";
  299. echo " vol down # Decreases the volume by 10%.";
  300. echo " vol [amount] # Sets the volume to an amount between 0 and 100.";
  301. echo " vol # Shows the current Spotify volume.";
  302. break
  303. fi
  304. osascript -e "tell application \"Spotify\" to set sound volume to $newvol";
  305. break ;;
  306. "toggle" )
  307. if [ "$2" = "shuffle" ]; then
  308. osascript -e 'tell application "Spotify" to set shuffling to not shuffling';
  309. curr=`osascript -e 'tell application "Spotify" to shuffling'`;
  310. cecho "Spotify shuffling set to $curr";
  311. elif [ "$2" = "repeat" ]; then
  312. osascript -e 'tell application "Spotify" to set repeating to not repeating';
  313. curr=`osascript -e 'tell application "Spotify" to repeating'`;
  314. cecho "Spotify repeating set to $curr";
  315. fi
  316. break ;;
  317. "status" )
  318. showStatus;
  319. break ;;
  320. "info" )
  321. info=`osascript -e 'tell application "Spotify"
  322. set durSec to (duration of current track / 1000)
  323. set tM to (round (durSec / 60) rounding down) as text
  324. if length of ((durSec mod 60 div 1) as text) is greater than 1 then
  325. set tS to (durSec mod 60 div 1) as text
  326. else
  327. set tS to ("0" & (durSec mod 60 div 1)) as text
  328. end if
  329. set myTime to tM as text & "min " & tS as text & "s"
  330. set pos to player position
  331. set nM to (round (pos / 60) rounding down) as text
  332. if length of ((round (pos mod 60) rounding down) as text) is greater than 1 then
  333. set nS to (round (pos mod 60) rounding down) as text
  334. else
  335. set nS to ("0" & (round (pos mod 60) rounding down)) as text
  336. end if
  337. set nowAt to nM as text & "min " & nS as text & "s"
  338. set info to "" & "\nArtist: " & artist of current track
  339. set info to info & "\nTrack: " & name of current track
  340. set info to info & "\nAlbum Artist: " & album artist of current track
  341. set info to info & "\nAlbum: " & album of current track
  342. set info to info & "\nSeconds: " & durSec
  343. set info to info & "\nSeconds played: " & pos
  344. set info to info & "\nDuration: " & mytime
  345. set info to info & "\nNow at: " & nowAt
  346. set info to info & "\nPlayed Count: " & played count of current track
  347. set info to info & "\nTrack Number: " & track number of current track
  348. set info to info & "\nPopularity: " & popularity of current track
  349. set info to info & "\nId: " & id of current track
  350. set info to info & "\nSpotify URL: " & spotify url of current track
  351. set info to info & "\nArtwork: " & artwork url of current track
  352. set info to info & "\nPlayer: " & player state
  353. set info to info & "\nVolume: " & sound volume
  354. set info to info & "\nShuffle: " & shuffling
  355. set info to info & "\nRepeating: " & repeating
  356. end tell
  357. return info'`
  358. cecho "$info";
  359. break ;;
  360. "share" )
  361. uri=`osascript -e 'tell application "Spotify" to spotify url of current track'`;
  362. remove='spotify:track:'
  363. url=${uri#$remove}
  364. url="https://open.spotify.com/track/$url"
  365. if [ "$2" = "" ]; then
  366. cecho "Spotify URL: $url"
  367. cecho "Spotify URI: $uri"
  368. echo "To copy the URL or URI to your clipboard, use:"
  369. echo "\`spotify share url\` or"
  370. echo "\`spotify share uri\` respectively."
  371. elif [ "$2" = "url" ]; then
  372. cecho "Spotify URL: $url";
  373. echo -n $url | pbcopy
  374. elif [ "$2" = "uri" ]; then
  375. cecho "Spotify URI: $uri";
  376. echo -n $uri | pbcopy
  377. fi
  378. break;;
  379. "pos" )
  380. cecho "Adjusting Spotify play position."
  381. osascript -e "tell application \"Spotify\" to set player position to $2";
  382. break;;
  383. "help" | * )
  384. showHelp;
  385. break ;;
  386. esac
  387. done
  388. }