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"
|
2024-10-30 09:17:24 +00:00
|
|
|
"net"
|
2024-10-19 09:47:56 +00:00
|
|
|
"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-30 09:17:24 +00:00
|
|
|
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
|
|
|
|
var Clients = make(map[net.Addr]*models.WebsocketClient)
|
2024-10-20 18:51:21 +00:00
|
|
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrade HTTP requests to WebSocket connections
|
2024-10-19 09:47:56 +00:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrades HTTP requests to WebSocket connections and manages the client lifecycle
|
2024-10-29 17:49:00 +00:00
|
|
|
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-30 09:19:07 +00:00
|
|
|
log.Info("Client connected", "host", ws.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-30 08:57:09 +00:00
|
|
|
client := models.WebsocketClient{
|
2024-10-30 07:09:41 +00:00
|
|
|
Conn: ws,
|
2024-10-20 09:06:37 +00:00
|
|
|
}
|
2024-10-30 07:09:41 +00:00
|
|
|
mu.Lock()
|
2024-10-30 09:17:24 +00:00
|
|
|
Clients[ws.LocalAddr()] = &client
|
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
|
2024-10-30 07:09:41 +00:00
|
|
|
handleClientCommands(client)
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|