Marco
636ce06836
1. Lobbies are only identified by their passphrases 2. Improve logging 3. Do not close an existing websocket connection for a player but ignore the request
86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"mchess_server/api"
|
|
"mchess_server/utils"
|
|
"net/http"
|
|
|
|
"mchess_server/lobbies"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
gorillaws "github.com/gorilla/websocket"
|
|
)
|
|
|
|
var upgrader = gorillaws.Upgrader{
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true
|
|
},
|
|
}
|
|
|
|
func RegisterWebSocketConnection(c *gin.Context) {
|
|
limiter.Take()
|
|
|
|
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
go waitForAndHandlePlayerID(c, conn)
|
|
}
|
|
|
|
func waitForAndHandlePlayerID(ctx context.Context, conn *gorillaws.Conn) {
|
|
limiter.Take()
|
|
|
|
msgType, msg, err := conn.ReadMessage()
|
|
if err != nil {
|
|
errorMessage := fmt.Sprintf("Reading from websocket connection did not work: %s", err)
|
|
log.Println(errorMessage)
|
|
conn.Close()
|
|
return
|
|
}
|
|
|
|
log.Println("read from websocket endpoint: ", msgType, string(msg), err)
|
|
|
|
var info api.PlayerInfo
|
|
err = json.Unmarshal(msg, &info)
|
|
if err != nil {
|
|
errorMessage := fmt.Sprintf("Unmarshaling message did not work: %s", err)
|
|
log.Println(errorMessage)
|
|
conn.WriteMessage(msgType, []byte(errorMessage))
|
|
conn.Close()
|
|
return
|
|
}
|
|
|
|
lobby := lobbies.GetLobbyRegistry().GetLobbyByPassphrase(utils.NewPassphraseFromString(*info.Passphrase))
|
|
if lobby == nil {
|
|
conn.WriteMessage(msgType, []byte("lobby not found"))
|
|
conn.Close()
|
|
return
|
|
}
|
|
|
|
player, found := lobby.GetPlayerByUUID(*info.PlayerID)
|
|
if !found {
|
|
conn.WriteMessage(msgType, []byte("player not found"))
|
|
conn.Close()
|
|
return
|
|
}
|
|
if player.Conn.HasWebsocketConnection() {
|
|
conn.WriteMessage(msgType, []byte("player already connected"))
|
|
return
|
|
}
|
|
lobby.Game.SetWebsocketConnectionFor(ctx, player, conn)
|
|
log.Println("player after setting connection: ")
|
|
log.Println("id: ", player.Uuid)
|
|
log.Println("color: ", player.GetColor())
|
|
log.Println("Connection: ", player.Conn.ID)
|
|
}
|
|
|
|
func ConnectWsForGame(c *gin.Context) {
|
|
limiter.Take()
|
|
|
|
}
|