rogueserver/api/daily.go

109 lines
2.1 KiB
Go
Raw Normal View History

2024-03-16 18:51:13 -07:00
package api
import (
2024-03-18 16:55:02 -07:00
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/binary"
2024-03-17 10:18:51 -07:00
"encoding/json"
"fmt"
2024-03-16 18:51:13 -07:00
"log"
"net/http"
2024-03-18 16:55:02 -07:00
"os"
"strconv"
2024-03-18 16:55:02 -07:00
"time"
2024-03-16 18:51:13 -07:00
"github.com/Flashfyre/pokerogue-server/db"
)
2024-03-18 16:55:02 -07:00
const secondsPerDay = 60 * 60 * 24
2024-03-16 18:51:13 -07:00
var (
2024-03-18 16:55:02 -07:00
dailyRunSecret []byte
dailyRunSeed string
2024-03-16 18:51:13 -07:00
)
func ScheduleDailyRunRefresh() {
scheduler.Every(1).Day().At("00:00").Do(func() {
InitDailyRun()
})
}
func InitDailyRun() {
2024-03-18 16:55:02 -07:00
secret, err := os.ReadFile("secret.key")
2024-03-16 18:51:13 -07:00
if err != nil {
2024-03-18 16:55:02 -07:00
if !os.IsNotExist(err) {
log.Fatalf("failed to read daily seed secret: %s", err)
}
2024-03-18 16:55:02 -07:00
newSecret := make([]byte, 32)
_, err := rand.Read(newSecret)
if err != nil {
2024-03-18 16:55:02 -07:00
log.Fatalf("failed to generate daily seed secret: %s", err)
}
2024-03-18 16:55:02 -07:00
err = os.WriteFile("secret.key", newSecret, 0400)
if err != nil {
log.Fatalf("failed to write daily seed secret: %s", err)
}
secret = newSecret
}
dailyRunSecret = secret
dailyRunSeed = base64.StdEncoding.EncodeToString(DeriveDailyRunSeed(time.Now().UTC()))
err = db.TryAddDailyRun(dailyRunSeed)
if err != nil {
log.Print(err.Error())
} else {
log.Printf("Daily Run Seed: %s", dailyRunSeed)
2024-03-16 18:51:13 -07:00
}
}
2024-03-18 16:55:02 -07:00
func DeriveDailyRunSeed(seedTime time.Time) []byte {
day := make([]byte, 8)
binary.BigEndian.PutUint64(day, uint64(seedTime.Unix()/secondsPerDay))
hashedSeed := md5.Sum(append(day, dailyRunSecret...))
return hashedSeed[:]
}
// /daily/seed - fetch daily run seed
2024-03-16 18:51:13 -07:00
func (s *Server) HandleSeed(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(dailyRunSeed))
}
2024-03-17 10:18:51 -07:00
// /daily/rankings - fetch daily rankings
func (s *Server) HandleRankings(w http.ResponseWriter, r *http.Request) {
var err error
var page int
if r.URL.Query().Has("page") {
page, err = strconv.Atoi(r.URL.Query().Get("page"))
if err != nil {
http.Error(w, fmt.Sprintf("failed to convert page: %s", err), http.StatusBadRequest)
return
}
} else {
page = 1
}
2024-03-18 16:55:02 -07:00
rankings, err := db.FetchRankings(page)
2024-03-17 10:18:51 -07:00
if err != nil {
log.Print("failed to retrieve rankings")
}
response, err := json.Marshal(rankings)
if err != nil {
http.Error(w, fmt.Sprintf("failed to marshal response json: %s", err), http.StatusInternalServerError)
return
}
w.Write(response)
}