-
Notifications
You must be signed in to change notification settings - Fork 0
/
golf.go
56 lines (49 loc) · 1.36 KB
/
golf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package rctfgolf
import (
"fmt"
"net/http"
"os"
"time"
"github.com/redpwn/rctf-golf/internal/api"
)
func unixMillisToTime(millis int64) time.Time {
return time.Unix(millis/1000, millis%1000*int64(time.Millisecond))
}
func calculateWithClient(c *api.APIClient, chall string) (time.Duration, error) {
if debug, ok := os.LookupEnv("RCTF_GOLF_DEBUG"); ok {
elapsed, err := time.ParseDuration(debug)
if err != nil {
return 0, fmt.Errorf("illegal debug elapsed time value: %w", err)
}
if int64(elapsed) < 0 {
return 0, fmt.Errorf("cannot set debug with negative elapsed time")
}
return elapsed, nil
}
clientConfig, err := c.GetClientConfig()
if err != nil {
return 0, err
}
start := unixMillisToTime(clientConfig.StartTime)
solves, err := c.GetChallengeSolves(chall, api.GetChallengeSolvesParams{
Limit: 1,
Offset: 0,
})
if err != nil {
return 0, err
}
var current time.Time
if len(solves) > 0 {
current = unixMillisToTime(solves[0].CreatedAt)
} else {
current = time.Now()
}
elapsed := current.Sub(start)
return elapsed, nil
}
func GetTime(baseURL string, chall string) (time.Duration, error) {
return calculateWithClient(api.NewClient(baseURL), chall)
}
func GetTimeWithClient(baseURL string, chall string, client *http.Client) (time.Duration, error) {
return calculateWithClient(api.NewClientWithHTTPClient(baseURL, client), chall)
}