-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
acsr.go
281 lines (210 loc) · 6.01 KB
/
acsr.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package servermanager
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/gob"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"github.com/sirupsen/logrus"
)
var acsrURL = "https://acsr.assettocorsaservers.com"
func init() {
gob.Register(Championship{})
if acsrOverrideURL := os.Getenv("ACSR_URL"); acsrOverrideURL != "" {
acsrURL = acsrOverrideURL
}
}
type ACSRClient struct {
Enabled bool
AccountID string
APIKey string
}
func NewACSRClient(accountID, apiKey string, enabled bool) *ACSRClient {
return &ACSRClient{
AccountID: accountID,
APIKey: apiKey,
Enabled: enabled && Premium(),
}
}
// Sends a championship to ACSR, called OnEndSession and when a championship is created
func (a *ACSRClient) SendChampionship(inChampionship Championship) {
if !a.Enabled || len(inChampionship.Events) == 0 {
return
}
if !baseURLIsSet() {
logrus.Errorf("Cannot send Championship to ACSR - no baseURL is set.")
return
}
if !baseURLIsValid() {
logrus.Errorf("Cannot send Championship to ACSR - baseURL is not valid.")
return
}
// championships are cloned before being sent to ACSR. this prevents any issues with pointers within the
// struct being erroneously modified in our original championship struct.
championship, err := cloneChampionship(inChampionship)
if err != nil {
logrus.WithError(err).Errorf("Cannot clone Championship for ACSR")
return
}
championship.Events = ExtractRaceWeekendSessionsIntoIndividualEvents(championship.Events)
for _, event := range championship.Events {
for _, session := range event.Sessions {
if session.Completed() {
session.Results.Anonymize()
}
}
}
geoIP, err := geoIP()
if err != nil {
logrus.WithError(err).Error("Could not get GeoIP data for server")
return
}
resp, err := a.send("/submit-result", championship, map[string]string{
"baseurl": config.HTTP.BaseURL,
"geoip": geoIP.CountryName,
})
if err != nil {
logrus.WithError(err).Error("could not submit championship to ACSR")
return
}
defer resp.Body.Close()
if resp.StatusCode < 400 {
logrus.Debugf("acsr: updated championship: %s sent", championship.ID.String())
} else {
logrus.Errorf("acsr: sent championship: %s was not accepted. (status: %d) Please check your credentials.", championship.ID.String(), resp.StatusCode)
}
}
func (a *ACSRClient) send(url string, data interface{}, queryParams map[string]string) (*http.Response, error) {
output, err := json.Marshal(data)
if err != nil {
return nil, err
}
key, err := hex.DecodeString(a.APIKey)
if err != nil {
return nil, err
}
encryptedData, err := encrypt(output, key)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", acsrURL+url, bytes.NewBuffer(encryptedData))
if err != nil {
return nil, err
}
q := req.URL.Query()
for key, val := range queryParams {
q.Add(key, val)
}
q.Add("guid", a.AccountID)
req.URL.RawQuery = q.Encode()
req.Header.Set("Content-Type", "application/json")
return http.DefaultClient.Do(req)
}
type ACSRDriverRatingRequest struct {
GUIDs []string `json:"guids"`
}
type ACSRDriverRating struct {
DriverID uint `json:"driver_id"`
SkillRatingGrade string `json:"skill_rating_grade"`
SkillRating float64 `json:"skill_rating"`
SafetyRating int `json:"safety_rating"`
NumEvents int `json:"num_events"`
IsProvisional bool `json:"is_provisional"`
}
func (a *ACSRClient) GetRating(guids ...string) (map[string]*ACSRDriverRating, error) {
data := ACSRDriverRatingRequest{}
anonymisedGUIDs := make(map[string]string)
for _, guid := range guids {
anonymised := AnonymiseDriverGUID(guid)
anonymisedGUIDs[anonymised] = guid
data.GUIDs = append(data.GUIDs, anonymised)
}
resp, err := a.send("/api/ratings", data, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("servermanager: acsr request responded with a bad status code (%d). check your credentials", resp.StatusCode)
}
var anonymisedOut map[string]*ACSRDriverRating
if err := json.NewDecoder(resp.Body).Decode(&anonymisedOut); err != nil {
return nil, err
}
normalGUIDMap := make(map[string]*ACSRDriverRating)
for anonymisedGUID, data := range anonymisedOut {
if guid, ok := anonymisedGUIDs[anonymisedGUID]; ok {
normalGUIDMap[guid] = data
}
}
return normalGUIDMap, nil
}
type ACSRRatingRanges struct {
Name string `json:"name"`
RatingType string `json:"rating_type"`
Count int `json:"count"`
Min int `json:"min"`
Max int `json:"max"`
}
func (a *ACSRClient) GetRanges() ([]*ACSRRatingRanges, error) {
resp, err := a.send("/api/ranges", nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("servermanager: acsr request responded with a bad status code (%d). check your credentials", resp.StatusCode)
}
var out []*ACSRRatingRanges
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, err
}
return out, nil
}
// cloneChampionship takes a Championship and returns a complete new copy of it.
func cloneChampionship(c Championship) (out Championship, err error) {
buf := new(bytes.Buffer)
for _, event := range c.Events {
if event.IsRaceWeekend() {
event.RaceWeekend.Championship = nil
}
}
err = gob.NewEncoder(buf).Encode(c)
if err != nil {
return out, err
}
err = gob.NewDecoder(buf).Decode(&out)
return out, err
}
func encrypt(data, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, data, nil), nil
}
func baseURLIsValid() bool {
if !baseURLIsSet() {
return false
}
_, err := url.Parse(config.HTTP.BaseURL)
return err == nil
}
func baseURLIsSet() bool {
return config != nil && config.HTTP.BaseURL != ""
}