snow/handlers/socket.go

117 lines
2.1 KiB
Go
Raw Normal View History

2024-01-20 01:58:57 +00:00
package handlers
import (
2024-01-21 00:18:40 +00:00
"github.com/beevik/etree"
2024-01-20 01:58:57 +00:00
"github.com/ectrc/snow/aid"
"github.com/ectrc/snow/person"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
2024-01-20 23:08:29 +00:00
type SocketType string
var (
SocketTypeXmpp SocketType = "xmpp"
SocketTypeUnknown SocketType = "unknown"
)
2024-01-20 01:58:57 +00:00
type Socket struct {
ID string
2024-01-21 00:18:40 +00:00
JID string
2024-01-20 23:08:29 +00:00
Type SocketType
2024-01-20 01:58:57 +00:00
Connection *websocket.Conn
Person *person.Person
}
2024-01-21 00:18:40 +00:00
type MessageToWrite struct {
Socket *Socket
Message []byte
}
func (s *Socket) Write(message []byte) {
socketWriteQueue <- MessageToWrite{
Socket: s,
Message: message,
}
}
func (s *Socket) WriteTree(message *etree.Document) {
bytes, err := message.WriteToBytes()
if err != nil {
return
}
socketWriteQueue <- MessageToWrite{
Socket: s,
Message: bytes,
}
}
2024-01-20 01:58:57 +00:00
var (
2024-01-21 00:18:40 +00:00
socketWriteQueue = make(chan MessageToWrite, 1000)
socketHandlers = map[SocketType]func(string) {
2024-01-20 23:08:29 +00:00
SocketTypeXmpp: handlePresenceSocket,
}
2024-01-20 01:58:57 +00:00
sockets = aid.GenericSyncMap[Socket]{}
)
func MiddlewareWebsocket(c *fiber.Ctx) error {
if !websocket.IsWebSocketUpgrade(c) {
return fiber.ErrUpgradeRequired
}
2024-01-20 23:08:29 +00:00
var protocol SocketType
switch c.Get("Sec-WebSocket-Protocol") {
case "xmpp":
protocol = SocketTypeXmpp
default:
protocol = SocketTypeUnknown
}
2024-01-20 01:58:57 +00:00
c.Locals("uuid", uuid.New().String())
2024-01-20 23:08:29 +00:00
c.Locals("protocol", protocol)
2024-01-20 01:58:57 +00:00
return c.Next()
}
func WebsocketConnection(c *websocket.Conn) {
2024-01-20 23:08:29 +00:00
protocol := c.Locals("protocol").(SocketType)
2024-01-20 01:58:57 +00:00
uuid := c.Locals("uuid").(string)
sockets.Add(uuid, &Socket{
ID: uuid,
2024-01-20 23:08:29 +00:00
Type: protocol,
2024-01-20 01:58:57 +00:00
Connection: c,
})
2024-01-21 00:18:40 +00:00
defer func() {
socket, ok := sockets.Get(uuid)
if !ok {
return
}
socket.Connection.Close()
sockets.Delete(uuid)
aid.Print("(xmpp) connection closed", uuid)
}()
2024-01-20 01:58:57 +00:00
2024-01-21 00:18:40 +00:00
if handle, ok := socketHandlers[protocol]; ok {
2024-01-20 23:08:29 +00:00
handle(uuid)
}
2024-01-20 01:58:57 +00:00
}
2024-01-21 00:18:40 +00:00
func init() {
go func() {
for {
if aid.Config != nil {
break
}
}
aid.Print("(socket) write queue started")
for {
message := <-socketWriteQueue
aid.Print("(socket) message sent", message.Socket.ID, string(message.Message))
message.Socket.Connection.WriteMessage(websocket.TextMessage, message.Message)
}
}()
2024-01-20 01:58:57 +00:00
}