knowyt/server/src/application/saveQuote.go

61 lines
1.3 KiB
Go
Raw Normal View History

2021-10-15 21:07:41 +00:00
package application
import (
"fmt"
2021-10-16 18:14:58 +00:00
"github.com/google/uuid"
2021-10-15 21:07:41 +00:00
"net/http"
2021-10-16 14:57:28 +00:00
"path"
2021-10-16 18:14:58 +00:00
"sirlab.de/go/knyt/game"
2021-10-15 21:07:41 +00:00
"sirlab.de/go/knyt/user"
)
func (app *Application) SaveQuote(usr *user.User, w http.ResponseWriter, r *http.Request) {
gameRef := r.URL.Query().Get("g")
gm, err := app.GetGameById(gameRef)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "game not found")
return
}
2021-10-16 19:47:45 +00:00
if usr.GetGameId() != gameRef && !usr.IsGamemaster() {
2021-10-15 21:07:41 +00:00
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "forbidden")
return
}
quoteText := r.URL.Query().Get("quote")
2021-10-16 18:14:58 +00:00
quoteId := r.URL.Query().Get("id")
if quoteId == ":new:" {
quoteNewUuid := uuid.NewString()
err = gm.CreateQuote(
app.getQuoteFileNameFromId(gm, quoteNewUuid),
usr.GetId(),
quoteNewUuid,
quoteText,
)
} else {
err = gm.SaveQuote(
app.getQuoteFileNameFromId(gm, quoteId),
usr.GetId(),
quoteId,
quoteText,
)
}
2021-10-16 14:57:28 +00:00
2021-10-16 18:14:58 +00:00
if err != nil {
fmt.Printf("%s", err)
2021-10-15 21:07:41 +00:00
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "forbidden")
return
}
2021-10-16 14:57:28 +00:00
fmt.Fprintf(w, "ok")
2021-10-15 21:07:41 +00:00
}
2021-10-16 18:14:58 +00:00
func (app *Application) getQuoteFileNameFromId(gm *game.Game, id string) string {
gameDirName := path.Join(app.config.DataDir, "games", gm.GetId())
quoteFileNameShort := id + ".json"
return path.Join(gameDirName, "quotes", quoteFileNameShort)
}