snow/socket/socket.go

74 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-01-28 22:04:40 +00:00
package socket
import (
"reflect"
"sync"
2024-01-28 22:04:40 +00:00
"github.com/ectrc/snow/aid"
"github.com/ectrc/snow/person"
"github.com/gofiber/contrib/websocket"
"github.com/google/uuid"
)
type MatchmakerData struct {
PlaylistID string
Region string
}
2024-02-16 01:14:14 +00:00
type WebSocket interface {
WriteMessage(messageType int, data []byte) error
ReadMessage() (messageType int, p []byte, err error)
}
2024-01-29 21:08:05 +00:00
type Socket[T JabberData | MatchmakerData] struct {
2024-01-28 22:04:40 +00:00
ID string
2024-02-16 01:14:14 +00:00
Connection WebSocket
2024-01-28 22:04:40 +00:00
Data *T
Person *person.Person
2024-01-31 16:21:19 +00:00
M sync.Mutex
}
func (s *Socket[T]) Write(payload []byte) {
2024-01-31 16:21:19 +00:00
s.M.Lock()
defer s.M.Unlock()
err := s.Connection.WriteMessage(websocket.TextMessage, payload)
if err != nil {
s.Remove()
}
}
func (s *Socket[T]) Remove() {
reflectType := reflect.TypeOf(s.Data).String()
switch reflectType {
case "*socket.JabberData":
JabberSockets.Delete(s.ID)
case "*socket.MatchmakerData":
MatchmakerSockets.Delete(s.ID)
}
2024-01-28 22:04:40 +00:00
}
2024-02-16 01:14:14 +00:00
func newSocket[T JabberData | MatchmakerData](conn WebSocket, data ...T) *Socket[T] {
2024-01-28 22:04:40 +00:00
additional := data[0]
return &Socket[T]{
ID: uuid.New().String(),
Connection: conn,
Data: &additional,
}
}
2024-02-16 01:14:14 +00:00
func NewJabberSocket(conn WebSocket, id string, data JabberData) *Socket[JabberData] {
2024-01-28 22:04:40 +00:00
socket := newSocket[JabberData](conn, data)
socket.ID = id
return socket
}
func NewMatchmakerSocket(conn *websocket.Conn, data MatchmakerData) *Socket[MatchmakerData] {
return newSocket[MatchmakerData](conn, data)
}
var (
JabberSockets = aid.GenericSyncMap[Socket[JabberData]]{}
MatchmakerSockets = aid.GenericSyncMap[Socket[MatchmakerData]]{}
)