rogueserver/api/daily/common.go

83 lines
1.5 KiB
Go
Raw Normal View History

package daily
2024-03-16 18:51:13 -07:00
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
"fmt"
2024-03-16 18:51:13 -07:00
"log"
2024-03-18 16:55:02 -07:00
"os"
"time"
2024-03-16 18:51:13 -07:00
2024-03-19 19:05:37 -07:00
"github.com/go-co-op/gocron"
2024-04-14 16:25:36 -07:00
"github.com/pagefaultgames/pokerogue-server/db"
2024-03-16 18:51:13 -07:00
)
2024-03-18 16:55:02 -07:00
const secondsPerDay = 60 * 60 * 24
2024-03-16 18:51:13 -07:00
var (
2024-03-19 19:05:37 -07:00
dailyRunScheduler = gocron.NewScheduler(time.UTC)
dailyRunSecret []byte
2024-03-16 18:51:13 -07:00
)
func Init() error {
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) {
2024-04-08 15:15:09 -07:00
return fmt.Errorf("failed to read daily seed secret: %s", err)
2024-03-18 16:55:02 -07:00
}
2024-03-18 16:55:02 -07:00
newSecret := make([]byte, 32)
_, err := rand.Read(newSecret)
if err != nil {
2024-04-08 15:15:09 -07:00
return fmt.Errorf("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 {
2024-04-08 15:15:09 -07:00
return fmt.Errorf("failed to write daily seed secret: %s", err)
2024-03-18 16:55:02 -07:00
}
secret = newSecret
}
dailyRunSecret = secret
err = db.TryAddDailyRun(Seed())
2024-03-18 16:55:02 -07:00
if err != nil {
2024-04-01 19:54:55 -07:00
log.Print(err)
2024-03-16 18:51:13 -07:00
}
2024-04-01 19:54:55 -07:00
log.Printf("Daily Run Seed: %s", Seed())
scheduleRefresh()
2024-04-08 15:15:09 -07:00
return nil
2024-03-16 18:51:13 -07:00
}
func Seed() string {
return base64.StdEncoding.EncodeToString(deriveDailyRunSeed(time.Now().UTC()))
}
func scheduleRefresh() {
dailyRunScheduler.Every(1).Day().At("00:00").Do(func() error {
err := Init()
if err != nil {
log.Fatal(err)
}
return nil
}())
dailyRunScheduler.StartAsync()
}
2024-04-01 19:54:55 -07:00
func deriveDailyRunSeed(seedTime time.Time) []byte {
2024-03-18 16:55:02 -07:00
day := make([]byte, 8)
binary.BigEndian.PutUint64(day, uint64(seedTime.Unix()/secondsPerDay))
hashedSeed := md5.Sum(append(day, dailyRunSecret...))
return hashedSeed[:]
}