package api import ( json "encoding/json" "errors" "fmt" "log" "net/http" "strconv" "strings" "github.com/gofrs/uuid/v5" "golang.org/x/text/cases" "golang.org/x/text/language" "medad.fun/internal/config" "medad.fun/internal/game" "medad.fun/internal/state" ) var ErrLobbyNotExistent = errors.New("the requested lobby doesn't exist") type V1Handler struct { cfg *config.Config } func NewHandler(cfg *config.Config) *V1Handler { return &V1Handler{ cfg: cfg, } } func marshalToHTTPWriter(data any, writer http.ResponseWriter) (bool, error) { bytes, err := json.Marshal(data) if err != nil { return false, err } writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Length", strconv.Itoa(len(bytes))) _, err = writer.Write(bytes) return true, err } type LobbyEntries []*LobbyEntry // LobbyEntry is an API object for representing a join-able public lobby. type LobbyEntry struct { LobbyID string `json:"lobbyId"` Wordpack string `json:"wordpack"` Scoring string `json:"scoring"` State game.State `json:"state"` PlayerCount int `json:"playerCount"` MaxPlayers int `json:"maxPlayers"` Round int `json:"round"` Rounds int `json:"rounds"` DrawingTime int `json:"drawingTime"` MaxClientsPerIP int `json:"maxClientsPerIp"` CustomWords bool `json:"customWords"` } func (handler *V1Handler) getLobbies(writer http.ResponseWriter, _ *http.Request) { // REMARK: If paging is ever implemented, we might want to maintain order // when deleting lobbies from state in the state package. lobbies := state.GetPublicLobbies() lobbyEntries := make(LobbyEntries, 0, len(lobbies)) for _, lobby := range lobbies { // While one would expect locking the lobby here, it's not very // important to get 100% consistent results here. lobbyEntries = append(lobbyEntries, &LobbyEntry{ LobbyID: lobby.LobbyID, PlayerCount: lobby.GetConnectedPlayerCount(), MaxPlayers: lobby.MaxPlayers, Round: lobby.Round, Rounds: lobby.Rounds, DrawingTime: lobby.DrawingTime, CustomWords: len(lobby.CustomWords) > 0, MaxClientsPerIP: lobby.ClientsPerIPLimit, Wordpack: lobby.Wordpack, State: lobby.State, Scoring: lobby.ScoreCalculation.Identifier(), }) } if started, err := marshalToHTTPWriter(lobbyEntries, writer); err != nil { if !started { http.Error(writer, err.Error(), http.StatusInternalServerError) } return } } func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Request) { if err := request.ParseForm(); err != nil { http.Error(writer, err.Error(), http.StatusBadRequest) return } var requestErrors []string // The lobby ID is normally autogenerated and it isn't advisble to set it // yourself, but for certain integrations / automations this can be useful. // However, to avoid any kind of abuse, this needs to be a valid UUID at // least. lobbyId := request.Form.Get("lobby_id") if lobbyId != "" { var err error _, err = uuid.FromString(lobbyId) if err != nil { requestErrors = append(requestErrors, err.Error()) } } scoreCalculation, scoreCalculationInvalid := ParseScoreCalculation(request.Form.Get("score_calculation")) languageData, languageKey, languageInvalid := ParseLanguage(request.Form.Get("language")) drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, request.Form.Get("drawing_time")) rounds, roundsInvalid := ParseRounds(handler.cfg, request.Form.Get("rounds")) maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, request.Form.Get("max_players")) wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("words_per_turn"), config.Default.LobbySettingBounds.MaxWordsPerTurn) customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("custom_words_per_turn"), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn) clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, request.Form.Get("clients_per_ip_limit")) publicLobby, publicLobbyInvalid := ParseBoolean("public", request.Form.Get("public")) var lowercaser cases.Caser if languageInvalid != nil { lowercaser = cases.Lower(language.English) } else { lowercaser = languageData.Lowercaser() } customWords, customWordsInvalid := ParseCustomWords(lowercaser, request.Form.Get("custom_words")) if scoreCalculationInvalid != nil { requestErrors = append(requestErrors, scoreCalculationInvalid.Error()) } if languageInvalid != nil { requestErrors = append(requestErrors, languageInvalid.Error()) } if drawingTimeInvalid != nil { requestErrors = append(requestErrors, drawingTimeInvalid.Error()) } if roundsInvalid != nil { requestErrors = append(requestErrors, roundsInvalid.Error()) } if maxPlayersInvalid != nil { requestErrors = append(requestErrors, maxPlayersInvalid.Error()) } if customWordsInvalid != nil { requestErrors = append(requestErrors, customWordsInvalid.Error()) } if wordsPerTurnInvalid != nil { requestErrors = append(requestErrors, wordsPerTurnInvalid.Error()) } if customWordsPerTurnInvalid != nil { requestErrors = append(requestErrors, customWordsPerTurnInvalid.Error()) } if clientsPerIPLimitInvalid != nil { requestErrors = append(requestErrors, clientsPerIPLimitInvalid.Error()) } if publicLobbyInvalid != nil { requestErrors = append(requestErrors, publicLobbyInvalid.Error()) } if len(requestErrors) != 0 { http.Error(writer, strings.Join(requestErrors, ";"), http.StatusBadRequest) return } playerName := GetPlayername(request) player, lobby, err := game.CreateLobby(lobbyId, playerName, languageKey, publicLobby, drawingTime, rounds, maxPlayers, wordsPerTurn, customWordsPerTurn, clientsPerIPLimit, customWords, scoreCalculation) if err != nil { http.Error(writer, err.Error(), http.StatusBadRequest) return } // Due to the fact the IDs can be chosen manually, there's a big clash // potential! However, since we only allow specifying this via the rest API // we treat this here. This can't be treated in the game package right now // anyway though, as there'd be an import cycle. if state.GetLobby(lobby.LobbyID) != nil { http.Error(writer, "lobby id already in use", http.StatusBadRequest) return } lobby.WriteObject = WriteObject lobby.WritePreparedMessage = WritePreparedMessage player.SetLastKnownAddress(GetIPAddressFromRequest(request)) SetGameplayCookies(writer, request, player, lobby) lobbyData := CreateLobbyData(handler.cfg, lobby) if started, err := marshalToHTTPWriter(lobbyData, writer); err != nil { if !started { http.Error(writer, err.Error(), http.StatusInternalServerError) } return } // We only add the lobby if everything else was successful. state.AddLobby(lobby) } func (handler *V1Handler) postPlayer(writer http.ResponseWriter, request *http.Request) { lobby := state.GetLobby(request.PathValue("lobby_id")) if lobby == nil { http.Error(writer, ErrLobbyNotExistent.Error(), http.StatusNotFound) return } var lobbyData *LobbyData lobby.Synchronized(func() { player := GetPlayer(lobby, request) if player == nil { if !lobby.HasFreePlayerSlot() { http.Error(writer, "lobby already full", http.StatusUnauthorized) return } requestAddress := GetIPAddressFromRequest(request) if !lobby.CanIPConnect(requestAddress) { http.Error(writer, "maximum amount of players per IP reached", http.StatusUnauthorized) return } newPlayer := lobby.JoinPlayer(GetPlayername(request)) newPlayer.SetLastKnownAddress(requestAddress) // Use the players generated usersession and pass it as a cookie. SetGameplayCookies(writer, request, newPlayer, lobby) } else { player.SetLastKnownAddress(GetIPAddressFromRequest(request)) } lobbyData = CreateLobbyData(handler.cfg, lobby) }) if lobbyData != nil { if started, err := marshalToHTTPWriter(lobbyData, writer); err != nil { if !started { http.Error(writer, err.Error(), http.StatusInternalServerError) } return } } } func GetDiscordInstanceId(request *http.Request) string { discordInstanceId := request.URL.Query().Get("instance_id") if discordInstanceId == "" { cookie, _ := request.Cookie("discord-instance-id") if cookie != nil { discordInstanceId = cookie.Value } } return discordInstanceId } const discordDomain = "1320396325925163070.discordsays.com" func SetDiscordCookies(w http.ResponseWriter, request *http.Request) { discordInstanceId := GetDiscordInstanceId(request) if discordInstanceId != "" { http.SetCookie(w, &http.Cookie{ Name: "discord-instance-id", Value: discordInstanceId, Domain: discordDomain, Path: "/", SameSite: http.SameSiteNoneMode, Partitioned: true, Secure: true, }) } } // SetGameplayCookies takes the players usersession and lobby id // and sets them as a cookie. func SetGameplayCookies( w http.ResponseWriter, request *http.Request, player *game.Player, lobby *game.Lobby, ) { discordInstanceId := GetDiscordInstanceId(request) if discordInstanceId != "" { http.SetCookie(w, &http.Cookie{ Name: "usersession", Value: player.GetUserSession().String(), Domain: discordDomain, Path: "/", SameSite: http.SameSiteNoneMode, Partitioned: true, Secure: true, }) http.SetCookie(w, &http.Cookie{ Name: "lobby-id", Value: lobby.LobbyID, Domain: discordDomain, Path: "/", SameSite: http.SameSiteNoneMode, Partitioned: true, Secure: true, }) } else { // For the discord case, we need both, as the discord specific cookies // aren't available during the readirect from ssrCreate to ssrEnter. http.SetCookie(w, &http.Cookie{ Name: "usersession", Value: player.GetUserSession().String(), Path: "/", SameSite: http.SameSiteStrictMode, }) http.SetCookie(w, &http.Cookie{ Name: "lobby-id", Value: lobby.LobbyID, Path: "/", SameSite: http.SameSiteStrictMode, }) } } func (handler *V1Handler) patchLobby(writer http.ResponseWriter, request *http.Request) { userSession, err := GetUserSession(request) if err != nil { log.Printf("error getting user session: %v", err) http.Error(writer, "no valid usersession supplied", http.StatusBadRequest) return } if userSession == uuid.Nil { http.Error(writer, "no usersession supplied", http.StatusBadRequest) return } lobby := state.GetLobby(GetLobbyId(request)) if lobby == nil { http.Error(writer, ErrLobbyNotExistent.Error(), http.StatusNotFound) return } if err := request.ParseForm(); err != nil { http.Error(writer, fmt.Sprintf("error parsing request query into form (%s)", err), http.StatusBadRequest) return } var requestErrors []string // Uneditable properties if request.Form.Get("custom_words") != "" { requestErrors = append(requestErrors, "can't modify custom_words in existing lobby") } if request.Form.Get("language") != "" { requestErrors = append(requestErrors, "can't modify language in existing lobby") } // Editable properties maxPlayers, maxPlayersInvalid := ParseMaxPlayers(handler.cfg, request.Form.Get("max_players")) drawingTime, drawingTimeInvalid := ParseDrawingTime(handler.cfg, request.Form.Get("drawing_time")) rounds, roundsInvalid := ParseRounds(handler.cfg, request.Form.Get("rounds")) wordsPerTurn, wordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("words_per_turn"), config.Default.LobbySettingBounds.MaxWordsPerTurn) customWordsPerTurn, customWordsPerTurnInvalid := ParseCustomWordsPerTurn(request.Form.Get("custom_words_per_turn"), config.Default.LobbySettingBounds.MaxCustomWordsPerTurn) clientsPerIPLimit, clientsPerIPLimitInvalid := ParseClientsPerIPLimit(handler.cfg, request.Form.Get("clients_per_ip_limit")) publicLobby, publicLobbyInvalid := ParseBoolean("public", request.Form.Get("public")) owner := lobby.GetOwner() if owner == nil || owner.GetUserSession() != userSession { http.Error(writer, "only the lobby owner can edit the lobby", http.StatusForbidden) return } if maxPlayersInvalid != nil { requestErrors = append(requestErrors, maxPlayersInvalid.Error()) } if drawingTimeInvalid != nil { requestErrors = append(requestErrors, drawingTimeInvalid.Error()) } if roundsInvalid != nil { requestErrors = append(requestErrors, roundsInvalid.Error()) } else { currentRound := lobby.Round if rounds < currentRound { requestErrors = append(requestErrors, fmt.Sprintf("rounds must be greater than or equal to the current round (%d)", currentRound)) } } if wordsPerTurnInvalid != nil { requestErrors = append(requestErrors, wordsPerTurnInvalid.Error()) } if customWordsPerTurnInvalid != nil { requestErrors = append(requestErrors, customWordsPerTurnInvalid.Error()) } if clientsPerIPLimitInvalid != nil { requestErrors = append(requestErrors, clientsPerIPLimitInvalid.Error()) } if publicLobbyInvalid != nil { requestErrors = append(requestErrors, publicLobbyInvalid.Error()) } if len(requestErrors) != 0 { http.Error(writer, strings.Join(requestErrors, ";"), http.StatusBadRequest) return } // We synchronize as late as possible to avoid unnecessary lags. // The previous code here isn't really prone to bugs due to lack of sync. lobby.Synchronized(func() { // While changing maxClientsPerIP and maxPlayers to a value lower than // is currently being used makes little sense, we'll allow it, as it doesn't // really break anything. lobby.MaxPlayers = maxPlayers lobby.WordsPerTurn = wordsPerTurn lobby.CustomWordsPerTurn = customWordsPerTurn lobby.ClientsPerIPLimit = clientsPerIPLimit lobby.Public = publicLobby lobby.Rounds = rounds if lobby.State == game.Ongoing { lobby.DrawingTimeNew = drawingTime } else { lobby.DrawingTime = drawingTime } lobbySettingsCopy := lobby.EditableLobbySettings lobbySettingsCopy.DrawingTime = drawingTime lobby.Broadcast(&game.Event{Type: game.EventTypeLobbySettingsChanged, Data: lobbySettingsCopy}) }) } func (handler *V1Handler) getStats(writer http.ResponseWriter, _ *http.Request) { if started, err := marshalToHTTPWriter(state.Stats(), writer); err != nil { if !started { http.Error(writer, err.Error(), http.StatusInternalServerError) } return } } // SuggestedBrushSizes is suggested brush sizes value used for // Lobbydata objects. A unit test makes sure these values are ordered // and within the specified bounds. var SuggestedBrushSizes = [4]uint8{8, 16, 24, 32} // GameConstants are values that are lobby-independent and can't be changed via // settings, neither at compile time nor at startup time. type GameConstants struct { // DrawingBoardBaseWidth is the internal canvas width and is needed for // correctly up- / downscaling drawing instructions. DrawingBoardBaseWidth uint16 `json:"drawingBoardBaseWidth"` // DrawingBoardBaseHeight is the internal canvas height and is needed for // correctly up- / downscaling drawing instructions. DrawingBoardBaseHeight uint16 `json:"drawingBoardBaseHeight"` // MinBrushSize is the minimum amount of pixels the brush can draw in. MinBrushSize uint8 `json:"minBrushSize"` // MaxBrushSize is the maximum amount of pixels the brush can draw in. MaxBrushSize uint8 `json:"maxBrushSize"` // CanvasColor is the initially (empty) color of the canvas. CanvasColor uint8 `json:"canvasColor"` // SuggestedBrushSizes are suggestions for the different brush sizes // that the user can choose between. These brushes are guaranteed to // be ordered from low to high and stay with the bounds. SuggestedBrushSizes [4]uint8 `json:"suggestedBrushSizes"` } var GameConstantsData = &GameConstants{ DrawingBoardBaseWidth: game.DrawingBoardBaseWidth, DrawingBoardBaseHeight: game.DrawingBoardBaseHeight, MinBrushSize: game.MinBrushSize, MaxBrushSize: game.MaxBrushSize, CanvasColor: 0, /* White */ SuggestedBrushSizes: SuggestedBrushSizes, } // LobbyData is the data necessary for correctly configuring a lobby. // While unofficial clients will probably need all of these values, the // official webclient doesn't use all of them as of now. type LobbyData struct { game.SettingBounds game.EditableLobbySettings *GameConstants IsWordpackRtl bool } // CreateLobbyData creates a ready to use LobbyData object containing data // from the passed Lobby. func CreateLobbyData(cfg *config.Config, lobby *game.Lobby) *LobbyData { return &LobbyData{ SettingBounds: cfg.LobbySettingBounds, EditableLobbySettings: lobby.EditableLobbySettings, GameConstants: GameConstantsData, IsWordpackRtl: lobby.IsWordpackRtl, } } // GetUserSession accesses the usersession from an HTTP request and // returns the session. The session can either be in the cookie or in // the header. If no session can be found, an empty string is returned. func GetUserSession(request *http.Request) (uuid.UUID, error) { var userSession string if sessionCookie, err := request.Cookie("usersession"); err == nil && sessionCookie.Value != "" { userSession = sessionCookie.Value } else { userSession = request.Header.Get("Usersession") } if userSession == "" { return uuid.Nil, nil } id, err := uuid.FromString(userSession) if err != nil { return uuid.Nil, fmt.Errorf("error parsing user session: %w", err) } return id, nil } // GetPlayer returns the player object that matches the usersession in the // supplied HTTP request and lobby. If no user session is set, we return nil. func GetPlayer(lobby *game.Lobby, request *http.Request) *game.Player { userSession, err := GetUserSession(request) if err != nil { log.Printf("error getting user session: %v", err) return nil } if userSession == uuid.Nil { return nil } return lobby.GetPlayerBySession(userSession) } // GetPlayername either retrieves the playername from a cookie, the URL form. // If no preferred name can be found, we return an empty string. func GetPlayername(request *http.Request) string { if err := request.ParseForm(); err == nil { username := request.Form.Get("username") if username != "" { return username } } if usernameCookie, err := request.Cookie("username"); err == nil { if usernameCookie.Value != "" { return usernameCookie.Value } } return "" } // GetLobbyId returns either the lobby id from the URL or from a cookie. func GetLobbyId(request *http.Request) string { lobbyId := request.PathValue("lobby_id") if lobbyId == "" { cookie, _ := request.Cookie("lobby-id") lobbyId = cookie.Value } return lobbyId }