1#! /bin/python
2
3import requests, json, collections, sys, re
4
5id = "censored"
6secret = "censored"
7Token = collections.namedtuple('token', ['access', 'refresh', 'err'])
8
9
10
11def refresh() :
12
13 authfile = open("/mnt/andrew/code/lastsong" + '/.auth', 'r+') # current refresh token is kept in .auth
14 rt = authfile.read().splitlines()[0];
15
16 params = {'client_id':id,
17 'client_secret':secret,
18 'grant_type':"refresh_token",
19 'refresh_token':rt}
20
21 data = json.loads(requests.post(url = "https://accounts.spotify.com/api/token", data = params).text)
22 try:
23 authfile.write(data['refresh_token']); # refresh token is not updated if delta t < 3600ms
24 except:
25 pass
26 # print("Refresh token unchanged")
27 return(data['access_token']);
28
29def getsong() :
30 header = {'Authorization': "Authorization: Bearer " + refresh()}
31 response = requests.get("https://api.spotify.com/v1/me/player/recently-played", headers = header).text
32 data = json.loads(response)
33 # open('./sampleoutput.json', 'w').write(response); # for debugging
34 return("\"" + re.sub('\s[\(][F|f][t|e][a][t][\.].*', '', data['items'][0]['track']['name']) + "\" by " + data['items'][0]['track']['artists'][0]['name']);
35
36if __name__ == '__getsong__' or '__main__':
37 getsong()