diff --git a/api/account-helper.go b/api/account-helper.go index 116d1a8..20bceb4 100644 --- a/api/account-helper.go +++ b/api/account-helper.go @@ -8,12 +8,12 @@ import ( "github.com/Flashfyre/pokerogue-server/db" ) -func GetUsernameFromRequest(request *http.Request) (string, error) { - if request.Header.Get("Authorization") == "" { +func getUsernameFromRequest(r *http.Request) (string, error) { + if r.Header.Get("Authorization") == "" { return "", fmt.Errorf("missing token") } - token, err := base64.StdEncoding.DecodeString(request.Header.Get("Authorization")) + token, err := base64.StdEncoding.DecodeString(r.Header.Get("Authorization")) if err != nil { return "", fmt.Errorf("failed to decode token: %s", err) } @@ -30,12 +30,12 @@ func GetUsernameFromRequest(request *http.Request) (string, error) { return username, nil } -func GetUuidFromRequest(request *http.Request) ([]byte, error) { - if request.Header.Get("Authorization") == "" { +func getUuidFromRequest(r *http.Request) ([]byte, error) { + if r.Header.Get("Authorization") == "" { return nil, fmt.Errorf("missing token") } - token, err := base64.StdEncoding.DecodeString(request.Header.Get("Authorization")) + token, err := base64.StdEncoding.DecodeString(r.Header.Get("Authorization")) if err != nil { return nil, fmt.Errorf("failed to decode token: %s", err) } diff --git a/api/account.go b/api/account.go index e73b1ac..91333fa 100644 --- a/api/account.go +++ b/api/account.go @@ -26,21 +26,20 @@ const ( var isValidUsername = regexp.MustCompile(`^\w{1,16}$`).MatchString -// /account/info - get account info - type AccountInfoResponse struct { Username string `json:"username"` LastSessionSlot int `json:"lastSessionSlot"` } -func (s *Server) HandleAccountInfo(w http.ResponseWriter, r *http.Request) { - username, err := GetUsernameFromRequest(r) +// /account/info - get account info +func (s *Server) handleAccountInfo(w http.ResponseWriter, r *http.Request) { + username, err := getUsernameFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } - uuid, err := GetUuidFromRequest(r) // lazy + uuid, err := getUuidFromRequest(r) // lazy if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -74,11 +73,11 @@ func (s *Server) HandleAccountInfo(w http.ResponseWriter, r *http.Request) { w.Write(response) } -// /account/register - register account type AccountRegisterRequest GenericAuthRequest -func (s *Server) HandleAccountRegister(w http.ResponseWriter, r *http.Request) { +// /account/register - register account +func (s *Server) handleAccountRegister(w http.ResponseWriter, r *http.Request) { var request AccountRegisterRequest err := json.NewDecoder(r.Body).Decode(&request) if err != nil { @@ -121,12 +120,11 @@ func (s *Server) HandleAccountRegister(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// /account/login - log into account - type AccountLoginRequest GenericAuthRequest type AccountLoginResponse GenericAuthResponse -func (s *Server) HandleAccountLogin(w http.ResponseWriter, r *http.Request) { +// /account/login - log into account +func (s *Server) handleAccountLogin(w http.ResponseWriter, r *http.Request) { var request AccountLoginRequest err := json.NewDecoder(r.Body).Decode(&request) if err != nil { @@ -184,8 +182,7 @@ func (s *Server) HandleAccountLogin(w http.ResponseWriter, r *http.Request) { } // /account/logout - log out of account - -func (s *Server) HandleAccountLogout(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleAccountLogout(w http.ResponseWriter, r *http.Request) { token, err := base64.StdEncoding.DecodeString(r.Header.Get("Authorization")) if err != nil { http.Error(w, fmt.Sprintf("failed to decode token: %s", err), http.StatusBadRequest) diff --git a/api/daily.go b/api/daily.go index 35ec5b2..70a79de 100644 --- a/api/daily.go +++ b/api/daily.go @@ -53,16 +53,17 @@ func InitDailyRun() { dailyRunSecret = secret - dailyRunSeed = base64.StdEncoding.EncodeToString(DeriveDailyRunSeed(time.Now().UTC())) + dailyRunSeed = base64.StdEncoding.EncodeToString(deriveDailyRunSeed(time.Now().UTC())) err = db.TryAddDailyRun(dailyRunSeed) if err != nil { - log.Print(err.Error()) + log.Print(err) } + log.Printf("Daily Run Seed: %s", dailyRunSeed) } -func DeriveDailyRunSeed(seedTime time.Time) []byte { +func deriveDailyRunSeed(seedTime time.Time) []byte { day := make([]byte, 8) binary.BigEndian.PutUint64(day, uint64(seedTime.Unix()/secondsPerDay)) @@ -72,20 +73,13 @@ func DeriveDailyRunSeed(seedTime time.Time) []byte { } // /daily/seed - fetch daily run seed - -func (s *Server) HandleSeed(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleSeed(w http.ResponseWriter) { w.Write([]byte(dailyRunSeed)) } // /daily/rankings - fetch daily rankings - -func (s *Server) HandleRankings(w http.ResponseWriter, r *http.Request) { - var err error - var category int - var page int - - var uuid []byte - uuid, err = GetUuidFromRequest(r) +func (s *Server) handleRankings(w http.ResponseWriter, r *http.Request) { + uuid, err := getUuidFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -96,24 +90,22 @@ func (s *Server) HandleRankings(w http.ResponseWriter, r *http.Request) { log.Print("failed to update account last activity") } + var category int if r.URL.Query().Has("category") { category, err = strconv.Atoi(r.URL.Query().Get("category")) if err != nil { http.Error(w, fmt.Sprintf("failed to convert category: %s", err), http.StatusBadRequest) return } - } else { - category = 0 } + page := 1 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 } rankings, err := db.FetchRankings(category, page) @@ -131,8 +123,7 @@ func (s *Server) HandleRankings(w http.ResponseWriter, r *http.Request) { } // /daily/rankingpagecount - fetch daily ranking page count - -func (s *Server) HandleRankingPageCount(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleRankingPageCount(w http.ResponseWriter, r *http.Request) { var err error var category int @@ -142,8 +133,6 @@ func (s *Server) HandleRankingPageCount(w http.ResponseWriter, r *http.Request) http.Error(w, fmt.Sprintf("failed to convert category: %s", err), http.StatusBadRequest) return } - } else { - category = 0 } pageCount, err := db.FetchRankingPageCount(category) diff --git a/api/game.go b/api/game.go index 5efedf4..46240e8 100644 --- a/api/game.go +++ b/api/game.go @@ -13,25 +13,24 @@ import ( var ( playerCountScheduler = gocron.NewScheduler(time.UTC) - playerCount = 0 + playerCount int ) func SchedulePlayerCountRefresh() { - playerCountScheduler.Every(10).Second().Do(UpdatePlayerCount) + playerCountScheduler.Every(10).Second().Do(updatePlayerCount) playerCountScheduler.StartAsync() } -func UpdatePlayerCount() { +func updatePlayerCount() { var err error playerCount, err = db.FetchPlayerCount() if err != nil { - log.Print(err.Error()) + log.Print(err) } } // /game/playercount - get player count - -func (s *Server) HandlePlayerCountGet(w http.ResponseWriter, r *http.Request) { +func (s *Server) handlePlayerCountGet(w http.ResponseWriter) { response, err := json.Marshal(playerCount) if err != nil { http.Error(w, fmt.Sprintf("failed to marshal response json: %s", err), http.StatusInternalServerError) diff --git a/api/generic.go b/api/generic.go index 0888bba..2084071 100644 --- a/api/generic.go +++ b/api/generic.go @@ -1,7 +1,6 @@ package api import ( - "encoding/gob" "net/http" ) @@ -21,37 +20,34 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } - gob.Register([]interface{}{}) - gob.Register(map[string]interface{}{}) - switch r.URL.Path { case "/account/info": - s.HandleAccountInfo(w, r) + s.handleAccountInfo(w, r) case "/account/register": - s.HandleAccountRegister(w, r) + s.handleAccountRegister(w, r) case "/account/login": - s.HandleAccountLogin(w, r) + s.handleAccountLogin(w, r) case "/account/logout": - s.HandleAccountLogout(w, r) + s.handleAccountLogout(w, r) case "/game/playercount": - s.HandlePlayerCountGet(w, r) + s.handlePlayerCountGet(w) case "/savedata/get": - s.HandleSavedataGet(w, r) + s.handleSavedataGet(w, r) case "/savedata/update": - s.HandleSavedataUpdate(w, r) + s.handleSavedataUpdate(w, r) case "/savedata/delete": - s.HandleSavedataDelete(w, r) + s.handleSavedataDelete(w, r) case "/savedata/clear": - s.HandleSavedataClear(w, r) + s.handleSavedataClear(w, r) case "/daily/seed": - s.HandleSeed(w, r) + s.handleSeed(w) case "/daily/rankings": - s.HandleRankings(w, r) + s.handleRankings(w, r) case "/daily/rankingpagecount": - s.HandleRankingPageCount(w, r) + s.handleRankingPageCount(w, r) } } diff --git a/api/savedata-helper.go b/api/savedata-helper.go index d7f0542..bf775e8 100644 --- a/api/savedata-helper.go +++ b/api/savedata-helper.go @@ -12,7 +12,10 @@ import ( "github.com/klauspost/compress/zstd" ) -func ReadSystemSaveData(uuid []byte) (defs.SystemSaveData, error) { +func readSystemSaveData(uuid []byte) (defs.SystemSaveData, error) { + gob.Register([]interface{}{}) + gob.Register(map[string]interface{}{}) + var system defs.SystemSaveData save, err := os.ReadFile("userdata/" + hex.EncodeToString(uuid) + "/system.pzs") @@ -40,7 +43,10 @@ func ReadSystemSaveData(uuid []byte) (defs.SystemSaveData, error) { return system, nil } -func ReadSessionSaveData(uuid []byte, slotId int) (defs.SessionSaveData, error) { +func readSessionSaveData(uuid []byte, slotId int) (defs.SessionSaveData, error) { + gob.Register([]interface{}{}) + gob.Register(map[string]interface{}{}) + var session defs.SessionSaveData fileName := "session" @@ -73,12 +79,13 @@ func ReadSessionSaveData(uuid []byte, slotId int) (defs.SessionSaveData, error) return session, nil } -func ValidateSessionCompleted(session defs.SessionSaveData) bool { +func validateSessionCompleted(session defs.SessionSaveData) bool { switch session.GameMode { case 0: return session.BattleType == 2 && session.WaveIndex == 200 case 3: return session.BattleType == 2 && session.WaveIndex == 50 } + return false } diff --git a/api/savedata.go b/api/savedata.go index bbeac33..54929db 100644 --- a/api/savedata.go +++ b/api/savedata.go @@ -19,9 +19,8 @@ import ( const sessionSlotCount = 3 // /savedata/get - get save data - -func (s *Server) HandleSavedataGet(w http.ResponseWriter, r *http.Request) { - uuid, err := GetUuidFromRequest(r) +func (s *Server) handleSavedataGet(w http.ResponseWriter, r *http.Request) { + uuid, err := getUuidFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -29,7 +28,7 @@ func (s *Server) HandleSavedataGet(w http.ResponseWriter, r *http.Request) { switch r.URL.Query().Get("datatype") { case "0": // System - system, err := ReadSystemSaveData(uuid) + system, err := readSystemSaveData(uuid) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -54,7 +53,7 @@ func (s *Server) HandleSavedataGet(w http.ResponseWriter, r *http.Request) { return } - session, err := ReadSessionSaveData(uuid, slotId) + session, err := readSessionSaveData(uuid, slotId) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -74,9 +73,8 @@ func (s *Server) HandleSavedataGet(w http.ResponseWriter, r *http.Request) { } // /savedata/update - update save data - -func (s *Server) HandleSavedataUpdate(w http.ResponseWriter, r *http.Request) { - uuid, err := GetUuidFromRequest(r) +func (s *Server) handleSavedataUpdate(w http.ResponseWriter, r *http.Request) { + uuid, err := getUuidFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -188,9 +186,8 @@ func (s *Server) HandleSavedataUpdate(w http.ResponseWriter, r *http.Request) { } // /savedata/delete - delete save data - -func (s *Server) HandleSavedataDelete(w http.ResponseWriter, r *http.Request) { - uuid, err := GetUuidFromRequest(r) +func (s *Server) handleSavedataDelete(w http.ResponseWriter, r *http.Request) { + uuid, err := getUuidFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -245,9 +242,8 @@ type SavedataClearResponse struct { } // /savedata/clear - mark session save data as cleared and delete - -func (s *Server) HandleSavedataClear(w http.ResponseWriter, r *http.Request) { - uuid, err := GetUuidFromRequest(r) +func (s *Server) handleSavedataClear(w http.ResponseWriter, r *http.Request) { + uuid, err := getUuidFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -276,7 +272,7 @@ func (s *Server) HandleSavedataClear(w http.ResponseWriter, r *http.Request) { return } - sessionCompleted := ValidateSessionCompleted(session) + sessionCompleted := validateSessionCompleted(session) newCompletion := false if session.GameMode == 3 && session.Seed == dailyRunSeed { @@ -286,14 +282,14 @@ func (s *Server) HandleSavedataClear(w http.ResponseWriter, r *http.Request) { } err = db.AddOrUpdateAccountDailyRun(uuid, session.Score, waveCompleted) if err != nil { - log.Printf("failed to add or update daily run record: %s", err.Error()) + log.Printf("failed to add or update daily run record: %s", err) } } if sessionCompleted { newCompletion, err = db.TryAddSeedCompletion(uuid, session.Seed, int(session.GameMode)) if err != nil { - log.Printf("failed to mark seed as completed: %s", err.Error()) + log.Printf("failed to mark seed as completed: %s", err) } } diff --git a/db/daily.go b/db/daily.go index 2d85b41..2172b08 100644 --- a/db/daily.go +++ b/db/daily.go @@ -45,7 +45,7 @@ func FetchRankings(category int, page int) ([]defs.DailyRanking, error) { defer results.Close() for results.Next() { - ranking := defs.DailyRanking{} + var ranking defs.DailyRanking err = results.Scan(&ranking.Rank, &ranking.Username, &ranking.Score, &ranking.Wave) if err != nil { return rankings, err @@ -58,8 +58,6 @@ func FetchRankings(category int, page int) ([]defs.DailyRanking, error) { } func FetchRankingPageCount(category int) (int, error) { - var recordCount int - var query string switch category { case 0: @@ -68,6 +66,7 @@ func FetchRankingPageCount(category int) (int, error) { query = "SELECT COUNT(DISTINCT a.username) FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date >= DATE_SUB(DATE(UTC_TIMESTAMP()), INTERVAL DAYOFWEEK(UTC_TIMESTAMP()) - 1 DAY)" } + var recordCount int err := handle.QueryRow(query).Scan(&recordCount) if err != nil { return 0, err diff --git a/db/game.go b/db/game.go index cb62b9f..98af758 100644 --- a/db/game.go +++ b/db/game.go @@ -2,7 +2,6 @@ package db func FetchPlayerCount() (int, error) { var playerCount int - err := handle.QueryRow("SELECT COUNT(*) FROM accounts WHERE lastActivity > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)").Scan(&playerCount) if err != nil { return 0, err