From fef60f585e1b50242fa43183e0000debbdc05e9f Mon Sep 17 00:00:00 2001 From: Victor Hang Date: Sun, 22 Sep 2024 10:11:18 +0200 Subject: [PATCH] =?UTF-8?q?fix=20=F0=9F=90=9B:=20fix=20expired=20oauth2=20?= =?UTF-8?q?token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Victor Hang --- pkg/youtube/youtube_oauth2.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/pkg/youtube/youtube_oauth2.go b/pkg/youtube/youtube_oauth2.go index b19efe3..7ee867d 100644 --- a/pkg/youtube/youtube_oauth2.go +++ b/pkg/youtube/youtube_oauth2.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "time" "go.uber.org/zap" "golang.org/x/oauth2" @@ -68,6 +69,17 @@ func loadToken(filename string) (*oauth2.Token, error) { return token, nil } +// isTokenExpired checks if the token is expired. +func isTokenExpired(token *oauth2.Token) bool { + utils.Logger.Debug("Checking if token is expired.") + if token == nil || !token.Valid() || time.Now().After(token.Expiry) { + utils.Logger.Info("Token is expired or invalid.") + return true + } + utils.Logger.Debug("Token is valid.") + return false +} + // NewYouTubeAPI initializes the YouTube API by handling the OAuth2 flow. func NewYouTubeAPI(clientID, clientSecret string) (chan *YouTubeAPI, error) { utils.Logger.Info("Initializing YouTube API.", zap.String("client_id", clientID)) @@ -90,8 +102,13 @@ func NewYouTubeAPI(clientID, clientSecret string) (chan *YouTubeAPI, error) { defer close(apiChan) utils.Logger.Debug("Loading OAuth2 token.") token, err := loadToken(tokenFile) - if err != nil { - utils.Logger.Error("Failed to load token.", zap.String("token_file", tokenFile), zap.Error(err)) + if err != nil || isTokenExpired(token) { + // If token loading fails or token is expired, start OAuth flow + if err != nil { + utils.Logger.Error("Failed to load token.", zap.String("token_file", tokenFile), zap.Error(err)) + } else { + utils.Logger.Info("Token is expired. Starting OAuth2 flow.") + } utils.Logger.Debug("Starting OAuth2 flow.") if startOAuthErr = startOAuthFlow(config, apiChan, tokenFile); startOAuthErr != nil { utils.Logger.Error("OAuth2 flow failed.", zap.Error(startOAuthErr))