backseat-music/backseat/spotifyUtil/spotifyUtil.go
2025-07-22 20:35:12 +01:00

36 lines
1 KiB
Go

package spotifyUtil
import (
"context"
"fmt"
"git.akpain.net/codemicro/backseat-music/backseat/config"
"git.akpain.net/codemicro/backseat-music/backseat/data"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
)
func NewSpotityClient(ctx context.Context, datastore *data.Store) (*spotify.Client, error) {
client := spotify.New(spotifyauth.New(
spotifyauth.WithClientID(config.SpotifyClientID),
spotifyauth.WithClientSecret(config.SpotifyClientSecret),
).Client(ctx, datastore.GetSpotifyOAuthToken()))
_, err := client.CurrentUser(ctx) // we make this call to give the client the opportunity to refresh the token
if err != nil {
return nil, fmt.Errorf("get current user: %w", err)
}
tok, err := client.Token()
if err != nil {
return nil, fmt.Errorf("get spotify client token: %w", err)
}
if tok != datastore.GetSpotifyOAuthToken() {
// The token has been refreshed
if err := datastore.SetSpotifyOAuthToken(tok); err != nil {
return nil, fmt.Errorf("save refreshed token: %w", err)
}
}
return client, nil
}