Change daily seed generation and update schema for recording failed daily runs

pull/1/head
Flashfyre 9 months ago
parent 4710617f23
commit 2cb7be52eb

@ -1,13 +1,11 @@
package api package api
import ( import (
"encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
"time"
"github.com/Flashfyre/pokerogue-server/db" "github.com/Flashfyre/pokerogue-server/db"
) )
@ -23,7 +21,14 @@ func ScheduleDailyRunRefresh() {
} }
func InitDailyRun() { func InitDailyRun() {
dailyRunSeed = base64.StdEncoding.EncodeToString(SeedFromTime(time.Now().UTC())) var err error
dailyRunSeed, err = db.GetDailyRunSeed()
if err != nil {
log.Printf("failed to generated daily run seed: %s", err.Error())
}
if dailyRunSeed == "" {
dailyRunSeed = RandString(24)
err := db.TryAddDailyRun(dailyRunSeed) err := db.TryAddDailyRun(dailyRunSeed)
if err != nil { if err != nil {
log.Print(err.Error()) log.Print(err.Error())
@ -31,6 +36,7 @@ func InitDailyRun() {
log.Printf("Daily Run Seed: %s", dailyRunSeed) log.Printf("Daily Run Seed: %s", dailyRunSeed)
} }
} }
}
// /daily/seed - get daily run seed // /daily/seed - get daily run seed

@ -276,11 +276,22 @@ func (s *Server) HandleSavedataClear(w http.ResponseWriter, r *http.Request) {
return return
} }
sessionCompleted := ValidateSessionCompleted(session) sessionCompleted := session.BattleType == 2 && ValidateSessionCompleted(session)
newCompletion := false newCompletion := false
if session.GameMode == 3 {
waveCompleted := session.WaveIndex
if session.BattleType != 2 {
waveCompleted--
}
err = db.AddOrUpdateAccountDailyRun(uuid, session.Score, waveCompleted)
if err != nil {
log.Printf("failed to add or update daily run record: %s", err.Error())
}
}
if sessionCompleted { if sessionCompleted {
newCompletion, err = db.TryAddSeedCompletion(uuid, session.Seed, int(session.GameMode), session.Score) newCompletion, err = db.TryAddSeedCompletion(uuid, session.Seed, int(session.GameMode))
if err != nil { if err != nil {
log.Printf("failed to mark seed as completed: %s", err.Error()) log.Printf("failed to mark seed as completed: %s", err.Error())
} }

@ -1,23 +1,20 @@
package api package api
import ( import (
"crypto/md5" "crypto/rand"
"encoding/binary"
"math"
"time"
) )
var seedKey []byte // 32 bytes const randRunes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
const lenRandRunes = len(randRunes)
func SetSeedKey(key []byte) { func RandString(length int) string {
seedKey = key b := make([]byte, length)
}
func SeedFromTime(seedTime time.Time) []byte { rand.Read(b)
day := make([]byte, 8)
binary.BigEndian.PutUint64(day, uint64(math.Floor(float64(seedTime.Unix())/float64(time.Hour*24))))
sum := md5.Sum(append(seedKey, day...)) for i := range b {
b[i] = randRunes[int(b[i])%lenRandRunes]
}
return sum[:] return string(b)
} }

@ -1,6 +1,8 @@
package db package db
import ( import (
"database/sql"
"github.com/Flashfyre/pokerogue-server/defs" "github.com/Flashfyre/pokerogue-server/defs"
) )
@ -13,12 +15,35 @@ func TryAddDailyRun(seed string) error {
return nil return nil
} }
func GetDailyRunSeed() (string, error) {
var seed string
err := handle.QueryRow("SELECT seed FROM dailyRuns WHERE date = UTC_DATE()").Scan(&seed)
if err != nil {
if err == sql.ErrNoRows {
return "", err
}
return "", err
}
return seed, nil
}
func AddOrUpdateAccountDailyRun(uuid []byte, score int, wave int) error {
_, err := handle.Exec("INSERT INTO accountDailyRuns (uuid, date, score, wave, timestamp) VALUES (?, UTC_DATE(), ?, ?, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE score = ?, wave = GREATEST(wave, ?), timestamp = IF(score < ?, UTC_TIMESTAMP(), timestamp)", uuid, score, wave, score, wave, score)
if err != nil {
return err
}
return nil
}
func GetRankings(page int) ([]defs.DailyRanking, error) { func GetRankings(page int) ([]defs.DailyRanking, error) {
var rankings []defs.DailyRanking var rankings []defs.DailyRanking
offset := (page - 1) * 10 offset := (page - 1) * 10
results, err := handle.Query("SELECT RANK() OVER (ORDER BY sc.score DESC, sc.timestamp), a.username, sc.score FROM seedCompletions sc JOIN dailyRuns dr ON dr.seed = sc.seed JOIN accounts a ON sc.uuid = a.uuid WHERE dr.date = UTC_DATE() LIMIT 10 OFFSET ?", offset) results, err := handle.Query("SELECT RANK() OVER (ORDER BY adr.score DESC, adr.timestamp), a.username, adr.score, adr.wave FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date = UTC_DATE() LIMIT 10 OFFSET ?", offset)
if err != nil { if err != nil {
return rankings, err return rankings, err
} }
@ -27,7 +52,7 @@ func GetRankings(page int) ([]defs.DailyRanking, error) {
for results.Next() { for results.Next() {
ranking := defs.DailyRanking{} ranking := defs.DailyRanking{}
err = results.Scan(&ranking.Rank, &ranking.Username, &ranking.Score) err = results.Scan(&ranking.Rank, &ranking.Username, &ranking.Score, &ranking.Wave)
if err != nil { if err != nil {
return rankings, err return rankings, err
} }

@ -1,26 +1,24 @@
package db package db
func TryAddSeedCompletion(uuid []byte, seed string, mode int, score int) (bool, error) { func TryAddSeedCompletion(uuid []byte, seed string, mode int) (bool, error) {
if len(seed) < 24 { if len(seed) < 24 {
for range 24 - len(seed) { for range 24 - len(seed) {
seed += "0" seed += "0"
} }
} }
newCompletion := true
var count int var count int
err := handle.QueryRow("SELECT COUNT(*) FROM seedCompletions WHERE uuid = ? AND seed = ?", uuid, seed).Scan(&count) err := handle.QueryRow("SELECT COUNT(*) FROM seedCompletions WHERE uuid = ? AND seed = ?", uuid, seed).Scan(&count)
if err != nil { if err != nil {
return false, err return false, err
} else if count > 0 { } else if count > 0 {
newCompletion = false return false, nil
} }
_, err = handle.Exec("INSERT INTO seedCompletions (uuid, seed, mode, score, timestamp) VALUES (?, ?, ?, ?, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE score = ?, timestamp = IF(score < ?, UTC_TIMESTAMP(), timestamp)", uuid, seed, mode, score, score, score) _, err = handle.Exec("INSERT INTO seedCompletions (uuid, seed, mode, timestamp) VALUES (?, ?, ?, UTC_TIMESTAMP())", uuid, seed, mode)
if err != nil { if err != nil {
return false, err return false, err
} }
return newCompletion, nil return true, nil
} }

@ -4,4 +4,5 @@ type DailyRanking struct {
Rank int `json:"rank"` Rank int `json:"rank"`
Username string `json:"username"` Username string `json:"username"`
Score int `json:"score"` Score int `json:"score"`
Wave int `json:"wave"`
} }

@ -11,8 +11,6 @@ import (
"github.com/Flashfyre/pokerogue-server/db" "github.com/Flashfyre/pokerogue-server/db"
) )
var key []byte
func main() { func main() {
debug := flag.Bool("debug", false, "debug mode") debug := flag.Bool("debug", false, "debug mode")
@ -45,12 +43,6 @@ func main() {
os.Chmod(*addr, 0777) os.Chmod(*addr, 0777)
} }
key, err = os.ReadFile("key")
if err != nil {
log.Fatalf("failed to read key file!")
}
api.SetSeedKey(key)
api.ScheduleDailyRunRefresh() api.ScheduleDailyRunRefresh()
api.InitDailyRun() api.InitDailyRun()

Loading…
Cancel
Save