1212import digitalio
1313import adafruit_character_lcd .character_lcd as characterlcd
1414
15+ version = 'v0.2'
1516
1617class tokens :
17- def __init__ (self , refreshTk , base64Tk ):
18- self .refreshTk = refreshTk
19- self .base64Tk = base64Tk
18+ def __init__ (self ):
19+ refTokFile = open ('./SpotifyControl/refresh.tk' , 'r' )
20+ self .refreshTk = refTokFile .readline ()
21+ refTokFile .close ()
22+
23+ self .base64Tk = settings ['Spotify' ]['base64Tk' ]
24+
2025 self .authTk = None
2126 self .authExp = None
2227 self .update ()
2328
2429 def update (self ):
25- req = requests . post ( 'https://accounts.spotify.com/api/token' , data = { 'grant_type' : 'refresh_token' , 'refresh_token' : self . refreshTk }, headers = { 'Authorization' : f'Basic { self . base64Tk } ' })
30+ global lcd
2631
27- self .authTk = req .json ()['access_token' ]
28- expiresIn = req .json ()['expires_in' ]
29- self .authExp = datetime .datetime .now () + datetime .timedelta (seconds = (expiresIn - 60 ))
32+ req = requests .post ('https://accounts.spotify.com/api/token' , data = {'grant_type' :'refresh_token' ,'refresh_token' :self .refreshTk }, headers = {'Authorization' : f'Basic { self .base64Tk } ' })
33+ try :
34+ self .authTk = req .json ()['access_token' ]
35+ expiresIn = req .json ()['expires_in' ]
36+ self .authExp = datetime .datetime .now () + datetime .timedelta (seconds = (expiresIn - 60 ))
37+ except :
38+ lcd .clear ()
39+ lcd .message = 'Error updating\n tokens'
3040
3141
3242 def check (self ):
33- if datetime .datetime .now () > self .authExp :
43+ try :
44+ if datetime .datetime .now () > self .authExp :
45+ self .update ()
46+ print ('Token updated' )
47+ else :
48+ pass
49+ except TypeError :
3450 self .update ()
35- print ('Token updated' )
36- else :
37- pass
51+ print ('Token updated with None' )
3852
3953 return self .authExp - datetime .datetime .now ()
4054
55+ def changeRefreshTk (self , newRef , newAuth , expiresIn ):
56+ print ('entro' )
57+ refTokFile = open ('./SpotifyControl/refresh.tk' , 'w' )
58+ refTokFile .write (newRef )
59+ refTokFile .close ()
60+
61+ self .refreshTk = newRef
62+ self .authTk = newAuth
63+ self .authExp = datetime .datetime .now () + datetime .timedelta (seconds = (expiresIn - 60 ))
64+ return
65+
4166settings = configparser .ConfigParser ()
4267settings .read (os .path .join (sys .path [0 ], 'settings.conf' ))
43- tkn = tokens (settings ['Spotify' ]['refreshTk' ], settings ['Spotify' ]['base64Tk' ])
4468
4569receivedPin = 11
4670shufflePin = 9
@@ -71,7 +95,9 @@ def check(self):
7195# wipe LCD screen before we start
7296lcd .clear ()
7397# combine both lines into one update to the display
74- lcd .message = 'SpotifyControl\n is ready!'
98+ lcd .message = 'SpotifyControl\n ' + version + ' is ready!'
99+
100+ tkn = tokens ()
75101
76102urls = (
77103 '/' , 'index' ,
@@ -88,6 +114,7 @@ def check(self):
88114class index :
89115 def GET (self ):
90116 global settings
117+ global version
91118
92119 redirectUrl = settings ['Device' ]['address' ] + '/authorized'
93120 clientId = settings ['Spotify' ]['clientId' ]
@@ -96,7 +123,7 @@ def GET(self):
96123 body = """<html>
97124 <body>
98125 <h2>SpotifyControl</h2>
99- <h3>Version 0.1 </h3>
126+ <h3>Version """ + version + """ </h3>
100127 <p>Control the playback from Spotify on your Raspberry with simple HTTP requests!</p>
101128 <p>Current user: """ + "inserire nome" + """</p>
102129 <button onclick="document.location='""" + changeUserUrl + """'">Change user</p>
@@ -273,20 +300,24 @@ def POST(self):
273300
274301class authorized :
275302 def GET (self ):
303+ global tkn
304+ global lcd
305+
276306 authCode = web .input ('code' ).code
277307 base64Code = settings ['Spotify' ]['base64Tk' ]
278- redirectUrl = settings ['Device' ]['address' ]
279- data = '{\" grant_type\" : \" authorization_code\" , \" code\" : ' + authCode + ', \" redirect_uri\" = ' + redirectUrl + '}'
308+ redirectUrl = settings ['Device' ]['address' ] + '/authorized'
280309
281- reply = requests .get ('https://accounts.spotify.com/api/token' , headers = { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' , 'Authorization' : f'Basic { base64Code } ' }, data = data )
310+ reply = requests .post ('https://accounts.spotify.com/api/token' , data = { "grant_type" : "authorization_code" , "code" : authCode , "redirect_uri" : redirectUrl }, headers = { 'Authorization' : f'Basic { base64Code } ' })
282311
283312 try :
284- refTok = reply .json ()['refresh_token' ]
285- except :
286- pass
287- # return 'Bad response'
313+ tkn .changeRefreshTk (reply .json ()['refresh_token' ], reply .json ()['access_token' ], reply .json ()['expires_in' ])
314+ except KeyError :
315+ return reply .text
316+
317+ lcd .clear ()
318+ lcd .message = 'Login completed!\n Ready to play'
288319
289- return f'authcode: { authCode } </br>base64Code: { base64Code } </br>refreshToken: refTok '
320+ return 'Login completed '
290321
291322if __name__ == '__main__' :
292323 GPIO .output (shufflePin , GPIO .HIGH )
0 commit comments