package services import ( "context" "encoding/json" "fmt" "os" "path/filepath" "time" "github.com/zmb3/spotify/v2" spotifyauth "github.com/zmb3/spotify/v2/auth" "golang.org/x/oauth2" ) type SpotifyConfig struct { RedirectURL string ClientID string ClientSecret string } // On a mounted volume, so the OAuth dance survives rebuilds. const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json" // SaveSpotifyToken writes its own struct so the file format doesn't follow // oauth2.Token's. func SaveSpotifyToken(path string, tok *oauth2.Token) error { data := struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` Expiry time.Time `json:"expiry"` }{ AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken, TokenType: tok.TokenType, Expiry: tok.Expiry, } if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { return fmt.Errorf("creating token directory: %w", err) } jsonBytes, err := json.MarshalIndent(data, "", " ") if err != nil { return err } return os.WriteFile(path, jsonBytes, 0600) } func LoadSpotifyToken(path string) (*oauth2.Token, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } var saved struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` Expiry time.Time `json:"expiry"` } if err := json.Unmarshal(data, &saved); err != nil { return nil, err } tok := &oauth2.Token{ AccessToken: saved.AccessToken, RefreshToken: saved.RefreshToken, TokenType: saved.TokenType, Expiry: saved.Expiry, } return tok, nil } // InitSpotifyAuth never fails startup: with no usable token it returns a nil // client, so every caller must nil-check Store.SpotifyClient. func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) { auth := spotifyauth.New( spotifyauth.WithRedirectURL(config.RedirectURL), spotifyauth.WithClientID(config.ClientID), spotifyauth.WithClientSecret(config.ClientSecret), spotifyauth.WithScopes( spotifyauth.ScopeUserReadPlaybackState, spotifyauth.ScopeUserReadCurrentlyPlaying, spotifyauth.ScopeUserReadRecentlyPlayed, ), ) token, err := LoadSpotifyToken(SPOTIFY_TOKEN_JSON_PATH) if err != nil || token == nil { fmt.Println("No Spotify token saved. Authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.") return auth, nil } client, err := RefreshClient(auth, token) if err != nil { fmt.Println("Failed to refresh Spotify token. Re-authenticate by calling GET /api/spotify/auth as an admin and opening the URL it returns.") return auth, nil } return auth, client } // RefreshClient saves the new token, ignoring write errors. The client's // later automatic refreshes are not persisted. func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) { // The client outlives the request that created it. ctx := context.Background() token, err := auth.RefreshToken(ctx, token) if err != nil { return nil, err } SaveSpotifyToken(SPOTIFY_TOKEN_JSON_PATH, token) client := spotify.New(auth.Client(ctx, token)) return client, nil }