spotify 20 KB

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