2024-10-19 09:47:56 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2024-10-25 22:01:07 +00:00
|
|
|
"github.com/charmbracelet/log"
|
2024-10-19 09:47:56 +00:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"net/http"
|
2024-10-20 18:51:21 +00:00
|
|
|
"sync"
|
2024-10-28 08:33:05 +00:00
|
|
|
|
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-21 07:20:58 +00:00
|
|
|
// Clients is a map of connected WebSocket clients, where each client is represented by the Client struct
|
|
|
|
var Clients = make(map[*websocket.Conn]*models.Client)
|
2024-10-20 18:51:21 +00:00
|
|
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// Upgrader to upgrade HTTP requests to WebSocket connections
|
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
2024-10-29 17:49:00 +00:00
|
|
|
// HandleConnection upgrades HTTP requests to WebSocket connections and manages the client lifecycle.
|
|
|
|
func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
2024-10-19 09:47:56 +00:00
|
|
|
// Upgrade initial GET request to a WebSocket
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2024-10-25 22:01:07 +00:00
|
|
|
log.Error("WebSocket upgrade error:", "msg", err)
|
2024-10-19 09:47:56 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
2024-10-25 22:01:07 +00:00
|
|
|
log.Info("Client connected", "host", ws.NetConn().RemoteAddr(), "clients", len(Clients)+1)
|
2024-10-21 15:59:35 +00:00
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// Register the new client
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Lock()
|
2024-10-21 07:20:58 +00:00
|
|
|
Clients[ws] = &models.Client{
|
2024-10-20 09:06:37 +00:00
|
|
|
Conn: ws, // Store the WebSocket connection
|
|
|
|
}
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Unlock()
|
2024-10-19 09:47:56 +00:00
|
|
|
|
|
|
|
// Listen for commands from the connected client
|
|
|
|
handleClientCommands(ws)
|
|
|
|
}
|