snow/handlers/socket.go

74 lines
1.3 KiB
Go
Raw Normal View History

2024-01-20 01:58:57 +00:00
package handlers
import (
"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-20 23:08:29 +00:00
Type SocketType
2024-01-20 01:58:57 +00:00
Connection *websocket.Conn
Person *person.Person
}
var (
2024-01-20 23:08:29 +00:00
handles = map[SocketType]func(string) {
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,
})
defer close(uuid)
2024-01-20 23:08:29 +00:00
if handle, ok := handles[protocol]; ok {
handle(uuid)
}
2024-01-20 01:58:57 +00:00
}
func close(id string) {
socket, ok := sockets.Get(id)
if !ok {
return
}
socket.Connection.Close()
sockets.Delete(id)
aid.Print("(xmpp) connection closed", id)
}