645 lines
21 KiB
Go
645 lines
21 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"math/rand"
|
|
"net/http"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func registrar(c echo.Context) error {
|
|
player := c.FormValue("player")
|
|
password := c.FormValue("password")
|
|
confpass := c.FormValue("confirmpassword")
|
|
playerlore := c.FormValue("playerlore")
|
|
|
|
if !regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(player) {
|
|
return jsonError(c, http.StatusBadRequest, "você usou caracteres proibidos no seu nome")
|
|
}
|
|
|
|
if anyEmpty(player, password, confpass, playerlore) {
|
|
return jsonError(c, http.StatusBadRequest, "algum parametro esta faltando ou esta vazio, tente novamente")
|
|
}
|
|
|
|
if password != confpass {
|
|
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 jsonError(c, http.StatusInternalServerError, "Erro ao criar hash de senha do usuario: "+player)
|
|
}
|
|
|
|
imageFile, err := c.FormFile("PlayerImage")
|
|
if err != nil {
|
|
return jsonError(c, http.StatusBadRequest, "Arquivo de Imagem não foi enviado, adcione uma imagem.")
|
|
}
|
|
|
|
encode, err := readAndValidateImage(imageFile)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusBadRequest, err.Error())
|
|
}
|
|
|
|
var id int
|
|
err = db.QueryRow("SELECT id FROM players WHERE player=? LIMIT 1", player).Scan(&id)
|
|
if err == nil {
|
|
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 {
|
|
log.Println(err)
|
|
return jsonError(c, http.StatusInternalServerError, "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, PRIMARY KEY (`id`)) 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 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 && 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 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 {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
roll, err := strconv.Atoi(c.FormValue("roll"))
|
|
if err != nil {
|
|
return jsonError(c, http.StatusBadRequest, "algo deu errado ao rolar seu dado, tente novamente")
|
|
}
|
|
|
|
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")
|
|
}
|
|
|
|
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 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",
|
|
Message: value,
|
|
})
|
|
}
|
|
|
|
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 jsonError(c, http.StatusInternalServerError, "algo deu errado ao consultar tabela de rolagem")
|
|
}
|
|
defer row.Close()
|
|
|
|
var lista []logEntry
|
|
for row.Next() {
|
|
var id int
|
|
var log string
|
|
if err := row.Scan(&id, &log); err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao montar lista de rolagem")
|
|
}
|
|
lista = append(lista, logEntry{ID: id, Log: log})
|
|
}
|
|
|
|
sort.Slice(lista, func(i, j int) bool {
|
|
return lista[i].ID < lista[j].ID
|
|
})
|
|
|
|
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,
|
|
})
|
|
}
|
|
|
|
func player_info(c echo.Context) error {
|
|
id := c.Param("id")
|
|
|
|
if anyEmpty(id) {
|
|
return jsonError(c, http.StatusBadRequest, "você precisa passar a id do usuario.")
|
|
}
|
|
|
|
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;`, 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 informações do player")
|
|
}
|
|
|
|
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_data(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
var foto, nome, vida, descricao string
|
|
var id, conhecimento, level, idade, vd, vdm, destreza, inteligencia, forca, constituicao, carisma, inventario int64
|
|
var altura float64
|
|
|
|
err = db.QueryRow(`SELECT id, 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(&id, &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",
|
|
PlayerID: &id,
|
|
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 {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
updown := c.Param("updown")
|
|
atb := c.Param("atb")
|
|
|
|
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.")
|
|
}
|
|
|
|
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",
|
|
}
|
|
|
|
field, ok := updateList[atb]
|
|
if !ok {
|
|
return jsonError(c, http.StatusBadRequest, "você passou um parametro invalido, tente novamente com um parametro correto")
|
|
}
|
|
if atb != "vida" {
|
|
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)
|
|
}
|
|
var life, life_max int
|
|
err = db.QueryRow("SELECT vida, vida_maxima FROM players WHERE id=?", session["user_id"]).Scan(&life, &life_max)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao atualizar sua ficha")
|
|
}
|
|
|
|
if life <= 0 && sinal != "+" {
|
|
return jsonError(c, http.StatusBadRequest, "sua vida não pode ficar a baixo de zero")
|
|
}
|
|
if life >= life_max && sinal != "-" {
|
|
return jsonError(c, http.StatusBadRequest, fmt.Sprintf("sua vida maxima é %v, você não pode estar com a vida a cima da maxima", life_max))
|
|
}
|
|
|
|
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 {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
var lista []string
|
|
vida := c.FormValue("vida")
|
|
nome := c.FormValue("nome")
|
|
altura := c.FormValue("altura")
|
|
inv := c.FormValue("inventario")
|
|
lore := c.FormValue("lore")
|
|
|
|
if vida != "" {
|
|
a, _ := strconv.Atoi(vida)
|
|
if a < 1 {
|
|
return jsonError(c, http.StatusUnauthorized, "o seu merda, sua viada não pode ser 0 ou inferior.")
|
|
}
|
|
|
|
err := updateField("UPDATE players SET vida=?, vida_maxima=? WHERE id=?;", vida, vida, session["user_id"])
|
|
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua vida.")
|
|
}
|
|
lista = append(lista, "vida")
|
|
}
|
|
|
|
if nome != "" {
|
|
err := updateField("UPDATE players SET nome=? WHERE id=?;", nome, session["user_id"])
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar seu nome.")
|
|
}
|
|
lista = append(lista, "nome")
|
|
}
|
|
if altura != "" {
|
|
err := updateField("UPDATE players SET altura=? WHERE id=?;", altura, session["user_id"])
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar sua altura.")
|
|
}
|
|
lista = append(lista, "altura")
|
|
}
|
|
if inv != "" {
|
|
row, err := db.Query(fmt.Sprintf("SELECT item_peso FROM inv_%s;", session["playerName"]))
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
|
}
|
|
defer row.Close()
|
|
var total int
|
|
for row.Next() {
|
|
var peso int
|
|
if err := row.Scan(&peso); err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao ler itens do inventário")
|
|
}
|
|
total += peso
|
|
}
|
|
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 = updateField("UPDATE players SET inventario=? WHERE id=?;", inv, session["user_id"])
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar tamanho do inventário")
|
|
}
|
|
lista = append(lista, "inventario")
|
|
}
|
|
if lore != "" {
|
|
err := updateField("UPDATE players SET descrição=? WHERE id=?;", lore, session["user_id"])
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao alterar a sua história")
|
|
}
|
|
lista = append(lista, "lore")
|
|
}
|
|
|
|
if len(lista) == 0 {
|
|
return jsonError(c, http.StatusUnauthorized, "você é obrigado a alterar alguma informação")
|
|
}
|
|
|
|
return jsonSuccess(c, fmt.Sprintf("você mudou as seguintes informações: %s", lista))
|
|
}
|
|
|
|
func inv_get(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
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 {
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
|
}
|
|
defer row.Close()
|
|
|
|
var total int
|
|
var lista []plyInv
|
|
for row.Next() {
|
|
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, item)
|
|
total += item.ItemPeso
|
|
}
|
|
|
|
sort.Slice(lista, func(i, j int) bool {
|
|
return lista[i].ID < lista[j].ID
|
|
})
|
|
|
|
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: total,
|
|
InvItems: lista,
|
|
})
|
|
}
|
|
|
|
func inv_del(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "você precisa estar logado para apagar um item")
|
|
}
|
|
itemID := c.Param("id")
|
|
err = updateField(fmt.Sprintf("DELETE FROM inv_%s WHERE id=?;", session["playerName"]), itemID)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao deletar item.")
|
|
}
|
|
|
|
return jsonSuccess(c, "você deletou um item")
|
|
}
|
|
|
|
func inv_use(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "você precisa estar logado para usar algum item")
|
|
}
|
|
itemID := c.Param("id")
|
|
var durabilidade bool
|
|
var quantidade, menos int
|
|
var item_name string
|
|
err = db.QueryRow(fmt.Sprintf("SELECT item_durabilit, quantidade, item_nome FROM inv_%s WHERE id=?;", session["playerName"]), itemID).Scan(&durabilidade, &quantidade, &item_name)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "item não foi encontrado")
|
|
}
|
|
if durabilidade == false {
|
|
return jsonSuccess(c, "você usou um item sem durabilidade")
|
|
}
|
|
menos = quantidade - 1
|
|
if menos >= 1 {
|
|
err = updateField(fmt.Sprintf("UPDATE inv_%s SET quantidade=? WHERE id=?;", session["playerName"]), menos, itemID)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao usar seu item")
|
|
}
|
|
return jsonSuccess(c, fmt.Sprintf("você uso 1 %s", item_name))
|
|
}
|
|
err = updateField(fmt.Sprintf("DELETE FROM inv_%s WHERE id=?", session["playerName"]), itemID)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "item não foi apagado, algo deu errado")
|
|
}
|
|
return jsonSuccess(c, fmt.Sprintf("você gastou seu ultimo %s", item_name))
|
|
}
|
|
|
|
func inv_add(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "Você precisa estar logado para adicionar itens ao inventário.")
|
|
}
|
|
|
|
nome := c.FormValue("item_name")
|
|
durabiliteStr := c.FormValue("durabilite")
|
|
peso := c.FormValue("peso")
|
|
quantidade := c.FormValue("quantidade")
|
|
|
|
if anyEmpty(nome, durabiliteStr, peso, quantidade) {
|
|
return jsonError(c, http.StatusBadRequest, "Algum parâmetro está faltando ou está vazio. Tente novamente.")
|
|
}
|
|
|
|
durabilite, err := strconv.ParseBool(durabiliteStr)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusBadRequest, "A durabilidade deve ser 'true' ou 'false'.")
|
|
}
|
|
|
|
row, err := db.Query(fmt.Sprintf("SELECT item_peso FROM inv_%s;", session["playerName"]))
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar itens do inventário.")
|
|
}
|
|
defer row.Close()
|
|
|
|
var total, atualpeso int
|
|
for row.Next() {
|
|
var itempeso int
|
|
if err := row.Scan(&itempeso); err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao ler itens do inventário.")
|
|
}
|
|
total += itempeso
|
|
}
|
|
|
|
err = db.QueryRow("SELECT inventario FROM players WHERE id=?;", session["user_id"]).Scan(&atualpeso)
|
|
ps, _ := strconv.Atoi(peso)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return jsonError(c, http.StatusInternalServerError, "Algo deu errado ao verificar o tamanho do seu inventário.")
|
|
}
|
|
|
|
total += ps
|
|
if total > atualpeso {
|
|
return jsonError(c, http.StatusInternalServerError, fmt.Sprintf("%s é muito pesado para colocar no seu inventário.", nome))
|
|
}
|
|
|
|
_, err = db.Exec(fmt.Sprintf("INSERT INTO inv_%s (item_nome, quantidade, item_peso, item_durabilit) VALUE (?, ?, ?, ?);", session["playerName"]), nome, quantidade, peso, durabilite)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return jsonError(c, http.StatusInternalServerError, fmt.Sprintf("Algo deu errado ao adicionar %s ao seu inventário.", nome))
|
|
}
|
|
|
|
return jsonSuccess(c, fmt.Sprintf("%s %ss foram colocados no seu inventário.", quantidade, nome))
|
|
}
|
|
func inv_ph(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "Você precisa estar logado para adicionar itens ao inventário.")
|
|
}
|
|
|
|
row, err := db.Query(fmt.Sprintf("SELECT * FROM invPower_%s ORDER BY id DESC;", session["playerName"]))
|
|
if err != nil {
|
|
log.Println("Erro ao consultar sua lista de habilidade.")
|
|
return jsonError(c, http.StatusInternalServerError, "Erro ao consultar sua lista de habilidade.")
|
|
}
|
|
defer row.Close()
|
|
|
|
var lista []plyPwr
|
|
for row.Next() {
|
|
var id int
|
|
var nome, desc string
|
|
if err := row.Scan(&id, &nome, &desc); err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "algo deu errado ao montar lista de rolagem")
|
|
}
|
|
lista = append(lista, plyPwr{ID: id, Name: nome, Desc: desc})
|
|
}
|
|
|
|
sort.Slice(lista, func(i, j int) bool {
|
|
return lista[i].ID < lista[j].ID
|
|
})
|
|
|
|
if len(lista) == 0 {
|
|
return jsonError(c, http.StatusNotFound, "você ainda não tem habilidades")
|
|
}
|
|
return c.JSON(http.StatusOK, resp_json{
|
|
Status: "Success",
|
|
InvPws: lista,
|
|
})
|
|
}
|
|
|
|
func inv_phAdd(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "Você precisa estar logado para adicionar itens ao inventário.")
|
|
}
|
|
|
|
nome := c.FormValue("nameph")
|
|
desc := c.FormValue("descph")
|
|
|
|
if anyEmpty(nome, desc) {
|
|
return jsonError(c, http.StatusBadRequest, "Algum parâmetro está faltando ou está vazio. Tente novamente.")
|
|
}
|
|
|
|
_, err = db.Exec(fmt.Sprintf("INSERT INTO invPower_%s (name_power, desc_power) VALUES (?, ?)", session["playerName"]), nome, desc)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return jsonError(c, http.StatusInternalServerError, fmt.Sprintf("erro ao adicionar %s a sua lista", nome))
|
|
}
|
|
return jsonSuccess(c, fmt.Sprintf("%s foi adicionado a sua lista", nome))
|
|
}
|
|
|
|
func inv_phDel(c echo.Context) error {
|
|
session, err := requireSession(c)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if session["playerName"] == "" {
|
|
return jsonError(c, http.StatusUnauthorized, "você precisa estar logado para apagar uma habilidade")
|
|
}
|
|
itemID := c.Param("id")
|
|
err = updateField(fmt.Sprintf("DELETE FROM invPower_%s WHERE id=?;", session["playerName"]), itemID)
|
|
if err != nil {
|
|
return jsonError(c, http.StatusInternalServerError, "erro ao deletar habilidade.")
|
|
}
|
|
|
|
return jsonSuccess(c, "você deletou uma habilidade")
|
|
}
|