2023-05-18 20:04:55 -06:00
package lib
import (
"context"
"os"
2024-02-29 10:53:08 -07:00
"strings"
2024-02-29 10:31:26 -07:00
"sync"
2023-05-18 20:04:55 -06:00
"atri.dad/lib/pubsub"
"github.com/zmb3/spotify"
"golang.org/x/oauth2"
)
2024-02-29 10:31:26 -07:00
var (
spotifyOAuth2Endpoint = oauth2 . Endpoint {
TokenURL : "https://accounts.spotify.com/api/token" ,
AuthURL : "https://accounts.spotify.com/authorize" ,
}
config * oauth2 . Config
once sync . Once
)
2024-02-29 10:53:08 -07:00
func NowPlayingTextFilter ( s string ) string {
s = strings . Replace ( s , "'" , "'" , - 1 )
s = strings . Replace ( s , "\"" , """ , - 1 )
return s
}
2024-02-29 10:31:26 -07:00
func GetOAuth2Config ( clientID string , clientSecret string ) * oauth2 . Config {
once . Do ( func ( ) {
config = & oauth2 . Config {
ClientID : clientID ,
ClientSecret : clientSecret ,
Scopes : [ ] string { spotify . ScopeUserReadCurrentlyPlaying } ,
Endpoint : spotifyOAuth2Endpoint ,
}
} )
return config
2023-05-18 20:04:55 -06:00
}
func GetCurrentlyPlayingTrack ( clientID string , clientSecret string , refreshToken string ) ( * spotify . CurrentlyPlaying , error ) {
// OAuth2 config
2024-02-29 10:31:26 -07:00
config := GetOAuth2Config ( clientID , clientSecret )
2023-05-18 20:04:55 -06:00
// Token source
tokenSource := config . TokenSource ( context . Background ( ) , & oauth2 . Token { RefreshToken : refreshToken } )
// Get new token
newToken , err := tokenSource . Token ( )
if err != nil {
return nil , err
}
// Create new client
client := spotify . Authenticator { } . NewClient ( newToken )
// Get currently playing track
playing , err := client . PlayerCurrentlyPlaying ( )
if err != nil {
return nil , err
}
return playing , nil
}
func CurrentlyPlayingTrackSSE ( ctx context . Context , pubSub pubsub . PubSub ) error {
clientID := os . Getenv ( "SPOTIFY_CLIENT_ID" )
clientSecret := os . Getenv ( "SPOTIFY_CLIENT_SECRET" )
refreshToken := os . Getenv ( "SPOTIFY_REFRESH_TOKEN" )
playing , err := GetCurrentlyPlayingTrack ( clientID , clientSecret , refreshToken )
if err != nil {
return err
}
if playing . Item != nil && playing . Playing {
2024-02-29 10:53:08 -07:00
songName := NowPlayingTextFilter ( playing . Item . Name )
artistName := NowPlayingTextFilter ( playing . Item . Artists [ 0 ] . Name )
return SendSSE ( ctx , pubSub , "spotify" , ` <div class="indicator-item badge badge-success"><a _='on mouseover put "🔥 Listening to ` + songName + " by " + artistName + ` 🔥" into my.textContent on mouseout put "🔥" into my.textContent' href=" ` + playing . Item . ExternalURLs [ "spotify" ] + ` " rel="noreferrer" target="_blank">🔥</a></div> ` )
2023-05-18 20:04:55 -06:00
} else {
2024-05-14 22:50:25 -06:00
SendSSE ( ctx , pubSub , "spotify" , "<span></span>" )
2023-05-18 20:04:55 -06:00
}
return nil
}