This commit is contained in:
skidoodle 2024-10-10 21:43:06 +02:00
parent b5fe22bdc0
commit 15cccfcb20
Signed by: albert
GPG key ID: A06E3070D7D55BF2

86
main.go
View file

@ -15,21 +15,21 @@ import (
) )
var ( var (
clients = make(map[*websocket.Conn]bool) // Map to keep track of connected clients clients = make(map[*websocket.Conn]bool) // Map to keep track of connected clients
clientsMutex sync.Mutex // Mutex to protect access to clients map clientsMutex sync.Mutex // Mutex to protect access to clients map
broadcast = make(chan *spotify.CurrentlyPlaying) // Channel for broadcasting currently playing track broadcast = make(chan *spotify.CurrentlyPlaying) // Channel for broadcasting currently playing track
connect = make(chan *websocket.Conn) // Channel for managing new connections connect = make(chan *websocket.Conn) // Channel for managing new connections
disconnect = make(chan *websocket.Conn) // Channel for managing client disconnections disconnect = make(chan *websocket.Conn) // Channel for managing client disconnections
upgrader = websocket.Upgrader{ upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true }, // Allow all origins CheckOrigin: func(r *http.Request) bool { return true }, // Allow all origins
HandshakeTimeout: 10 * time.Second, // Timeout for WebSocket handshake HandshakeTimeout: 10 * time.Second, // Timeout for WebSocket handshake
ReadBufferSize: 1024, // Buffer size for reading incoming messages ReadBufferSize: 1024, // Buffer size for reading incoming messages
WriteBufferSize: 1024, // Buffer size for writing outgoing messages WriteBufferSize: 1024, // Buffer size for writing outgoing messages
Subprotocols: []string{"binary"}, // Supported subprotocols Subprotocols: []string{"binary"}, // Supported subprotocols
} }
spotifyClient spotify.Client // Spotify API client spotifyClient spotify.Client // Spotify API client
tokenSource oauth2.TokenSource // OAuth2 token source tokenSource oauth2.TokenSource // OAuth2 token source
config *oauth2.Config // OAuth2 configuration config *oauth2.Config // OAuth2 configuration
) )
func main() { func main() {
@ -65,8 +65,8 @@ func main() {
// Log server start-up and initialize background tasks // Log server start-up and initialize background tasks
log.Println("Server started on :3000") log.Println("Server started on :3000")
go TrackFetcher() // Periodically fetch currently playing track from Spotify go TrackFetcher() // Periodically fetch currently playing track from Spotify
go MessageHandler() // Broadcast messages to connected clients go MessageHandler() // Broadcast messages to connected clients
go ConnectionManager() // Manage client connections go ConnectionManager() // Manage client connections
// Start the HTTP server // Start the HTTP server
@ -78,7 +78,9 @@ func main() {
// ConnectionHandler upgrades HTTP connections to WebSocket and handles communication with clients // ConnectionHandler upgrades HTTP connections to WebSocket and handles communication with clients
func ConnectionHandler(w http.ResponseWriter, r *http.Request) { func ConnectionHandler(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil) ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {return} if err != nil {
return
}
connect <- ws connect <- ws
defer func() { defer func() {
@ -114,17 +116,17 @@ func ConnectionHandler(w http.ResponseWriter, r *http.Request) {
func ConnectionManager() { func ConnectionManager() {
for { for {
select { select {
case client := <-connect: case client := <-connect:
clientsMutex.Lock() clientsMutex.Lock()
clients[client] = true clients[client] = true
clientsMutex.Unlock() clientsMutex.Unlock()
case client := <-disconnect: case client := <-disconnect:
clientsMutex.Lock() clientsMutex.Lock()
if _, ok := clients[client]; ok { if _, ok := clients[client]; ok {
delete(clients, client) delete(clients, client)
client.Close() client.Close()
} }
clientsMutex.Unlock() clientsMutex.Unlock()
} }
} }
} }
@ -169,22 +171,22 @@ func TrackFetcher() {
// Check if the track is playing // Check if the track is playing
switch { switch {
case current.Playing: case current.Playing:
broadcast <- current broadcast <- current
playing = true playing = true
// Send updates every 3 seconds while playing // Send updates every 3 seconds while playing
for current.Playing { for current.Playing {
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
current, err = spotifyClient.PlayerCurrentlyPlaying() current, err = spotifyClient.PlayerCurrentlyPlaying()
if err != nil { if err != nil {
log.Printf("Error getting currently playing track: %v", err) log.Printf("Error getting currently playing track: %v", err)
break break
}
broadcast <- current
} }
case !current.Playing && playing: broadcast <- current
playing = false
} }
case !current.Playing && playing:
playing = false
}
// Wait before checking again to avoid overwhelming the API // Wait before checking again to avoid overwhelming the API
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)