Skip to content

Instantly share code, notes, and snippets.

@ofenstichloch
Created June 5, 2017 18:34
Show Gist options
  • Save ofenstichloch/13417641033464d5c150a5ea391df0e1 to your computer and use it in GitHub Desktop.
Save ofenstichloch/13417641033464d5c150a5ea391df0e1 to your computer and use it in GitHub Desktop.
Mac Spotify add track to playlist script for Touchbar
#Persistent storage file: ~/.conf/SpotifyAPI
#Includes following fields:
# access_token: OAuth access token (current or expired)
# refresh_token: OAuth refresh token to request a new access_token if expired
# client: Spotify Client ID
# clientSecret: Spotify Client Secret
# expire: Added by the script to refresh access token
# userid: Spotify user ID
#This version creates and adds to playlist in form "YYYY MMM" like "2017 Jun"
#To change this change the two occurences of "name" in get_playlist and create_playlist
import json
import requests
import time
import calendar
import datetime
from subprocess import Popen,PIPE
from requests.auth import HTTPBasicAuth
CONFIG = ".config/spotifyAPI"
conf = dict()
def get_conf(path):
global conf
with open(path) as cf:
conf = json.load(cf)
def save_conf(path):
global conf
with open(path,'w') as outf:
json.dump(conf, outf)
def request_new_token():
global conf
url = 'https://accounts.spotify.com/api/token'
data = dict(grant_type='refresh_token', refresh_token=conf['refresh_token'])
rep = requests.post(url, data=data, auth=HTTPBasicAuth(conf['client'], conf['clientSecret'])).json()
conf['access_token'] = rep['access_token']
conf['expire'] = time.time()+rep['expires_in']
if 'refresh_token' in rep:
conf['refresh_token'] = rep['refresh__token']
def get_song():
cmd='''tell application "Spotify"
return id of current track
end tell
'''
proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout = proc.communicate(cmd)
return stdout[0].rstrip()
def get_playlist():
month = calendar.month_abbr[datetime.datetime.now().month]
year = datetime.datetime.now().year
name=str(year)+" "+month
url = 'https://api.spotify.com/v1/me/playlists'
headers = {"Authorization": "Bearer "+conf['access_token']}
offset = 0
while True:
rep = requests.get(url+'?offset='+str(offset), headers=headers).json()['items']
if not rep:
return None
for list in rep:
if list['name'] == name:
return list['id']
offset += 20
def add_song(uid, sid, pid):
url = 'https://api.spotify.com/v1/users/'+uid+'/playlists/'+pid+'/tracks?uris='+sid
headers = {"Authorization": "Bearer " + conf['access_token']}
rep = requests.post(url, headers=headers).json()
def create_playlist(uid):
url = 'https://api.spotify.com/v1/users/'+uid+'/playlists'
headers = {"Authorization": "Bearer " + conf['access_token'], "Content-Type": "application/json"}
month = calendar.month_abbr[datetime.datetime.now().month]
year = datetime.datetime.now().year
name = str(year) + " " + month
data = '{ "name": "'+ name + '"}'
rep = requests.post(url, data=data, headers=headers).json()
#-----------------------------------------------MAIN-------------------------------------------------------
get_conf(CONFIG)
if 'expire' not in conf or conf['expire'] <= time.time():
print("new token")
request_new_token()
save_conf(CONFIG)
track = str(get_song())
playlist = get_playlist()
if playlist == None:
create_playlist(conf['userid'])
playlist = get_playlist()
add_song(conf['userid'], track, playlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment