spotify 20 KB

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