2024-06-22 10:05:41 +00:00
|
|
|
package api
|
2024-03-30 09:10:36 +00:00
|
|
|
|
|
|
|
import (
|
2024-06-22 10:05:41 +00:00
|
|
|
"git.solsynth.dev/hydrogen/messaging/pkg/internal/models"
|
|
|
|
"git.solsynth.dev/hydrogen/messaging/pkg/internal/services"
|
2024-03-30 09:10:36 +00:00
|
|
|
"github.com/gofiber/contrib/websocket"
|
|
|
|
jsoniter "github.com/json-iterator/go"
|
2024-05-26 15:01:20 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2024-03-30 09:10:36 +00:00
|
|
|
)
|
|
|
|
|
2024-04-25 13:00:45 +00:00
|
|
|
func messageGateway(c *websocket.Conn) {
|
2024-06-22 10:29:41 +00:00
|
|
|
user := c.Locals("user").(models.Account)
|
2024-03-30 09:10:36 +00:00
|
|
|
|
|
|
|
// Push connection
|
2024-05-07 12:45:02 +00:00
|
|
|
services.ClientRegister(user, c)
|
2024-05-26 15:01:20 +00:00
|
|
|
log.Debug().Uint("user", user.ID).Msg("New websocket connection established...")
|
2024-03-30 09:10:36 +00:00
|
|
|
|
|
|
|
// Event loop
|
|
|
|
var task models.UnifiedCommand
|
|
|
|
|
|
|
|
var messageType int
|
|
|
|
var packet []byte
|
|
|
|
var err error
|
|
|
|
|
|
|
|
for {
|
|
|
|
if messageType, packet, err = c.ReadMessage(); err != nil {
|
|
|
|
break
|
|
|
|
} else if err := jsoniter.Unmarshal(packet, &task); err != nil {
|
|
|
|
_ = c.WriteMessage(messageType, models.UnifiedCommand{
|
|
|
|
Action: "error",
|
|
|
|
Message: "unable to unmarshal your command, requires json request",
|
|
|
|
}.Marshal())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
message := services.DealCommand(task, user)
|
|
|
|
|
|
|
|
if message != nil {
|
|
|
|
if err = c.WriteMessage(messageType, message.Marshal()); err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pop connection
|
2024-05-07 12:45:02 +00:00
|
|
|
services.ClientUnregister(user, c)
|
2024-05-26 15:01:20 +00:00
|
|
|
log.Debug().Uint("user", user.ID).Msg("A websocket connection disconnected...")
|
2024-03-30 09:10:36 +00:00
|
|
|
}
|