refatoramento fodido para reduzir codigo repetido de rotas
This commit is contained in:
Binary file not shown.
74
back_end/funcs.go
Normal file
74
back_end/funcs.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func jsonError(c echo.Context, code int, msg string) error {
|
||||
return c.JSON(code, resp_json{
|
||||
Status: "Error",
|
||||
Message: msg,
|
||||
})
|
||||
}
|
||||
|
||||
func jsonSuccess(c echo.Context, msg string) error {
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: msg,
|
||||
})
|
||||
}
|
||||
|
||||
func requireSession(c echo.Context) (map[string]string, error) {
|
||||
session, err := ValidSession(c)
|
||||
if err != nil {
|
||||
jsonError(c, http.StatusUnauthorized, err.Error())
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func anyEmpty(values ...string) bool {
|
||||
for _, v := range values {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func updateField(query string, args ...interface{}) error {
|
||||
_, err := db.Exec(query, args...)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func readAndValidateImage(file *multipart.FileHeader) (string, error) {
|
||||
if file.Size > 25*1024*1024 {
|
||||
return "", fmt.Errorf("imagem excede 25MB")
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(file.Filename))
|
||||
if !formatFILES[ext] {
|
||||
return "", fmt.Errorf("formato inválido")
|
||||
}
|
||||
open, err := file.Open()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer open.Close()
|
||||
data, err := io.ReadAll(open)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
@@ -1,55 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func logout(c echo.Context) error {
|
||||
_, err := ValidSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: "para fazer logout você deve estar logado seu cabaço",
|
||||
})
|
||||
}
|
||||
cookie, _ := c.Cookie(cookieName)
|
||||
|
||||
sessionID := cookie.Value
|
||||
delCookie(c, sessionID)
|
||||
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: "Você fez foi deslogado.",
|
||||
})
|
||||
}
|
||||
|
||||
func online(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: "Api esta online",
|
||||
})
|
||||
}
|
||||
|
||||
func badreq(c echo.Context) error {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "essa rota não foi preparada para requisições do tipo get.",
|
||||
})
|
||||
}
|
||||
|
||||
func registrar(c echo.Context) error {
|
||||
player := c.FormValue("player")
|
||||
password := c.FormValue("password")
|
||||
@@ -57,211 +20,137 @@ func registrar(c echo.Context) error {
|
||||
playerlore := c.FormValue("playerlore")
|
||||
|
||||
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(player) {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você usou caracteres proibidos no seu nome",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, "você usou caracteres proibidos no seu nome")
|
||||
}
|
||||
|
||||
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" || strings.TrimSpace(confpass) == "" || strings.TrimSpace(playerlore) == "" {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algum parametro esta faltando ou esta vazio, tente novamente",
|
||||
})
|
||||
if anyEmpty(player, password, confpass, playerlore) {
|
||||
return jsonError(c, http.StatusBadRequest, "algum parametro esta faltando ou esta vazio, tente novamente")
|
||||
}
|
||||
|
||||
if password != confpass {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Suas senhas não são iguais, verifique e tente novamente.",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, "Suas senhas não são iguais, verifique e tente novamente.")
|
||||
}
|
||||
|
||||
passhash, err := bcrypt.GenerateFromPassword([]byte(password), 15)
|
||||
if err != nil {
|
||||
log.Println("Algo deu errado com a hash de senha.")
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Erro ao criar hash de senha do usuario: " + player,
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao criar hash de senha do usuario: "+player)
|
||||
}
|
||||
|
||||
format := formatFILES
|
||||
|
||||
ImageFile, err := c.FormFile("PlayerImage")
|
||||
imageFile, err := c.FormFile("PlayerImage")
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Arquivo de Imagem não foi enviado, adcione uma imagem.",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, "Arquivo de Imagem não foi enviado, adcione uma imagem.")
|
||||
}
|
||||
|
||||
if !format[strings.ToLower(filepath.Ext(ImageFile.Filename))] {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "sua imagem deve ser png, jpg, jpeg ou gif.",
|
||||
})
|
||||
}
|
||||
openfile, err := ImageFile.Open()
|
||||
encode, err := readAndValidateImage(imageFile)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "não foi possivel ler sua imagem",
|
||||
})
|
||||
}
|
||||
defer openfile.Close()
|
||||
if ImageFile.Size > 25*1024*1024 {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Sua imagem deve ter no maximo 25MB",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
readFile, err := io.ReadAll(openfile)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "não foi possivel ler sua Imagem, tente novamente.",
|
||||
})
|
||||
}
|
||||
encode := base64.StdEncoding.EncodeToString(readFile)
|
||||
var id int
|
||||
err = db.QueryRow("SELECT id FROM players WHERE player=? LIMIT 1", player).Scan(&id)
|
||||
if err == nil {
|
||||
log.Println(id)
|
||||
return c.JSON(http.StatusConflict, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Esse usuario ja esta em uso, escolha outro e tente novamente.",
|
||||
})
|
||||
return jsonError(c, http.StatusConflict, "Esse usuario ja esta em uso, escolha outro e tente novamente.")
|
||||
}
|
||||
|
||||
row, err := db.Exec("INSERT INTO players (foto, player, password, nome, descrição) VALUES (?, ?, ?, ?, ?);", encode, player, string(passhash), "John Doe", playerlore)
|
||||
if err == nil {
|
||||
newID, _ := row.LastInsertId()
|
||||
|
||||
query := fmt.Sprintf("CREATE TABLE invPower_%s (id INT NOT NULL AUTO_INCREMENT, name_power VARCHAR(30) NOT NULL, desc_power LONGTEXT NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB;", player)
|
||||
_, err := db.Exec(query)
|
||||
if err != nil {
|
||||
db.Exec("DELETE FROM players WHERE id=?", int(newID))
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao criar o inventario de poderes do player: " + player,
|
||||
})
|
||||
}
|
||||
log.Printf("tabela invPower_%s foi criada.\n", player)
|
||||
|
||||
query = fmt.Sprintf(`CREATE TABLE inv_%s (id INT NOT NULL AUTO_INCREMENT, item_nome VARCHAR(30) NOT NULL , quantidade INT NOT NULL DEFAULT '1' , item_peso INT NOT NULL DEFAULT '1' , item_durabilit BOOLEAN NOT NULL DEFAULT FALSE ) ENGINE = InnoDB;`, player)
|
||||
newInv, err := db.Query(query)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao criar o inventario do player: " + player,
|
||||
})
|
||||
}
|
||||
newInv.Next()
|
||||
defer newInv.Close()
|
||||
log.Printf("tabela inv_%s foi criada.\n", player)
|
||||
|
||||
newCookie, err := sessionCookie(int(newID), player)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
}
|
||||
c.SetCookie(newCookie)
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: "sua conta foi criada com sucesso",
|
||||
})
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao criar sua conta, tente novamente")
|
||||
}
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Erro ao criar sua conta, tente novamente",
|
||||
})
|
||||
|
||||
newID, _ := row.LastInsertId()
|
||||
|
||||
query := fmt.Sprintf("CREATE TABLE invPower_%s (id INT NOT NULL AUTO_INCREMENT, name_power VARCHAR(30) NOT NULL, desc_power LONGTEXT NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB;", player)
|
||||
_, err = db.Exec(query)
|
||||
if err != nil {
|
||||
db.Exec("DELETE FROM players WHERE id=?", int(newID))
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao criar inventario de poderes do player: "+player)
|
||||
}
|
||||
|
||||
query = fmt.Sprintf(`CREATE TABLE inv_%s (id INT NOT NULL AUTO_INCREMENT, item_nome VARCHAR(30) NOT NULL , quantidade INT NOT NULL DEFAULT '1' , item_peso INT NOT NULL DEFAULT '1' , item_durabilit BOOLEAN NOT NULL DEFAULT FALSE ) ENGINE = InnoDB;`, player)
|
||||
newInv, err := db.Query(query)
|
||||
if err != nil {
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao criar o inventario do player: "+player)
|
||||
}
|
||||
newInv.Next()
|
||||
defer newInv.Close()
|
||||
|
||||
newCookie, err := sessionCookie(int(newID), player)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return jsonError(c, http.StatusInternalServerError, err.Error())
|
||||
}
|
||||
c.SetCookie(newCookie)
|
||||
|
||||
return jsonSuccess(c, "sua conta foi criada com sucesso")
|
||||
}
|
||||
|
||||
func login(c echo.Context) error {
|
||||
player := c.FormValue("player")
|
||||
password := c.FormValue("password")
|
||||
|
||||
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algum parametro esta faltando ou esta vaziu, tente novamente",
|
||||
})
|
||||
if anyEmpty(player, password) {
|
||||
return jsonError(c, http.StatusBadRequest, "algum parametro está faltando ou está vazio, tente novamente")
|
||||
}
|
||||
|
||||
var id int
|
||||
var DBpass string
|
||||
err := db.QueryRow("SELECT id, password FROM players WHERE player=? LIMIT 1", player).Scan(&id, &DBpass)
|
||||
|
||||
if err == nil {
|
||||
if bcrypt.CompareHashAndPassword([]byte(DBpass), []byte(password)) == nil {
|
||||
newCookie, err := sessionCookie(id, player)
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
c.SetCookie(newCookie)
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: "Login sucesso",
|
||||
})
|
||||
if err == nil && bcrypt.CompareHashAndPassword([]byte(DBpass), []byte(password)) == nil {
|
||||
newCookie, err := sessionCookie(id, player)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return jsonError(c, http.StatusInternalServerError, err.Error())
|
||||
}
|
||||
c.SetCookie(newCookie)
|
||||
return jsonSuccess(c, "Login sucesso")
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Usuario ou senha incorreto",
|
||||
})
|
||||
return jsonError(c, http.StatusUnauthorized, "Usuario ou senha incorreto")
|
||||
}
|
||||
|
||||
func logout(c echo.Context) error {
|
||||
_, err := requireSession(c)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
cookie, _ := c.Cookie(cookieName)
|
||||
sessionID := cookie.Value
|
||||
delCookie(c, sessionID)
|
||||
return jsonSuccess(c, "Você fez foi deslogado.")
|
||||
}
|
||||
|
||||
func online(c echo.Context) error {
|
||||
return jsonSuccess(c, "Api esta online")
|
||||
}
|
||||
|
||||
func badreq(c echo.Context) error {
|
||||
return jsonError(c, http.StatusBadRequest, "essa rota não foi preparada para requisições do tipo get.")
|
||||
}
|
||||
|
||||
func roll(c echo.Context) error {
|
||||
userSession, err := ValidSession(c)
|
||||
session, err := requireSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
roll, err := strconv.Atoi(c.FormValue("roll"))
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao rola seu dado, tente novamente",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, "algo deu errado ao rolar seu dado, tente novamente")
|
||||
}
|
||||
var dado int
|
||||
switch roll {
|
||||
case 6:
|
||||
dado = rand.Intn(roll) + 1
|
||||
case 10:
|
||||
dado = rand.Intn(roll) + 1
|
||||
case 20:
|
||||
dado = rand.Intn(roll) + 1
|
||||
case 40:
|
||||
dado = rand.Intn(roll) + 1
|
||||
case 50:
|
||||
dado = rand.Intn(roll) + 1
|
||||
case 100:
|
||||
dado = rand.Intn(roll) + 1
|
||||
default:
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você so pode rodar dados de 6, 10, 20, 40, 50 ou 100",
|
||||
})
|
||||
|
||||
allowed := map[int]bool{6: true, 10: true, 20: true, 40: true, 50: true, 100: true}
|
||||
if !allowed[roll] {
|
||||
return jsonError(c, http.StatusBadRequest, "você só pode rodar dados de 6, 10, 20, 40, 50 ou 100")
|
||||
}
|
||||
var value string = fmt.Sprintf("%s rolou 1d%v e o resultado é %v", userSession["playerName"], roll, dado)
|
||||
|
||||
dado := rand.Intn(roll) + 1
|
||||
value := fmt.Sprintf("%s rolou 1d%v e o resultado é %v", session["playerName"], roll, dado)
|
||||
|
||||
_, err = db.Exec("INSERT INTO roll_logs (id, log) VALUES (NULL, ?);", value)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "não foi possivel inserir o log do da rolagem no banco de dados",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "não foi possível inserir o log da rolagem no banco de dados")
|
||||
}
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
@@ -273,21 +162,16 @@ func roll_get(c echo.Context) error {
|
||||
row, err := db.Query("SELECT * FROM roll_logs ORDER BY id DESC LIMIT 5;")
|
||||
if err != nil {
|
||||
log.Println("Erro ao consultar tabela de rolagem.")
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao consultar tabela de rolagem",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao consultar tabela de rolagem")
|
||||
}
|
||||
var lista []logEntry
|
||||
defer row.Close()
|
||||
|
||||
var lista []logEntry
|
||||
for row.Next() {
|
||||
var id int
|
||||
var log string
|
||||
if err := row.Scan(&id, &log); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao montar lista de rolagem",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao montar lista de rolagem")
|
||||
}
|
||||
lista = append(lista, logEntry{ID: id, Log: log})
|
||||
}
|
||||
@@ -296,12 +180,10 @@ func roll_get(c echo.Context) error {
|
||||
return lista[i].ID < lista[j].ID
|
||||
})
|
||||
|
||||
if len(lista) <= 0 {
|
||||
return c.JSON(http.StatusNotFound, resp_json{
|
||||
Status: "NoDB",
|
||||
Message: "Ainda não exite historico de rolagem",
|
||||
})
|
||||
if len(lista) == 0 {
|
||||
return jsonError(c, http.StatusNotFound, "Ainda não existe histórico de rolagem")
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Logs: lista,
|
||||
@@ -309,114 +191,94 @@ func roll_get(c echo.Context) error {
|
||||
}
|
||||
|
||||
func player_data(c echo.Context) error {
|
||||
userSession, err := ValidSession(c)
|
||||
session, err := requireSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
var foto, playername, vida, descrição string
|
||||
var conhecimento, level, idade, vd, vdm, destresa, inteligencia, força, constituição, cárisma, inventario int64
|
||||
var altura float64
|
||||
err = db.QueryRow("SELECT foto, nome, conhecimento, level, idade, altura, vida, vida_maxima, destresa, inteligencia, força, constituição, cárisma, inventario, descrição FROM players WHERE id=? LIMIT 1;", userSession["user_id"]).Scan(&foto, &playername, &conhecimento, &level, &idade, &altura, &vd, &vdm, &destresa, &inteligencia, &força, &constituição, &cárisma, &inventario, &descrição)
|
||||
if err == nil {
|
||||
vida = fmt.Sprintf("%v/%v", vd, vdm)
|
||||
porcentagem := (float64(vd) / float64(vdm)) * 100
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Foto: foto,
|
||||
PlayerName: playername,
|
||||
Conhecimento: &conhecimento,
|
||||
Level: &level,
|
||||
Idade: &idade,
|
||||
Altura: &altura,
|
||||
Vida: vida,
|
||||
VidaPorcentagem: &porcentagem,
|
||||
Destresa: &destresa,
|
||||
Inteligencia: &inteligencia,
|
||||
Força: &força,
|
||||
Constituição: &constituição,
|
||||
Cárisma: &cárisma,
|
||||
Inventario: &inventario,
|
||||
Descrição: descrição,
|
||||
})
|
||||
}
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Algo deu errado ao carregar dados da sua ficha",
|
||||
})
|
||||
|
||||
var foto, nome, vida, descricao string
|
||||
var conhecimento, level, idade, vd, vdm, destreza, inteligencia, forca, constituicao, carisma, inventario int64
|
||||
var altura float64
|
||||
|
||||
err = db.QueryRow(`SELECT foto, nome, conhecimento, level, idade, altura, vida, vida_maxima,
|
||||
destresa, inteligencia, força, constituição, cárisma, inventario, descrição
|
||||
FROM players WHERE id=? LIMIT 1;`, session["user_id"]).
|
||||
Scan(&foto, &nome, &conhecimento, &level, &idade, &altura, &vd, &vdm,
|
||||
&destreza, &inteligencia, &forca, &constituicao, &carisma, &inventario, &descricao)
|
||||
|
||||
if err != nil {
|
||||
return jsonError(c, http.StatusBadRequest, "Algo deu errado ao carregar dados da sua ficha")
|
||||
}
|
||||
|
||||
vida = fmt.Sprintf("%v/%v", vd, vdm)
|
||||
porcentagem := (float64(vd) / float64(vdm)) * 100
|
||||
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Foto: foto,
|
||||
PlayerName: nome,
|
||||
Conhecimento: &conhecimento,
|
||||
Level: &level,
|
||||
Idade: &idade,
|
||||
Altura: &altura,
|
||||
Vida: vida,
|
||||
VidaPorcentagem: &porcentagem,
|
||||
Destresa: &destreza,
|
||||
Inteligencia: &inteligencia,
|
||||
Força: &forca,
|
||||
Constituição: &constituicao,
|
||||
Cárisma: &carisma,
|
||||
Inventario: &inventario,
|
||||
Descrição: descricao,
|
||||
})
|
||||
}
|
||||
|
||||
func player_update(c echo.Context) error {
|
||||
userSession, err := ValidSession(c)
|
||||
session, err := requireSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
updown := c.Param("updown")
|
||||
atb := c.Param("atb")
|
||||
var sinal string
|
||||
|
||||
switch updown {
|
||||
case "up":
|
||||
sinal = "+"
|
||||
case "down":
|
||||
sinal = "-"
|
||||
default:
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você passou um parametro invalido em updown, use up ou down.",
|
||||
})
|
||||
sinal := map[string]string{"up": "+", "down": "-"}[updown]
|
||||
if sinal == "" {
|
||||
return jsonError(c, http.StatusBadRequest, "você passou um parametro invalido em updown, use up ou down.")
|
||||
}
|
||||
|
||||
var updateList = map[string]string{
|
||||
"vida": fmt.Sprintf("UPDATE players SET vida = vida %s 1 WHERE id=?;", sinal),
|
||||
"level": fmt.Sprintf("UPDATE players SET level = level %s 1 WHERE id=?;", sinal),
|
||||
"idade": fmt.Sprintf("UPDATE players SET idade = idade %s 1 WHERE id=?;", sinal),
|
||||
"conhecimento": fmt.Sprintf("UPDATE players SET conhecimento = conhecimento %s 1 WHERE id=?;", sinal),
|
||||
"força": fmt.Sprintf("UPDATE players SET força = força %s 1 WHERE id=?;", sinal),
|
||||
"destresa": fmt.Sprintf("UPDATE players SET destresa = destresa %s 1 WHERE id=?;", sinal),
|
||||
"constituição": fmt.Sprintf("UPDATE players SET constituição = constituição %s 1 WHERE id=?;", sinal),
|
||||
"inteligencia": fmt.Sprintf("UPDATE players SET inteligencia = inteligencia %s 1 WHERE id=?;", sinal),
|
||||
"cárisma": fmt.Sprintf("UPDATE players SET cárisma = cárisma %s 1 WHERE id=?;", sinal),
|
||||
updateList := map[string]string{
|
||||
"vida": "vida",
|
||||
"level": "level",
|
||||
"idade": "idade",
|
||||
"conhecimento": "conhecimento",
|
||||
"força": "força",
|
||||
"destresa": "destresa",
|
||||
"constituição": "constituição",
|
||||
"inteligencia": "inteligencia",
|
||||
"cárisma": "cárisma",
|
||||
}
|
||||
|
||||
query, ok := updateList[atb]
|
||||
field, ok := updateList[atb]
|
||||
if !ok {
|
||||
return c.JSON(http.StatusBadRequest, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você passou um parametro invalido, tente novamente com um parametro correto",
|
||||
})
|
||||
}
|
||||
_, err = db.Exec(query, userSession["user_id"])
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado a atualizar sua ficha",
|
||||
})
|
||||
return jsonError(c, http.StatusBadRequest, "você passou um parametro invalido, tente novamente com um parametro correto")
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: sinal + "1 em " + atb,
|
||||
})
|
||||
query := fmt.Sprintf("UPDATE players SET %s = %s %s 1 WHERE id=?;", field, field, sinal)
|
||||
if err := updateField(query, session["user_id"]); err != nil {
|
||||
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao atualizar sua ficha")
|
||||
}
|
||||
|
||||
return jsonSuccess(c, sinal+"1 em "+atb)
|
||||
}
|
||||
|
||||
func player_updateInputs(c echo.Context) error {
|
||||
userSession, err := ValidSession(c)
|
||||
session, err := requireSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
var lista []string
|
||||
|
||||
vida := c.FormValue("vida")
|
||||
nome := c.FormValue("nome")
|
||||
altura := c.FormValue("altura")
|
||||
@@ -424,156 +286,99 @@ func player_updateInputs(c echo.Context) error {
|
||||
lore := c.FormValue("lore")
|
||||
|
||||
if vida != "" {
|
||||
_, err = db.Exec("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, userSession["user_id"])
|
||||
err := updateField("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, session["user_id"])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao alterar sua vida.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua vida.")
|
||||
}
|
||||
lista = append(lista, "vida")
|
||||
}
|
||||
|
||||
if nome != "" {
|
||||
_, err = db.Exec("UPDATE players SET nome=? WHERE id=?;", nome, userSession["user_id"])
|
||||
err := updateField("UPDATE players SET nome=? WHERE id=?;", nome, session["user_id"])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao alterar seu nome.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao alterar seu nome.")
|
||||
}
|
||||
lista = append(lista, "nome")
|
||||
}
|
||||
|
||||
if altura != "" {
|
||||
_, err = db.Exec("UPDATE players SET altura=? WHERE id=?;", altura, userSession["user_id"])
|
||||
err := updateField("UPDATE players SET altura=? WHERE id=?;", altura, session["user_id"])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao alterar sua altura.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua altura.")
|
||||
}
|
||||
lista = append(lista, "altura")
|
||||
}
|
||||
|
||||
if inv != "" {
|
||||
row, err := db.Query(fmt.Sprintf("SELECT id, item_peso FROM inv_%s ORDER BY id DESC;", userSession["playerName"]))
|
||||
row, err := db.Query(fmt.Sprintf("SELECT item_peso FROM inv_%s;", session["playerName"]))
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Println("Erro ao consultar items do inventario.")
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Erro ao consultar items do inventario.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
||||
}
|
||||
var peso_total int = 0
|
||||
|
||||
defer row.Close()
|
||||
var total int
|
||||
for row.Next() {
|
||||
var id int
|
||||
var peso int
|
||||
if err := row.Scan(&id, &peso); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao inventario",
|
||||
})
|
||||
if err := row.Scan(&peso); err != nil {
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao ler itens do inventário")
|
||||
}
|
||||
peso_total = peso_total + peso
|
||||
total += peso
|
||||
}
|
||||
valorInv, _ := strconv.Atoi(inv)
|
||||
if peso_total > valorInv {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você não pode ter um inventario com menos capacidade do que esta carregando.",
|
||||
})
|
||||
val, _ := strconv.Atoi(inv)
|
||||
if total > val {
|
||||
return jsonError(c, http.StatusUnauthorized, "você não pode ter um inventário com menos capacidade do que está carregando")
|
||||
}
|
||||
|
||||
_, err = db.Exec("UPDATE players SET inventario=? WHERE id=?;", inv, userSession["user_id"])
|
||||
err = updateField("UPDATE players SET inventario=? WHERE id=?;", inv, session["user_id"])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao alterar o tamanho do seu inventario.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao alterar tamanho do inventário")
|
||||
}
|
||||
lista = append(lista, "inventario")
|
||||
}
|
||||
|
||||
if lore != "" {
|
||||
_, err = db.Exec("UPDATE players SET descrição=? WHERE id=?;", lore, userSession["user_id"])
|
||||
err := updateField("UPDATE players SET descrição=? WHERE id=?;", lore, session["user_id"])
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao alterar a sua historia.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "erro ao alterar a sua história")
|
||||
}
|
||||
lista = append(lista, "lore")
|
||||
}
|
||||
|
||||
if len(lista) <= 0 {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: "você é obrigado a alguma informação seu cabaço.",
|
||||
})
|
||||
if len(lista) == 0 {
|
||||
return jsonError(c, http.StatusUnauthorized, "você é obrigado a alterar alguma informação")
|
||||
}
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
Message: fmt.Sprintf("você mudou as seguintes informaçôes: %s", lista),
|
||||
})
|
||||
|
||||
return jsonSuccess(c, fmt.Sprintf("você mudou as seguintes informações: %s", lista))
|
||||
}
|
||||
|
||||
func inv_get(c echo.Context) error {
|
||||
userSession, err := ValidSession(c)
|
||||
session, err := requireSession(c)
|
||||
if err != nil {
|
||||
return c.JSON(http.StatusUnauthorized, resp_json{
|
||||
Status: "Error",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
row, err := db.Query(fmt.Sprintf("SELECT id, item_nome, quantidade, item_peso FROM inv_%s ORDER BY id DESC;", userSession["playerName"]))
|
||||
row, err := db.Query(fmt.Sprintf("SELECT id, item_nome, quantidade, item_peso FROM inv_%s ORDER BY id DESC;", session["playerName"]))
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Println("Erro ao consultar items do inventario.")
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "Erro ao consultar items do inventario.",
|
||||
})
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
||||
}
|
||||
var peso_total int = 0
|
||||
defer row.Close()
|
||||
|
||||
var total int
|
||||
var lista []plyInv
|
||||
|
||||
for row.Next() {
|
||||
var id int
|
||||
var nome string
|
||||
var quantidade int
|
||||
var peso int
|
||||
if err := row.Scan(&id, &nome, &quantidade, &peso); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, resp_json{
|
||||
Status: "Error",
|
||||
Message: "algo deu errado ao inventario",
|
||||
})
|
||||
var item plyInv
|
||||
if err := row.Scan(&item.ID, &item.ItemName, &item.ItemQuantidade, &item.ItemPeso); err != nil {
|
||||
return jsonError(c, http.StatusInternalServerError, "Erro ao ler item do inventário")
|
||||
}
|
||||
lista = append(lista, plyInv{ID: id, ItemName: nome, ItemQuantidade: quantidade, ItemPeso: peso})
|
||||
peso_total = peso_total + peso
|
||||
lista = append(lista, item)
|
||||
total += item.ItemPeso
|
||||
}
|
||||
|
||||
sort.Slice(lista, func(i, j int) bool {
|
||||
return lista[i].ID < lista[j].ID
|
||||
})
|
||||
|
||||
if len(lista) <= 0 {
|
||||
return c.JSON(http.StatusNotFound, resp_json{
|
||||
Status: "NoDB",
|
||||
Message: "o Inventario ainda esta vazio",
|
||||
})
|
||||
if len(lista) == 0 {
|
||||
return jsonError(c, http.StatusNotFound, "O inventário ainda está vazio")
|
||||
}
|
||||
|
||||
return c.JSON(http.StatusOK, resp_json{
|
||||
Status: "Success",
|
||||
InvPeso: peso_total,
|
||||
InvPeso: total,
|
||||
InvItems: lista,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user