2024-10-20 09:06:37 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2024-10-25 22:01:07 +00:00
|
|
|
"github.com/charmbracelet/log"
|
2024-10-20 09:06:37 +00:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Represents a command from the client (start/stop)
|
2024-10-20 09:06:37 +00:00
|
|
|
type ClientCommand struct {
|
2024-10-30 06:37:14 +00:00
|
|
|
Command string `json:"command"` // Command send to the server
|
|
|
|
Password string `json:"password"` // Pomodoro control password
|
|
|
|
Settings PomodoroConfig `json:"settings"` // Pomodoro config
|
2024-10-20 09:06:37 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Represents a single client
|
2024-10-20 09:06:37 +00:00
|
|
|
type Client struct {
|
2024-10-30 06:37:14 +00:00
|
|
|
Conn *websocket.Conn // Websocket connection of the client
|
|
|
|
Mutex sync.Mutex // Mutex used to lock
|
2024-10-20 09:06:37 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Sends a message to the websocket.
|
|
|
|
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
|
2024-10-20 09:06:37 +00:00
|
|
|
func (c *Client) SendMessage(messageType int, data []byte) error {
|
|
|
|
c.Mutex.Lock()
|
|
|
|
defer c.Mutex.Unlock()
|
|
|
|
|
|
|
|
err := c.Conn.WriteMessage(messageType, data)
|
|
|
|
if err != nil {
|
2024-10-25 22:01:07 +00:00
|
|
|
log.Error("Error writing to WebSocket:", "msg", err)
|
2024-10-20 09:06:37 +00:00
|
|
|
c.Conn.Close() // Close the connection on error
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|