diff --git a/auth.go b/auth.go index 767e07f..c1eb5cd 100644 --- a/auth.go +++ b/auth.go @@ -9,7 +9,6 @@ import ( "github.com/google/uuid" "github.com/pkg/browser" "github.com/zmb3/spotify/v2" - spotifyauth "github.com/zmb3/spotify/v2/auth" ) const ( @@ -17,7 +16,6 @@ const ( ) var ( - auth *spotifyauth.Authenticator state string server *http.Server ) @@ -50,12 +48,6 @@ func completeAuth(w http.ResponseWriter, r *http.Request) { } func authorize() { - auth = spotifyauth.New( - spotifyauth.WithClientID(clientViper.GetString(SpotifyIDKeyName)), - spotifyauth.WithClientSecret(clientViper.GetString(SpotifySecretKeyName)), - spotifyauth.WithRedirectURL(redirectURI), - spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate), - ) server = &http.Server{Addr: fmt.Sprintf(":%s", port)} state = uuid.New().String() http.HandleFunc("/callback", completeAuth) diff --git a/main.go b/main.go index a1adf7c..11f96ea 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,7 @@ const ( ) var ( + auth *spotifyauth.Authenticator clientChannel = make(chan *spotify.Client, 1) ) @@ -27,6 +28,13 @@ func main() { log.Fatal(err) } + auth = spotifyauth.New( + spotifyauth.WithClientID(clientViper.GetString(SpotifyIDKeyName)), + spotifyauth.WithClientSecret(clientViper.GetString(SpotifySecretKeyName)), + spotifyauth.WithRedirectURL(redirectURI), + spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate), + ) + // check if token viper is set if !isClientInfoSet() { if err := askClientInfo(); err != nil { @@ -37,8 +45,22 @@ func main() { } else { ctx := context.Background() token := getToken() - httpClient := spotifyauth.New().Client(ctx, token) - clientChannel <- spotify.New(httpClient) + + newToken, err := auth.RefreshToken(ctx, token) + if err != nil { + log.Fatalf("fail to get a new access token: %v", err) + } + + // update an access token if it has expired + if token.AccessToken != newToken.AccessToken { + if err := saveToken(newToken); err != nil { + log.Fatalf("fail to save token: %v", err) + } + } + + spotifyClient := spotify.New(auth.Client(ctx, newToken)) + + clientChannel <- spotifyClient } client := <-clientChannel