Messaging/pkg/internal/services/connections.go

48 lines
1015 B
Go
Raw Normal View History

2024-03-30 09:10:36 +00:00
package services
import (
2024-05-26 15:01:20 +00:00
"sync"
"git.solsynth.dev/hydrogen/messaging/pkg/internal/models"
2024-03-30 09:10:36 +00:00
"github.com/gofiber/contrib/websocket"
)
2024-05-26 15:01:20 +00:00
var (
wsMutex sync.Mutex
wsConn = make(map[uint]map[*websocket.Conn]bool)
)
2024-03-30 09:10:36 +00:00
func ClientRegister(user models.Account, conn *websocket.Conn) {
2024-05-26 15:01:20 +00:00
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[*websocket.Conn]bool)
}
wsConn[user.ID][conn] = true
2024-05-26 15:01:20 +00:00
wsMutex.Unlock()
}
func ClientUnregister(user models.Account, conn *websocket.Conn) {
2024-05-26 15:01:20 +00:00
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[*websocket.Conn]bool)
}
delete(wsConn[user.ID], conn)
2024-05-26 15:01:20 +00:00
wsMutex.Unlock()
2024-03-30 09:10:36 +00:00
}
func PushCommand(userId uint, task models.UnifiedCommand) {
for conn := range wsConn[userId] {
2024-03-30 09:10:36 +00:00
_ = conn.WriteMessage(1, task.Marshal())
}
}
func DealCommand(task models.UnifiedCommand, user models.Account) *models.UnifiedCommand {
switch task.Action {
default:
return &models.UnifiedCommand{
Action: "error",
Message: "command not found",
}
}
}