Added separate endpoints to handle eggs (get, update and delete)

pull/13/head
gamray 2024-05-12 22:37:43 +02:00
parent 8439519d8e
commit 4567108da8
5 changed files with 225 additions and 10 deletions

1
.gitignore vendored
View File

@ -7,6 +7,7 @@ secret.key
# local testing # local testing
/.data/ /.data/
docker-compose.yml
# Jetbrains IDEs # Jetbrains IDEs
/.idea/ /.idea/

View File

@ -54,6 +54,9 @@ func Init(mux *http.ServeMux) error {
mux.HandleFunc("GET /savedata/delete", handleSaveData) // TODO use deleteSystemSave mux.HandleFunc("GET /savedata/delete", handleSaveData) // TODO use deleteSystemSave
mux.HandleFunc("POST /savedata/clear", handleSaveData) // TODO use clearSessionData mux.HandleFunc("POST /savedata/clear", handleSaveData) // TODO use clearSessionData
mux.HandleFunc("GET /savedata/newclear", handleNewClear) mux.HandleFunc("GET /savedata/newclear", handleNewClear)
mux.HandleFunc("GET /savedata/eggs", handleRetrieveEggs)
mux.HandleFunc("POST /savedata/eggs", handleUpdateEggs)
mux.HandleFunc("POST /savedata/deleteeggs", handleDeleteEgg)
// new session // new session
mux.HandleFunc("POST /savedata/updateall", handleUpdateAll) mux.HandleFunc("POST /savedata/updateall", handleUpdateAll)

View File

@ -146,6 +146,7 @@ func handleGameClassicSessionCount(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strconv.Itoa(classicSessionCount))) _, _ = w.Write([]byte(strconv.Itoa(classicSessionCount)))
} }
// savedata
func handleGetSaveData(w http.ResponseWriter, r *http.Request) { func handleGetSaveData(w http.ResponseWriter, r *http.Request) {
token, uuid, err := tokenAndUuidFromRequest(r) token, uuid, err := tokenAndUuidFromRequest(r)
if err != nil { if err != nil {
@ -609,6 +610,75 @@ func handleNewClear(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, r, newClear) jsonResponse(w, r, newClear)
} }
func handleRetrieveEggs(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
eggs, err := db.RetrieveAccountEggs(uuid)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
jsonResponse(w, r, eggs)
w.Header().Set("Content-Type", "application/json")
}
func handleUpdateEggs(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var newEggsInfo []defs.EggData
err = json.NewDecoder(r.Body).Decode(&newEggsInfo)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
err = db.UpdateAccountEggs(uuid, newEggsInfo)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type DeleteEggId struct {
Id int `json:"id"`
}
func handleDeleteEgg(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var eggsId []DeleteEggId
err = json.NewDecoder(r.Body).Decode(&eggsId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
for _, egg := range eggsId {
err = db.RemoveAccountEgg(uuid, egg.Id)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
}
w.WriteHeader(http.StatusOK)
}
// daily // daily
func handleDailySeed(w http.ResponseWriter, r *http.Request) { func handleDailySeed(w http.ResponseWriter, r *http.Request) {

104
db/db.go
View File

@ -145,30 +145,114 @@ func Init(username, password, protocol, address, database string) error {
func setupDb(tx *sql.Tx) error { func setupDb(tx *sql.Tx) error {
queries := []string{ queries := []string{
`CREATE TABLE IF NOT EXISTS accounts (uuid BINARY(16) NOT NULL PRIMARY KEY, username VARCHAR(16) UNIQUE NOT NULL, hash BINARY(32) NOT NULL, salt BINARY(16) NOT NULL, registered TIMESTAMP NOT NULL, lastLoggedIn TIMESTAMP DEFAULT NULL, lastActivity TIMESTAMP DEFAULT NULL, banned TINYINT(1) NOT NULL DEFAULT 0, trainerId SMALLINT(5) UNSIGNED DEFAULT 0, secretId SMALLINT(5) UNSIGNED DEFAULT 0)`, `CREATE TABLE IF NOT EXISTS accounts (
uuid BINARY(16) NOT NULL PRIMARY KEY,
username VARCHAR(16) UNIQUE NOT NULL,
hash BINARY(32) NOT NULL,
salt BINARY(16) NOT NULL,
registered TIMESTAMP NOT NULL,
lastLoggedIn TIMESTAMP DEFAULT NULL,
lastActivity TIMESTAMP DEFAULT NULL,
banned TINYINT(1) NOT NULL DEFAULT 0,
trainerId SMALLINT(5) UNSIGNED DEFAULT 0,
secretId SMALLINT(5) UNSIGNED DEFAULT 0)`,
`CREATE INDEX IF NOT EXISTS accountsByActivity ON accounts (lastActivity)`, `CREATE INDEX IF NOT EXISTS accountsByActivity ON accounts (lastActivity)`,
`CREATE TABLE IF NOT EXISTS sessions (token BINARY(32) NOT NULL PRIMARY KEY, uuid BINARY(16) NOT NULL, active TINYINT(1) NOT NULL DEFAULT 0, expire TIMESTAMP DEFAULT NULL, CONSTRAINT sessions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`, `CREATE TABLE IF NOT EXISTS sessions (
token BINARY(32) NOT NULL PRIMARY KEY,
uuid BINARY(16) NOT NULL,
active TINYINT(1) NOT NULL DEFAULT 0,
expire TIMESTAMP DEFAULT NULL,
CONSTRAINT sessions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS sessionsByUuid ON sessions (uuid)`, `CREATE INDEX IF NOT EXISTS sessionsByUuid ON sessions (uuid)`,
`CREATE TABLE IF NOT EXISTS accountStats (uuid BINARY(16) NOT NULL PRIMARY KEY, playTime INT(11) NOT NULL DEFAULT 0, battles INT(11) NOT NULL DEFAULT 0, classicSessionsPlayed INT(11) NOT NULL DEFAULT 0, sessionsWon INT(11) NOT NULL DEFAULT 0, highestEndlessWave INT(11) NOT NULL DEFAULT 0, highestLevel INT(11) NOT NULL DEFAULT 0, pokemonSeen INT(11) NOT NULL DEFAULT 0, pokemonDefeated INT(11) NOT NULL DEFAULT 0, pokemonCaught INT(11) NOT NULL DEFAULT 0, pokemonHatched INT(11) NOT NULL DEFAULT 0, eggsPulled INT(11) NOT NULL DEFAULT 0, regularVouchers INT(11) NOT NULL DEFAULT 0, plusVouchers INT(11) NOT NULL DEFAULT 0, premiumVouchers INT(11) NOT NULL DEFAULT 0, goldenVouchers INT(11) NOT NULL DEFAULT 0, CONSTRAINT accountStats_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`, `CREATE TABLE IF NOT EXISTS accountStats (
uuid BINARY(16) NOT NULL PRIMARY KEY,
playTime INT(11) NOT NULL DEFAULT 0,
battles INT(11) NOT NULL DEFAULT 0,
classicSessionsPlayed INT(11) NOT NULL DEFAULT 0,
sessionsWon INT(11) NOT NULL DEFAULT 0,
highestEndlessWave INT(11) NOT NULL DEFAULT 0,
highestLevel INT(11) NOT NULL DEFAULT 0,
pokemonSeen INT(11) NOT NULL DEFAULT 0,
pokemonDefeated INT(11) NOT NULL DEFAULT 0,
pokemonCaught INT(11) NOT NULL DEFAULT 0,
pokemonHatched INT(11) NOT NULL DEFAULT 0,
eggsPulled INT(11) NOT NULL DEFAULT 0,
regularVouchers INT(11) NOT NULL DEFAULT 0,
plusVouchers INT(11) NOT NULL DEFAULT 0,
premiumVouchers INT(11) NOT NULL DEFAULT 0,
goldenVouchers INT(11) NOT NULL DEFAULT 0,
CONSTRAINT accountStats_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE)`,
`CREATE TABLE IF NOT EXISTS accountCompensations (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid BINARY(16) NOT NULL, voucherType INT(11) NOT NULL, count INT(11) NOT NULL DEFAULT 1, claimed BIT(1) NOT NULL DEFAULT b'0', CONSTRAINT accountCompensations_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`, `CREATE TABLE IF NOT EXISTS accountCompensations (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
uuid BINARY(16) NOT NULL,
voucherType INT(11) NOT NULL,
count INT(11) NOT NULL DEFAULT 1,
claimed BIT(1) NOT NULL DEFAULT b'0',
CONSTRAINT accountCompensations_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS accountCompensationsByUuid ON accountCompensations (uuid)`, `CREATE INDEX IF NOT EXISTS accountCompensationsByUuid ON accountCompensations (uuid)`,
`CREATE TABLE IF NOT EXISTS dailyRuns (date DATE NOT NULL PRIMARY KEY, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)`, `CREATE TABLE IF NOT EXISTS dailyRuns (
date DATE NOT NULL PRIMARY KEY,
seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)`,
`CREATE INDEX IF NOT EXISTS dailyRunsByDateAndSeed ON dailyRuns (date, seed)`, `CREATE INDEX IF NOT EXISTS dailyRunsByDateAndSeed ON dailyRuns (date, seed)`,
`CREATE TABLE IF NOT EXISTS dailyRunCompletions (uuid BINARY(16) NOT NULL, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, mode INT(11) NOT NULL DEFAULT 0, score INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, seed), CONSTRAINT dailyRunCompletions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`, `CREATE TABLE IF NOT EXISTS dailyRunCompletions (
uuid BINARY(16) NOT NULL,
seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
mode INT(11) NOT NULL DEFAULT 0,
score INT(11) NOT NULL DEFAULT 0,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (uuid, seed),
CONSTRAINT dailyRunCompletions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS dailyRunCompletionsByUuidAndSeed ON dailyRunCompletions (uuid, seed)`, `CREATE INDEX IF NOT EXISTS dailyRunCompletionsByUuidAndSeed ON dailyRunCompletions (uuid, seed)`,
`CREATE TABLE IF NOT EXISTS accountDailyRuns (uuid BINARY(16) NOT NULL, date DATE NOT NULL, score INT(11) NOT NULL DEFAULT 0, wave INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, date), CONSTRAINT accountDailyRuns_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT accountDailyRuns_ibfk_2 FOREIGN KEY (date) REFERENCES dailyRuns (date) ON DELETE NO ACTION ON UPDATE NO ACTION)`, `CREATE TABLE IF NOT EXISTS accountDailyRuns (
uuid BINARY(16) NOT NULL,
date DATE NOT NULL,
score INT(11) NOT NULL DEFAULT 0,
wave INT(11) NOT NULL DEFAULT 0,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (uuid, date),
CONSTRAINT accountDailyRuns_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT accountDailyRuns_ibfk_2 FOREIGN KEY (date) REFERENCES dailyRuns (date)
ON DELETE NO ACTION
ON UPDATE NO ACTION)`,
`CREATE INDEX IF NOT EXISTS accountDailyRunsByDate ON accountDailyRuns (date)`, `CREATE INDEX IF NOT EXISTS accountDailyRunsByDate ON accountDailyRuns (date)`,
`CREATE TABLE IF NOT EXISTS systemSaveData (uuid BINARY(16) PRIMARY KEY, data LONGBLOB, timestamp TIMESTAMP)`, `CREATE TABLE IF NOT EXISTS systemSaveData (
uuid BINARY(16) PRIMARY KEY,
data LONGBLOB,
timestamp TIMESTAMP)`,
`CREATE TABLE IF NOT EXISTS sessionSaveData (uuid BINARY(16), slot TINYINT, data LONGBLOB, timestamp TIMESTAMP, PRIMARY KEY (uuid, slot))`, `CREATE TABLE IF NOT EXISTS sessionSaveData (
} uuid BINARY(16),
slot TINYINT,
data LONGBLOB,
timestamp TIMESTAMP,
PRIMARY KEY (uuid, slot))`,
`CREATE TABLE IF NOT EXISTS eggs (
uuid VARCHAR(32) NOT NULL PRIMARY KEY,
owner BINARY(16) NOT NULL,
gachaType INT(11) NOT NULL,
hatchWaves INT(11) NOT NULL,
timestamp INT NOT NULL,
CONSTRAINT eggs_ibfk_1 FOREIGN KEY (owner) REFERENCES accounts (uuid)
ON DELETE CASCADE
ON UPDATE CASCADE)`}
for _, q := range queries { for _, q := range queries {
_, err := tx.Exec(q) _, err := tx.Exec(q)

View File

@ -142,3 +142,60 @@ func DeleteSessionSaveData(uuid []byte, slot int) error {
return nil return nil
} }
func RetrieveAccountEggs(uuid []byte) ([]defs.EggData, error) {
var accountEggs []defs.EggData
rows, err := handle.Query("SELECT uuid, gachaType, hatchWaves, timestamp FROM eggs WHERE owner = ?", uuid)
if err != nil {
return accountEggs, err
}
// For each row, we parse the raw data into an EggData and add it to the result
for rows.Next() {
var egg defs.EggData
err = rows.Scan(&egg.Id, &egg.GachaType, &egg.HatchWaves, &egg.Timestamp)
if err != nil {
return accountEggs, err
}
accountEggs = append(accountEggs, egg)
}
return accountEggs, nil
}
func UpdateAccountEggs(uuid []byte, eggs []defs.EggData) error {
for _, egg := range eggs {
// TODO: find a fix to enforce encoding from body to EggData only if
// it respects the EggData struct so we can get rid of the test
if egg.Id == 0 {
continue
}
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(egg)
if err != nil {
return err
}
_, err = handle.Exec(`INSERT INTO eggs (uuid, owner, gachaType, hatchWaves, timestamp)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE hatchWaves = ?`,
egg.Id, uuid, egg.GachaType, egg.HatchWaves, egg.Timestamp, egg.HatchWaves)
if err != nil {
return err
}
}
return nil
}
func RemoveAccountEgg(uuid []byte, eggId int) error {
_, err := handle.Exec("DELETE FROM eggs WHERE owner = ? AND uuid = ?", uuid, eggId)
if err != nil {
return err
}
return nil
}