some more code cleanup

This commit is contained in:
2022-11-27 20:02:31 +01:00
parent 4304a5a1d6
commit 43c91b694e
2 changed files with 68 additions and 70 deletions

28
main.go
View File

@@ -220,17 +220,17 @@ func housekeeping() {
shareCodes, err := utils.GetNewShareCodesForPlayer(tPlayer, conf.Steam.APIKey, rL)
if err != nil {
switch {
case errors.Is(err, utils.AuthcodeUnauthorizedError):
case errors.Is(err, utils.ErrorAuthcodeUnauthorized):
log.Infof("[HK] authCode for player %d is no longer valid", tPlayer.ID)
err = tPlayer.Update().ClearAuthCode().ClearSharecodeUpdated().Exec(context.Background())
if err != nil {
log.Errorf("[HK] Unable to clear authcode for player %d: %v", tPlayer.ID, err)
}
continue
case errors.Is(err, utils.SharecodeNoMatchError):
case errors.Is(err, utils.ErrorSharecodeNoMatch):
log.Warningf("[HK] last shareCode for player %d does not match player", tPlayer.ID)
continue
case errors.Is(err, utils.NoMatchError):
case errors.Is(err, utils.ErrorNoMatch):
log.Infof("[HK] tracked player %d with no matches found, untracked", tPlayer.ID)
err = tPlayer.Update().ClearAuthCode().ClearSharecodeUpdated().Exec(context.Background())
if err != nil {
@@ -413,7 +413,7 @@ func getPlayer(c *gin.Context) {
for _, iMatch := range tMatches {
mResponse := &utils.MatchResponse{
MatchId: iMatch.ID,
MatchID: iMatch.ID,
Map: iMatch.Map,
Date: iMatch.Date.Unix(),
Score: [2]int{iMatch.ScoreTeamA, iMatch.ScoreTeamB},
@@ -490,7 +490,7 @@ func deletePlayerTrack(c *gin.Context) {
_, err = utils.IsAuthCodeValid(tPlayer, conf.Steam.APIKey, "", authCode, nil)
if err != nil {
if errors.Is(err, utils.AuthcodeUnauthorizedError) {
if errors.Is(err, utils.ErrorAuthcodeUnauthorized) {
log.Infof("[DPT] authCode provided for player %s is invalid: %v", id, err)
c.Status(http.StatusUnauthorized)
return
@@ -540,11 +540,11 @@ func postPlayerTrack(c *gin.Context) {
_, err = utils.IsAuthCodeValid(tPlayer, conf.Steam.APIKey, shareCode, authCode, rL)
if err != nil {
switch {
case errors.Is(err, utils.AuthcodeUnauthorizedError):
case errors.Is(err, utils.ErrorAuthcodeUnauthorized):
log.Infof("[PPT] authCode provided for player %s is invalid: %v", id, err)
c.Status(http.StatusUnauthorized)
return
case errors.Is(err, utils.SharecodeNoMatchError):
case errors.Is(err, utils.ErrorSharecodeNoMatch):
log.Infof("[PPT] shareCode provided for player %s (%s) is invalid: %v", id, shareCode, err)
c.Status(http.StatusPreconditionFailed)
return
@@ -904,7 +904,7 @@ func getMatches(c *gin.Context) {
}
mResponse = append(mResponse, &utils.MatchResponse{
MatchId: iMatch.ID,
MatchID: iMatch.ID,
Map: iMatch.Map,
Date: iMatch.Date.Unix(),
Score: [2]int{iMatch.ScoreTeamA, iMatch.ScoreTeamB},
@@ -963,7 +963,7 @@ func getMatch(c *gin.Context) {
}
mResponse := &utils.MatchResponse{
MatchId: tMatch.ID,
MatchID: tMatch.ID,
ShareCode: tMatch.ShareCode,
Map: tMatch.Map,
Date: tMatch.Date.Unix(),
@@ -1088,18 +1088,18 @@ func main() {
journalhook.Enable()
}
if conf.Db.Driver == "pgx" {
pdb, err := sql.Open("pgx", conf.Db.ConnectTo)
if conf.DB.Driver == "pgx" {
pdb, err := sql.Open("pgx", conf.DB.ConnectTo)
if err != nil {
log.Fatalf("Failed to open database %s: %v", conf.Db.ConnectTo, err)
log.Fatalf("Failed to open database %s: %v", conf.DB.ConnectTo, err)
}
drv := sql.OpenDB(dialect.Postgres, pdb.DB())
db = ent.NewClient(ent.Driver(drv))
} else {
db, err = ent.Open(conf.Db.Driver, conf.Db.ConnectTo)
db, err = ent.Open(conf.DB.Driver, conf.DB.ConnectTo)
if err != nil {
log.Panicf("Failed to open database %s: %v", conf.Db.ConnectTo, err)
log.Panicf("Failed to open database %s: %v", conf.DB.ConnectTo, err)
}
defer func(Client *ent.Client) {
_ = Client.Close()

View File

@@ -32,10 +32,10 @@ type Conf struct {
Logging struct {
Level string
}
Db struct {
DB struct {
Driver string
ConnectTo string `yaml:"connect_to"`
}
} `yaml:"db"`
Parser struct {
Worker int
}
@@ -200,7 +200,7 @@ type MetaStatsResponse struct {
}
type MatchResponse struct {
MatchId uint64 `json:"match_id,string"`
MatchID uint64 `json:"match_id,string"`
ShareCode string `json:"share_code,omitempty"`
Map string `json:"map"`
Date int64 `json:"date"`
@@ -218,10 +218,10 @@ type MatchResponse struct {
}
var (
SharecodeNoMatchError = errors.New("sharecode not provided")
AuthcodeRateLimitError = errors.New("temporary rate-limited/unavailable")
AuthcodeUnauthorizedError = errors.New("authcode unauthorized")
NoMatchError = errors.New("no match found")
ErrorSharecodeNoMatch = errors.New("sharecode not provided")
ErrorAuthcodeRateLimit = errors.New("temporary rate-limited/unavailable")
ErrorAuthcodeUnauthorized = errors.New("authcode unauthorized")
ErrorNoMatch = errors.New("no match found")
)
const (
@@ -233,9 +233,10 @@ const (
//goland:noinspection SpellCheckingInspection
var (
SteamId64RegEx = regexp.MustCompile(`^\d{17}$`)
SteamID64RegEx = regexp.MustCompile(`^\d{17}$`)
ShareCodeRegEx = regexp.MustCompile(`^CSGO(?:-?[ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789]{5}){5}$`)
AuthCodeRegEx = regexp.MustCompile(`^[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{5}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}$`)
AuthCodeRegEx = regexp.MustCompile(
`^[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{5}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}$`)
)
func GetMetaStats(dbPlayer *ent.Player) (*MetaStatsResponse, error) {
@@ -388,13 +389,13 @@ func GetMetaStats(dbPlayer *ent.Player) (*MetaStatsResponse, error) {
return mResponse.WeaponDmg[i].Dmg > mResponse.WeaponDmg[j].Dmg
})
if len(mResponse.BestMates) > 10 {
if len(mResponse.BestMates) > 10 { //nolint:gomnd
mResponse.BestMates = mResponse.BestMates[:10]
}
if len(mResponse.MostMates) > 10 {
if len(mResponse.MostMates) > 10 { //nolint:gomnd
mResponse.MostMates = mResponse.MostMates[:10]
}
if len(mResponse.WeaponDmg) > 10 {
if len(mResponse.WeaponDmg) > 10 { //nolint:gomnd
mResponse.WeaponDmg = mResponse.WeaponDmg[:10]
}
@@ -431,7 +432,8 @@ func DeleteMatch(matchDel *ent.Match, db *ent.Client) error {
return nil
}
func GetWinLossTieForPlayer(dbPlayer *ent.Player) (wins int, looses int, ties int, err error) {
//nolint:nakedret
func GetWinLossTieForPlayer(dbPlayer *ent.Player) (wins, looses, ties int, err error) {
var res []struct {
MatchResult int `json:"match_result"`
Count int `json:"count"`
@@ -474,22 +476,22 @@ func GetWinLossTieForPlayer(dbPlayer *ent.Player) (wins int, looses int, ties in
return
}
func IsAuthCodeValid(player *ent.Player, apiKey string, shareCode string, authCode string, rl *rate.Limiter) (bool, error) {
func IsAuthCodeValid(tPlayer *ent.Player, apiKey, shareCode, authCode string, rl *rate.Limiter) (bool, error) {
var tMatch *ent.Match
var err error
if shareCode == "" {
tMatch, err = player.QueryMatches().Order(ent.Asc(match.FieldDate)).First(context.Background())
tMatch, err = tPlayer.QueryMatches().Order(ent.Asc(match.FieldDate)).First(context.Background())
if err != nil {
return false, SharecodeNoMatchError
return false, ErrorSharecodeNoMatch
}
_, err := getNextShareCode(tMatch.ShareCode, apiKey, authCode, player.ID, rl)
_, err := getNextShareCode(tMatch.ShareCode, apiKey, authCode, tPlayer.ID, rl)
if err != nil {
return false, err
}
return true, nil
} else {
_, err := getNextShareCode(shareCode, apiKey, authCode, player.ID, rl)
_, err := getNextShareCode(shareCode, apiKey, authCode, tPlayer.ID, rl)
if err != nil {
return false, err
}
@@ -497,28 +499,28 @@ func IsAuthCodeValid(player *ent.Player, apiKey string, shareCode string, authCo
}
}
func GetNewShareCodesForPlayer(player *ent.Player, apiKey string, rl *rate.Limiter) ([]string, error) {
latestMatch, err := player.QueryMatches().Order(ent.Desc(match.FieldDate)).First(context.Background())
func GetNewShareCodesForPlayer(tPlayer *ent.Player, apiKey string, rl *rate.Limiter) ([]string, error) {
latestMatch, err := tPlayer.QueryMatches().Order(ent.Desc(match.FieldDate)).First(context.Background())
if err != nil {
if ent.IsNotFound(err) {
return nil, NoMatchError
return nil, ErrorNoMatch
}
return nil, err
}
oldestMatch, err := player.QueryMatches().Order(ent.Asc(match.FieldDate)).First(context.Background())
oldestMatch, err := tPlayer.QueryMatches().Order(ent.Asc(match.FieldDate)).First(context.Background())
if err != nil {
if ent.IsNotFound(err) {
return nil, NoMatchError
return nil, ErrorNoMatch
}
return nil, err
}
var newShareCode string
if oldestMatch.ShareCode == player.OldestSharecodeSeen {
newShareCode, err = getNextShareCode(latestMatch.ShareCode, apiKey, player.AuthCode, player.ID, rl)
if oldestMatch.ShareCode == tPlayer.OldestSharecodeSeen {
newShareCode, err = getNextShareCode(latestMatch.ShareCode, apiKey, tPlayer.AuthCode, tPlayer.ID, rl)
} else {
newShareCode, err = getNextShareCode(oldestMatch.ShareCode, apiKey, player.AuthCode, player.ID, rl)
newShareCode, err = getNextShareCode(oldestMatch.ShareCode, apiKey, tPlayer.AuthCode, tPlayer.ID, rl)
}
if err != nil {
return nil, err
@@ -527,13 +529,13 @@ func GetNewShareCodesForPlayer(player *ent.Player, apiKey string, rl *rate.Limit
var rCodes []string
for newShareCode != "n/a" {
rCodes = append(rCodes, newShareCode)
newShareCode, err = getNextShareCode(rCodes[len(rCodes)-1], apiKey, player.AuthCode, player.ID, rl)
newShareCode, err = getNextShareCode(rCodes[len(rCodes)-1], apiKey, tPlayer.AuthCode, tPlayer.ID, rl)
if err != nil {
return nil, err
}
}
err = player.Update().SetSharecodeUpdated(time.Now().UTC()).SetOldestSharecodeSeen(oldestMatch.ShareCode).Exec(context.Background())
err = tPlayer.Update().SetSharecodeUpdated(time.Now().UTC()).SetOldestSharecodeSeen(oldestMatch.ShareCode).Exec(context.Background())
if err != nil {
return nil, err
}
@@ -541,8 +543,8 @@ func GetNewShareCodesForPlayer(player *ent.Player, apiKey string, rl *rate.Limit
return rCodes, nil
}
func getNextShareCode(lastCode string, apiKey string, authCode string, steamId uint64, rl *rate.Limiter) (string, error) {
if lastCode == "" || apiKey == "" || authCode == "" || steamId == 0 {
func getNextShareCode(lastCode, apiKey, authCode string, steamID uint64, rl *rate.Limiter) (string, error) {
if lastCode == "" || apiKey == "" || authCode == "" || steamID == 0 {
return "", fmt.Errorf("invalid arguments")
}
@@ -552,8 +554,8 @@ func getNextShareCode(lastCode string, apiKey string, authCode string, steamId u
return "", err
}
}
log.Debugf("[SC] STEAMPI with %s", fmt.Sprintf(shareCodeURLEntry, "REDACTED", steamId, "REDACTED", lastCode))
r, err := http.Get(fmt.Sprintf(shareCodeURLEntry, apiKey, steamId, authCode, lastCode))
log.Debugf("[SC] STEAMPI with %s", fmt.Sprintf(shareCodeURLEntry, "REDACTED", steamID, "REDACTED", lastCode))
r, err := http.Get(fmt.Sprintf(shareCodeURLEntry, apiKey, steamID, authCode, lastCode)) //nolint:noctx
if err != nil {
return "", err
}
@@ -562,34 +564,32 @@ func getNextShareCode(lastCode string, apiKey string, authCode string, steamId u
case http.StatusAccepted:
return "n/a", nil
case http.StatusTooManyRequests:
return "", AuthcodeRateLimitError
return "", ErrorAuthcodeRateLimit
case http.StatusServiceUnavailable:
return "", AuthcodeRateLimitError
return "", ErrorAuthcodeRateLimit
case http.StatusPreconditionFailed:
return "", SharecodeNoMatchError
return "", ErrorSharecodeNoMatch
case http.StatusForbidden:
return "", AuthcodeUnauthorizedError
return "", ErrorAuthcodeUnauthorized
case http.StatusOK:
break
default:
return "", errors.New("temporary steamapi error")
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(r.Body)
bJson, err := io.ReadAll(r.Body)
bJSON, err := io.ReadAll(r.Body)
if err != nil {
return "", err
}
_ = r.Body.Close()
rJSON := new(ShareCodeResponse)
err = json.Unmarshal(bJSON, rJSON)
if err != nil {
return "", err
}
rJson := new(ShareCodeResponse)
err = json.Unmarshal(bJson, rJson)
if err != nil {
return "", err
}
return rJson.Result.Code, nil
return rJSON.Result.Code, nil
}
func Player(db *ent.Client, id interface{}, apiKey string, rl *rate.Limiter) (*ent.Player, error) {
@@ -597,7 +597,7 @@ func Player(db *ent.Client, id interface{}, apiKey string, rl *rate.Limiter) (*e
case uint64:
return PlayerFromSteamID64(db, e, apiKey, rl)
case string:
if SteamId64RegEx.MatchString(e) {
if SteamID64RegEx.MatchString(e) {
steamID64, err := strconv.ParseUint(e, 10, 64)
if err != nil {
return nil, err
@@ -612,7 +612,7 @@ func Player(db *ent.Client, id interface{}, apiKey string, rl *rate.Limiter) (*e
}
}
func PlayerFromVanityURL(db *ent.Client, id string, apiKey string, rl *rate.Limiter) (*ent.Player, error) {
func PlayerFromVanityURL(db *ent.Client, id, apiKey string, rl *rate.Limiter) (*ent.Player, error) {
if id == "" {
return nil, fmt.Errorf("invalid arguments")
}
@@ -681,7 +681,7 @@ func PlayerFromSteamID64(db *ent.Client, steamID uint64, apiKey string, rl *rate
}
}
func TranslateWithDeepL(text string, language string, baseURL string, apiKey string, timeout int) (translated string, detectedLanguage string, err error) {
func TranslateWithDeepL(text, language, baseURL, apiKey string, timeout int) (translated, detectedLanguage string, err error) {
c := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
@@ -689,7 +689,7 @@ func TranslateWithDeepL(text string, language string, baseURL string, apiKey str
v.Set("auth_key", apiKey)
v.Set("text", text)
v.Set("target_lang", language)
dlResp, err := c.PostForm("https://"+baseURL+"/v2/translate", v)
dlResp, err := c.PostForm("https://"+baseURL+"/v2/translate", v) //nolint:noctx
switch {
case err != nil:
return "", "", fmt.Errorf("deepl response: %w", err)
@@ -697,12 +697,10 @@ func TranslateWithDeepL(text string, language string, baseURL string, apiKey str
return "", "", fmt.Errorf("deepl response %d", dlResp.StatusCode)
default:
respBytes, err := io.ReadAll(dlResp.Body)
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(dlResp.Body)
if err != nil {
return "", "", fmt.Errorf("error reading deepl response: %w", err)
}
_ = dlResp.Body.Close()
dlRespJSON := new(DeepLResponse)
err = json.Unmarshal(respBytes, &dlRespJSON)
if err != nil {
@@ -719,7 +717,7 @@ func PlayerFromSteam(players []*ent.Player, db *ent.Client, apiKey string, rl *r
idsToUpdate = append(idsToUpdate, updatePlayer.ID)
}
batches := int(math.Round((float64(len(players)) / 1000) + 0.5))
batches := int(math.Round((float64(len(players)) / 1000) + 0.5)) //nolint:gomnd
if rl != nil {
err := rl.WaitN(context.Background(), batches)
@@ -736,7 +734,7 @@ func PlayerFromSteam(players []*ent.Player, db *ent.Client, apiKey string, rl *r
var nPlayers []*ent.Player
for _, pS := range playerSum {
// check for vanityURL
if SteamId64RegEx.MatchString(path.Base(pS.ProfileURL)) {
if SteamID64RegEx.MatchString(path.Base(pS.ProfileURL)) {
pS.ProfileURL = ""
} else {
pS.ProfileURL = path.Base(pS.ProfileURL)