commit 95a5d460352be5fb98aedf4f3a2f403ea9ab20bb
parent 6e63419f661d3e271397a09ab69a0e5d3cc68595
Author: n0tr1v <n0tr1v@protonmail.com>
Date: Sun, 11 Jun 2023 18:47:05 -0700
useless code
Diffstat:
5 files changed, 9 insertions(+), 178 deletions(-)
diff --git a/pkg/web/handlers/api/v1/handlers.go b/pkg/web/handlers/api/v1/handlers.go
@@ -530,23 +530,6 @@ func CaptchaSolverHandler(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]any{"answer": answer})
}
-func ChessHandler(c echo.Context) error {
- authUser := c.Get("authUser").(*database.User)
- db := c.Get("database").(*database.DkfDB)
- roomName := c.Request().PostFormValue("room")
- enemyUsername := database.Username(c.Request().PostFormValue("enemyUsername"))
- pos := c.Request().PostFormValue("move")
- redirectURL := "/api/v1/chat/messages/" + roomName
- room, roomKey, err := dutils.GetRoomAndKey(db, c, roomName)
- if err != nil {
- return c.Redirect(http.StatusFound, redirectURL+"?error="+err.Error()+"&errorTs="+utils.FormatInt64(time.Now().Unix()))
- }
- if err = interceptors.ChessInstance.PlayMove(enemyUsername, pos, *authUser, c, roomName, roomKey, room.ID); err != nil {
- return c.Redirect(http.StatusFound, redirectURL+"?error="+err.Error()+"&errorTs="+utils.FormatInt64(time.Now().Unix()))
- }
- return c.Redirect(http.StatusFound, redirectURL)
-}
-
func WerewolfHandler(c echo.Context) error {
db := c.Get("database").(*database.DkfDB)
roomName := "werewolf"
diff --git a/pkg/web/handlers/api/v1/topBarHandler.go b/pkg/web/handlers/api/v1/topBarHandler.go
@@ -191,7 +191,6 @@ func ChatTopBarHandler(c echo.Context) error {
interceptorsArr := []interceptors.Interceptor{
interceptors.SnippetInterceptor{},
interceptors.SpamInterceptor{},
- interceptors.ChessInstance,
interceptors.BattleshipInstance,
interceptors.WWInstance,
interceptors.BangInterceptor{},
diff --git a/pkg/web/handlers/interceptors/chess.go b/pkg/web/handlers/interceptors/chess.go
@@ -2,13 +2,11 @@ package interceptors
import (
"bytes"
- "dkforest/bindata"
"dkforest/pkg/config"
"dkforest/pkg/database"
dutils "dkforest/pkg/database/utils"
"dkforest/pkg/pubsub"
"dkforest/pkg/utils"
- "dkforest/pkg/web/handlers/interceptors/command"
"encoding/base64"
"errors"
"fmt"
@@ -16,7 +14,6 @@ import (
"github.com/google/uuid"
"github.com/labstack/echo"
"github.com/notnil/chess"
- "github.com/sirupsen/logrus"
"html/template"
"image"
"image/color"
@@ -221,13 +218,11 @@ input[type=checkbox]:checked + label {
return buf.String()
}
-func renderBoardPng(last *chess.Move, position *chess.Position, isFlipped bool) image.Image {
- boardMap := position.Board().SquareMap()
+func renderBoardPng(isFlipped bool) image.Image {
ctx := gg.NewContext(boardSize, boardSize)
for i := 0; i < 64; i++ {
sq := chess.Square(i)
- sqPiece := boardMap[sq]
- renderSquare(ctx, sq, last, position.Turn(), sqPiece, isFlipped)
+ renderSquare(ctx, sq, isFlipped)
}
return ctx.Image()
}
@@ -252,7 +247,7 @@ func colorForSquare(sq chess.Square) color.RGBA {
return color.RGBA{R: 235, G: 209, B: 166, A: 255}
}
-func renderSquare(ctx *gg.Context, sq chess.Square, last *chess.Move, turn chess.Color, sqPiece chess.Piece, isFlipped bool) {
+func renderSquare(ctx *gg.Context, sq chess.Square, isFlipped bool) {
x, y := XyForSquare(isFlipped, sq)
// draw square
ctx.Push()
@@ -260,17 +255,8 @@ func renderSquare(ctx *gg.Context, sq chess.Square, last *chess.Move, turn chess
ctx.DrawRectangle(float64(x), float64(y), sqSize, sqSize)
ctx.Fill()
ctx.Pop()
- // Draw previous move
- //if last != nil {
- // if last.S1() == sq || last.S2() == sq {
- // ctx.Push()
- // ctx.SetRGBA(0, 1, 0, 0.1)
- // ctx.DrawRectangle(float64(x), float64(y), sqSize, sqSize)
- // ctx.Fill()
- // ctx.Pop()
- // }
- //}
+ // Draw file/rank
ctx.Push()
ctx.SetColor(color.RGBA{R: 0, G: 0, B: 0, A: 180})
if (!isFlipped && sq.Rank() == chess.Rank1) || (isFlipped && sq.Rank() == chess.Rank8) {
@@ -291,69 +277,6 @@ var pieceTypeMap = map[chess.PieceType]string{
chess.Pawn: "P",
}
-var cache = make(map[string]image.Image)
-
-func getFile(fileName string) image.Image {
- if img, ok := cache[fileName]; ok {
- return img
- }
- fileBy := bindata.MustAsset(fileName)
- img, _ := png.Decode(bytes.NewReader(fileBy))
- cache[fileName] = img
- return img
-}
-
-func renderTable(imgB64 string, isBlack bool) string {
- htmlTmpl := `
-<style>
-input[type=checkbox] {
- display:none;
-}
-input[type=checkbox] + label {
- display: inline-block;
- padding: 0 0 0 0;
- margin: 0 0 0 0;
- height: 39px;
- width: 39px;
- background-size: 100%;
- border: 3px solid transparent;
-}
-input[type=checkbox]:checked + label {
- display: inline-block;
- background-size: 100%;
- border: 3px solid red;
-}
-</style>
-
-<table style="width: 360px; height: 360px; background-image: url(data:image/png;base64,{{ .ImgB64 }})">
- {{ range $row := .Rows }}
- <tr>
- {{ range $col := $.Cols }}
- {{ $id := GetID $row $col }}
- <td>
- <input name="sq_{{ $id }}" ID="sq_{{ $id }}" type="checkbox" value="1" />
- <label for="sq_{{ $id }}"></label>
- </td>
- {{ end }}
- </tr>
- {{ end }}
-</table>
-`
- data := map[string]any{
- "ImgB64": imgB64,
- "Rows": []int{0, 1, 2, 3, 4, 5, 6, 7},
- "Cols": []int{0, 1, 2, 3, 4, 5, 6, 7},
- }
-
- fns := template.FuncMap{
- "GetID": func(row, col int) int { return getID(row, col, isBlack) },
- }
-
- var buf bytes.Buffer
- _ = utils.Must(template.New("").Funcs(fns).Parse(htmlTmpl)).Execute(&buf, data)
- return buf.String()
-}
-
func (g *ChessGame) renderBoardHTML(isFlipped bool, imgB64 string, spectator bool) string {
position := g.Game.Position()
out := g.renderBoardHTML1(position, isFlipped, imgB64, spectator)
@@ -361,24 +284,18 @@ func (g *ChessGame) renderBoardHTML(isFlipped bool, imgB64 string, spectator boo
}
func (g *ChessGame) renderBoardB64(isFlipped bool) string {
- position := g.Game.Position()
- moves := g.Game.Moves()
- var last *chess.Move
- if len(moves) > 0 {
- last = moves[len(moves)-1]
- }
var buf bytes.Buffer
- img := renderBoardPng(last, position, isFlipped)
+ img := renderBoardPng(isFlipped)
_ = png.Encode(&buf, img)
imgB64 := base64.StdEncoding.EncodeToString(buf.Bytes())
return imgB64
}
func (g *ChessGame) DrawPlayerCard(key string, isBlack, isYourTurn bool) string {
- return g.drawPlayerCard(key, "", isBlack, isYourTurn)
+ return g.drawPlayerCard(key, isBlack, isYourTurn)
}
-func (g *ChessGame) drawPlayerCard(key, roomName string, isBlack, isYourTurn bool) string {
+func (g *ChessGame) drawPlayerCard(key string, isBlack, isYourTurn bool) string {
enemy := utils.Ternary(isBlack, g.Player1, g.Player2)
imgB64 := g.renderBoardB64(isBlack)
@@ -412,15 +329,9 @@ func (g *ChessGame) drawPlayerCard(key, roomName string, isBlack, isYourTurn boo
</form>
<div style="position: relative;">
<iframe src="/chess/{{ .Key }}/form" style="position: absolute; top: 0; left: 0; border: 0px solid red; z-index: 999; width: 100%; height: 100%;"></iframe>
- <form method="post"{{ if .InChat }} action="/api/v1/chess"{{ end }} style="aspect-ratio: 1/1; height: 70%;">
+ <form method="post"style="aspect-ratio: 1/1; height: 70%;">
{{ .Table }}
- {{ if .InChat }}
- <input type="hidden" name="room" value="{{ .RoomName }}" />
- <input type="hidden" name="enemyUsername" value="{{ .Username }}" />
- <input type="hidden" name="move" value="move" />
- {{ else }}
- <input type="hidden" name="message" value="/pm {{ .Username }} /c move" />
- {{ end }}
+ <input type="hidden" name="message" value="/pm {{ .Username }} /c move" />
<div style="width: 100%; display: flex; margin: 5px 0;">
<div>
<button type="submit" style="background-color: #aaa;">Move</button>
@@ -459,8 +370,6 @@ func (g *ChessGame) drawPlayerCard(key, roomName string, isBlack, isYourTurn boo
data := map[string]any{
"Key": key,
- "RoomName": roomName,
- "InChat": roomName != "",
"White": g.Player1,
"Black": g.Player2,
"Username": enemy.Username,
@@ -721,61 +630,3 @@ type ChessMove struct {
}
var ChessPubSub = pubsub.NewPubSub[ChessMove]()
-
-func (b *Chess) InterceptMsg(cmd *command.Command) {
- m := cRgx.FindStringSubmatch(cmd.Message)
- if len(m) != 3 {
- return
- }
- enemyUsername := database.Username(m[1])
- pos := m[2]
- if err := b.PlayMove(enemyUsername, pos, *cmd.AuthUser, cmd.C, cmd.Room.Name, cmd.RoomKey, cmd.Room.ID); err != nil {
- cmd.Err = err
- return
- }
- cmd.Err = command.ErrStop
-}
-
-func (b *Chess) PlayMove(enemyUsername database.Username, pos string, authUser database.User, c echo.Context, roomName, roomKey string, roomID database.RoomID) error {
- b.Lock()
- defer b.Unlock()
-
- user, err := b.db.GetUserByUsername(enemyUsername)
- if err != nil {
- return errors.New("invalid username")
- }
-
- var gameKey string
- if authUser.ID < user.ID {
- gameKey = fmt.Sprintf("%d_%d", authUser.ID, user.ID)
- } else {
- gameKey = fmt.Sprintf("%d_%d", user.ID, authUser.ID)
- }
-
- g, ok := b.games[gameKey]
- if ok {
- if err := b.SendMove(gameKey, authUser.ID, g, c); err != nil {
- return err
- }
- } else {
- if pos != "" {
- return errors.New("no Game ongoing")
- }
- g = b.newGame(gameKey, user, authUser)
- }
-
- // Delete old messages sent by "0" to the players
- if err := b.db.DB().
- Where("room_id = ? AND user_id = ? AND (to_user_id = ? OR to_user_id = ?)", roomID, b.zeroID, g.Player1.ID, g.Player2.ID).
- Delete(&database.ChatMessage{}).Error; err != nil {
- logrus.Error(err)
- }
-
- card1 := g.drawPlayerCard(gameKey, roomName, false, true)
- _, _ = b.db.CreateMsg(card1, card1, roomKey, roomID, b.zeroID, &g.Player1.ID)
-
- card1 = g.drawPlayerCard(gameKey, roomName, true, true)
- _, _ = b.db.CreateMsg(card1, card1, roomKey, roomID, b.zeroID, &g.Player2.ID)
-
- return nil
-}
diff --git a/pkg/web/middlewares/middlewares.go b/pkg/web/middlewares/middlewares.go
@@ -176,7 +176,6 @@ func CSRFMiddleware() echo.MiddlewareFunc {
apiKey := c.Request().Header.Get("DKF_API_KEY")
return (apiKey != "" && strings.HasPrefix(c.Path(), "/api/v1/")) ||
c.Path() == "/api/v1/battleship" ||
- c.Path() == "/api/v1/chess" ||
c.Path() == "/api/v1/werewolf" ||
c.Path() == "/chess/:key"
},
diff --git a/pkg/web/web.go b/pkg/web/web.go
@@ -145,7 +145,6 @@ func getMainServer(db *database.DkfDB, i18nBundle *i18n.Bundle, renderer *tmp.Te
authGroup.GET("/api/v1/captcha-svc", v1.GetCaptchaHandler)
authGroup.POST("/api/v1/chat/:roomName/notifier", v1.RoomNotifierHandler)
authGroup.POST("/api/v1/battleship", v1.BattleshipHandler)
- authGroup.POST("/api/v1/chess", v1.ChessHandler)
authGroup.POST("/api/v1/werewolf", v1.WerewolfHandler)
authGroup.POST("/api/v1/captcha/solver", v1.CaptchaSolverHandler)
authGroup.GET("/api/v1/chat/controls/:roomName/:isStream", v1.ChatControlsHandler)