4 # Copyright (c) 2012--2019 Harish Narayanan <mail@harishnarayanan.org>
6 # Contains numerous helpful contributions from Jorge Colindres, Thomas
7 # Pritchard, iLan Epstein, Gabriele Bonetti, Sean Heller, Eric Martin
10 # Permission is hereby granted, free of charge, to any person
11 # obtaining a copy of this software and associated documentation files
12 # (the "Software"), to deal in the Software without restriction,
13 # including without limitation the rights to use, copy, modify, merge,
14 # publish, distribute, sublicense, and/or sell copies of the Software,
15 # and to permit persons to whom the Software is furnished to do so,
16 # subject to the following conditions:
18 # The above copyright notice and this permission notice shall be
19 # included in all copies or substantial portions of the Software.
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
25 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
26 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 USER_CONFIG_DEFAULTS="CLIENT_ID=\"\"\nCLIENT_SECRET=\"\"";
31 USER_CONFIG_FILE="${HOME}/.shpotify.cfg";
32 if ! [[ -f "${USER_CONFIG_FILE}" ]]; then
33 touch "${USER_CONFIG_FILE}";
34 echo -e "${USER_CONFIG_DEFAULTS}" > "${USER_CONFIG_FILE}";
36 source "${USER_CONFIG_FILE}";
40 echo "Connecting to Spotify's API:";
42 echo " This command line application needs to connect to Spotify's API in order to";
43 echo " find music by name. It is very likely you want this feature!";
45 echo " To get this to work, you need to sign up (or in) and create an 'Application' at:";
46 echo " https://developer.spotify.com/my-applications/#!/applications/create";
48 echo " Once you've created an application, find the 'Client ID' and 'Client Secret'";
49 echo " values, and enter them into your shpotify config file at '${USER_CONFIG_FILE}'";
51 echo " Be sure to quote your values and don't add any extra spaces!";
52 echo " When done, it should look like this (but with your own values):";
53 echo ' CLIENT_ID="abc01de2fghijk345lmnop"';
54 echo ' CLIENT_SECRET="qr6stu789vwxyz"';
60 echo " `basename $0` <command>";
64 echo " play # Resumes playback where Spotify last left off.";
65 echo " play <song name> # Finds a song by name and plays it.";
66 echo " play album <album name> # Finds an album by name and plays it.";
67 echo " play artist <artist name> # Finds an artist by name and plays it.";
68 echo " play list <playlist name> # Finds a playlist by name and plays it.";
69 echo " play uri <uri> # Play songs from specific uri.";
71 echo " next # Skips to the next song in a playlist.";
72 echo " prev # Returns to the previous song in a playlist.";
73 echo " replay # Replays the current track from the beginning.";
74 echo " pos <time> # Jumps to a time (in secs) in the current song.";
75 echo " pause # Pauses (or resumes) Spotify playback.";
76 echo " stop # Stops playback.";
77 echo " quit # Stops playback and quits Spotify.";
79 echo " vol up # Increases the volume by 10%.";
80 echo " vol down # Decreases the volume by 10%.";
81 echo " vol <amount> # Sets the volume to an amount between 0 and 100.";
82 echo " vol [show] # Shows the current Spotify volume.";
84 echo " status # Shows the current player status.";
85 echo " status artist # Shows the currently playing artist.";
86 echo " status album # Shows the currently playing album.";
87 echo " status track # Shows the currently playing track.";
89 echo " share # Displays the current song's Spotify URL and URI."
90 echo " share url # Displays the current song's Spotify URL and copies it to the clipboard."
91 echo " share uri # Displays the current song's Spotify URI and copies it to the clipboard."
93 echo " toggle shuffle # Toggles shuffle playback mode.";
94 echo " toggle repeat # Toggles repeat playback mode.";
100 green=$(tput setaf 2);
102 echo $bold$green"$1"$reset;
106 echo `osascript -e 'tell application "Spotify" to artist of current track as string'`;
110 echo `osascript -e 'tell application "Spotify" to album of current track as string'`;
114 echo `osascript -e 'tell application "Spotify" to name of current track as string'`;
118 state=`osascript -e 'tell application "Spotify" to player state as string'`;
119 cecho "Spotify is currently $state.";
120 duration=`osascript -e 'tell application "Spotify"
121 set durSec to (duration of current track / 1000) as text
122 set tM to (round (durSec / 60) rounding down) as text
123 if length of ((durSec mod 60 div 1) as text) is greater than 1 then
124 set tS to (durSec mod 60 div 1) as text
126 set tS to ("0" & (durSec mod 60 div 1)) as text
128 set myTime to tM as text & ":" & tS as text
131 position=`osascript -e 'tell application "Spotify"
132 set pos to player position
133 set nM to (round (pos / 60) rounding down) as text
134 if length of ((round (pos mod 60) rounding down) as text) is greater than 1 then
135 set nS to (round (pos mod 60) rounding down) as text
137 set nS to ("0" & (round (pos mod 60) rounding down)) as text
139 set nowAt to nM as text & ":" & nS as text
143 echo -e $reset"Artist: $(showArtist)\nAlbum: $(showAlbum)\nTrack: $(showTrack) \nPosition: $position / $duration";
149 if [ ! -d /Applications/Spotify.app ] && [ ! -d $HOME/Applications/Spotify.app ]; then
150 echo "The Spotify application must be installed."
154 if [ $(osascript -e 'application "Spotify" is running') = "false" ]; then
155 osascript -e 'tell application "Spotify" to activate' || return 1
159 while [ $# -gt 0 ]; do
165 # There are additional arguments, so find out how many
168 SPOTIFY_SEARCH_API="https://api.spotify.com/v1/search";
169 SPOTIFY_TOKEN_URI="https://accounts.spotify.com/api/token";
170 if [ -z "${CLIENT_ID}" ]; then
171 cecho "Invalid Client ID, please update ${USER_CONFIG_FILE}";
175 if [ -z "${CLIENT_SECRET}" ]; then
176 cecho "Invalid Client Secret, please update ${USER_CONFIG_FILE}";
180 SHPOTIFY_CREDENTIALS=$(printf "${CLIENT_ID}:${CLIENT_SECRET}" | base64 | tr -d "\n"|tr -d '\r');
184 cecho "Connecting to Spotify's API";
186 SPOTIFY_TOKEN_RESPONSE_DATA=$( \
187 curl "${SPOTIFY_TOKEN_URI}" \
190 -H "Authorization: Basic ${SHPOTIFY_CREDENTIALS}" \
191 -d "grant_type=client_credentials" \
193 if ! [[ "${SPOTIFY_TOKEN_RESPONSE_DATA}" =~ "access_token" ]]; then
194 cecho "Authorization failed, please check ${USER_CONFG_FILE}"
195 cecho "${SPOTIFY_TOKEN_RESPONSE_DATA}"
199 SPOTIFY_ACCESS_TOKEN=$( \
200 printf "${SPOTIFY_TOKEN_RESPONSE_DATA}" \
201 | grep -E -o '"access_token":".*",' \
202 | sed 's/"access_token"://g' \
214 cecho "Searching ${type}s for: $Q";
216 SPOTIFY_PLAY_URI=$( \
217 curl -s -G $SPOTIFY_SEARCH_API \
218 -H "Authorization: Bearer ${SPOTIFY_ACCESS_TOKEN}" \
219 -H "Accept: application/json" \
220 --data-urlencode "q=$Q" \
221 -d "type=$type&limit=1&offset=0" \
222 | grep -E -o "spotify:$type:[a-zA-Z0-9]+" -m 1
224 echo "play uri: ${SPOTIFY_PLAY_URI}"
229 _args=${array[@]:2:$len};
234 cecho "Searching playlists for: $Q";
237 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}" \
238 | grep -E -o "spotify:playlist:[a-zA-Z0-9]+" -m 10 \
242 echo "$results" | grep -c "spotify:playlist" \
245 if [ "$count" -gt 0 ]; then
246 random=$(( $RANDOM % $count));
248 SPOTIFY_PLAY_URI=$( \
249 echo "$results" | awk -v random="$random" '/spotify:playlist:[a-zA-Z0-9]+/{i++}i==random{print; exit}' \
253 "album" | "artist" | "track" )
254 _args=${array[@]:2:$len};
255 searchAndPlay $2 "$_args";;
258 SPOTIFY_PLAY_URI=${array[@]:2:$len};;
261 _args=${array[@]:1:$len};
262 searchAndPlay track "$_args";;
265 if [ "$SPOTIFY_PLAY_URI" != "" ]; then
266 if [ "$2" = "uri" ]; then
267 cecho "Playing Spotify URI: $SPOTIFY_PLAY_URI";
269 cecho "Playing ($Q Search) -> Spotify URI: $SPOTIFY_PLAY_URI";
272 osascript -e "tell application \"Spotify\" to play track \"$SPOTIFY_PLAY_URI\"";
275 cecho "No results when searching for $Q";
280 # play is the only param
281 cecho "Playing Spotify.";
282 osascript -e 'tell application "Spotify" to play';
287 state=`osascript -e 'tell application "Spotify" to player state as string'`;
288 if [ $state = "playing" ]; then
289 cecho "Pausing Spotify.";
291 cecho "Playing Spotify.";
294 osascript -e 'tell application "Spotify" to playpause';
298 state=`osascript -e 'tell application "Spotify" to player state as string'`;
299 if [ $state = "playing" ]; then
300 cecho "Pausing Spotify.";
301 osascript -e 'tell application "Spotify" to playpause';
303 cecho "Spotify is already stopped."
308 "quit" ) cecho "Quitting Spotify.";
309 osascript -e 'tell application "Spotify" to quit';
312 "next" ) cecho "Going to next track." ;
313 osascript -e 'tell application "Spotify" to next track';
317 "prev" ) cecho "Going to previous track.";
319 tell application "Spotify"
320 set player position to 0
326 "replay" ) cecho "Replaying current track.";
327 osascript -e 'tell application "Spotify" to set player position to 0'
331 vol=`osascript -e 'tell application "Spotify" to sound volume as integer'`;
332 if [[ $2 = "" || $2 = "show" ]]; then
333 cecho "Current Spotify volume level is $vol.";
335 elif [ "$2" = "up" ]; then
336 if [ $vol -le 90 ]; then
337 newvol=$(( vol+10 ));
338 cecho "Increasing Spotify volume to $newvol.";
341 cecho "Spotify volume level is at max.";
343 elif [ "$2" = "down" ]; then
344 if [ $vol -ge 10 ]; then
345 newvol=$(( vol-10 ));
346 cecho "Reducing Spotify volume to $newvol.";
349 cecho "Spotify volume level is at min.";
351 elif [[ $2 =~ ^[0-9]+$ ]] && [[ $2 -ge 0 && $2 -le 100 ]]; then
353 cecho "Setting Spotify volume level to $newvol";
355 echo "Improper use of 'vol' command"
356 echo "The 'vol' command should be used as follows:"
357 echo " vol up # Increases the volume by 10%.";
358 echo " vol down # Decreases the volume by 10%.";
359 echo " vol [amount] # Sets the volume to an amount between 0 and 100.";
360 echo " vol # Shows the current Spotify volume.";
364 osascript -e "tell application \"Spotify\" to set sound volume to $newvol";
368 if [ "$2" = "shuffle" ]; then
369 osascript -e 'tell application "Spotify" to set shuffling to not shuffling';
370 curr=`osascript -e 'tell application "Spotify" to shuffling'`;
371 cecho "Spotify shuffling set to $curr";
372 elif [ "$2" = "repeat" ]; then
373 osascript -e 'tell application "Spotify" to set repeating to not repeating';
374 curr=`osascript -e 'tell application "Spotify" to repeating'`;
375 cecho "Spotify repeating set to $curr";
381 # There are additional arguments, a status subcommand
396 # status is the only param
402 info=`osascript -e 'tell application "Spotify"
403 set durSec to (duration of current track / 1000)
404 set tM to (round (durSec / 60) rounding down) as text
405 if length of ((durSec mod 60 div 1) as text) is greater than 1 then
406 set tS to (durSec mod 60 div 1) as text
408 set tS to ("0" & (durSec mod 60 div 1)) as text
410 set myTime to tM as text & "min " & tS as text & "s"
411 set pos to player position
412 set nM to (round (pos / 60) rounding down) as text
413 if length of ((round (pos mod 60) rounding down) as text) is greater than 1 then
414 set nS to (round (pos mod 60) rounding down) as text
416 set nS to ("0" & (round (pos mod 60) rounding down)) as text
418 set nowAt to nM as text & "min " & nS as text & "s"
419 set info to "" & "\nArtist: " & artist of current track
420 set info to info & "\nTrack: " & name of current track
421 set info to info & "\nAlbum Artist: " & album artist of current track
422 set info to info & "\nAlbum: " & album of current track
423 set info to info & "\nSeconds: " & durSec
424 set info to info & "\nSeconds played: " & pos
425 set info to info & "\nDuration: " & mytime
426 set info to info & "\nNow at: " & nowAt
427 set info to info & "\nPlayed Count: " & played count of current track
428 set info to info & "\nTrack Number: " & track number of current track
429 set info to info & "\nPopularity: " & popularity of current track
430 set info to info & "\nId: " & id of current track
431 set info to info & "\nSpotify URL: " & spotify url of current track
432 set info to info & "\nArtwork: " & artwork url of current track
433 set info to info & "\nPlayer: " & player state
434 set info to info & "\nVolume: " & sound volume
435 set info to info & "\nShuffle: " & shuffling
436 set info to info & "\nRepeating: " & repeating
443 uri=`osascript -e 'tell application "Spotify" to spotify url of current track'`;
444 remove='spotify:track:'
446 url="https://open.spotify.com/track/$url"
448 if [ "$2" = "" ]; then
449 cecho "Spotify URL: $url"
450 cecho "Spotify URI: $uri"
451 echo "To copy the URL or URI to your clipboard, use:"
452 echo "\`spotify share url\` or"
453 echo "\`spotify share uri\` respectively."
454 elif [ "$2" = "url" ]; then
455 cecho "Spotify URL: $url";
456 echo -n $url | pbcopy
457 elif [ "$2" = "uri" ]; then
458 cecho "Spotify URI: $uri";
459 echo -n $uri | pbcopy
464 cecho "Adjusting Spotify play position."
465 osascript -e "tell application \"Spotify\" to set player position to $2";