This repository has been archived by the owner on Oct 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
392 lines (373 loc) · 9.63 KB
/
api.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package main
import (
"bytes"
"context"
"crypto/md5"
"encoding/binary"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"slices"
"sort"
"strconv"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4"
"github.com/maxsupermanhd/go-wz/packet"
"github.com/maxsupermanhd/go-wz/replay"
"github.com/maxsupermanhd/go-wz/wznet"
)
func APIcall(c func(http.ResponseWriter, *http.Request) (int, any)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
code, content := c(w, r)
if code <= 0 {
return
}
var response []byte
var err error
if content != nil {
if bcontent, ok := content.([]byte); ok {
if json.Valid(bcontent) {
response = bcontent
}
} else if econtent, ok := content.(error); ok {
log.Printf("Error inside handler [%v]: %v", r.URL.Path, econtent.Error())
response, err = json.Marshal(map[string]any{"error": econtent.Error()})
if err != nil {
code = 500
response = []byte(`{"error": "Failed to marshal json response"}`)
log.Println("Failed to marshal json content: ", err.Error())
}
} else {
response, err = json.Marshal(content)
if err != nil {
code = 500
response = []byte(`{"error": "Failed to marshal json response"}`)
log.Println("Failed to marshal json content: ", err.Error())
}
}
}
w.Header().Set("Access-Control-Allow-Origin", "https://wz2100-autohost.net https://dev.wz2100-autohost.net")
if len(response) > 0 {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(response)+1))
w.WriteHeader(code)
w.Write(response)
w.Write([]byte("\n"))
} else {
w.WriteHeader(code)
}
}
}
func APItryReachBackend(w http.ResponseWriter, _ *http.Request) {
s, m := RequestStatus()
io.WriteString(w, m)
if s {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
}
}
func APIgetGraphData(_ http.ResponseWriter, r *http.Request) (int, any) {
params := mux.Vars(r)
gids := params["gid"]
gid, err := strconv.Atoi(gids)
if err != nil {
return 500, err
}
var j string
err = dbpool.QueryRow(r.Context(), `SELECT coalesce(graphs, 'null') FROM games WHERE id = $1;`, gid).Scan(&j)
if err != nil {
if err == pgx.ErrNoRows {
return 204, nil
}
return 500, err
}
if j == "null" {
return 204, nil
}
frames := []map[string]any{}
err = json.Unmarshal([]byte(j), &frames)
if err != nil {
return 500, err
}
sort.Slice(frames, func(i, j int) bool {
gti, ok := frames[i]["gameTime"].(float64)
if !ok {
return true
}
gtj, ok := frames[j]["gameTime"].(float64)
if !ok {
return true
}
return gti < gtj
})
avg := []float64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
avgw := float64(60)
var rpl *replay.Replay
replaycontent, err := getReplayFromStorage(r.Context(), gid)
if err != nil {
if err != errReplayNotFound {
return 500, err
}
} else {
rpl, err = replay.ReadReplay(bytes.NewBuffer(replaycontent))
if err != nil {
return 500, err
}
if rpl == nil {
return 500, errors.New("replay is nil")
}
}
rplPktIndex := 0
prevOrderFp := make([]int32, 32)
calcDroidCs := func(droids []uint32) byte {
slices.Sort(droids)
buf := bytes.NewBufferString("")
binary.Write(buf, binary.NativeEndian, droids)
return md5.Sum(buf.Bytes())[0]
}
for i, v := range frames {
if rpl != nil {
rplPktCount := make([]int, rpl.Settings.GameOptions.Game.MaxPlayers)
gt, ok := v["gameTime"].(float64)
if ok {
rplcountloop:
for ; rplPktIndex < len(rpl.Messages); rplPktIndex++ {
switch p := rpl.Messages[rplPktIndex].NetPacket.(type) {
case packet.PkGameGameTime:
if p.GameTime >= uint32(gt) {
break rplcountloop
}
case packet.PkGameDroidInfo:
if p.SecOrder == wznet.DSO_RETURN_TO_LOC {
continue
}
if p.Order == wznet.DORDER_NONE {
continue
}
pos := rpl.Settings.GameOptions.NetplayPlayers[p.Player].Position
currOrderFp := (p.CoordX ^ p.CoordY) + int32(calcDroidCs(p.Droids))
if prevOrderFp[pos] != currOrderFp {
rplPktCount[pos]++
prevOrderFp[pos] = currOrderFp
}
case packet.PkGameResearchStatus:
rplPktCount[rpl.Settings.GameOptions.NetplayPlayers[p.Player].Position]++
}
}
}
v["replayPackets"] = rplPktCount
rplPktSum := make([]int, rpl.Settings.GameOptions.Game.MaxPlayers)
for i2 := i - 60; i2 != i; i2++ {
if i2 < 0 {
continue
}
oldPktCount := frames[i2]["replayPackets"].([]int)
for i3, v3 := range oldPktCount {
rplPktSum[i3] += v3
}
}
v["replayPacketsP60t"] = rplPktSum
} else {
v["replayPackets"] = []int{}
v["replayPacketsP60t"] = []int{}
}
val := []int{}
v["labActivityP60t"] = val
if i == 0 {
continue
}
prfs, ok := v["recentResearchPerformance"].([]any)
if !ok {
continue
}
pots, ok := v["recentResearchPotential"].([]any)
if !ok {
continue
}
prevPrfs, ok := frames[i-1]["recentResearchPerformance"].([]any)
if !ok {
continue
}
prevPots, ok := frames[i-1]["recentResearchPotential"].([]any)
if !ok {
continue
}
for p := 0; p < min(len(prfs), len(pots)); p++ {
prf, ok := prfs[p].(float64)
if !ok {
continue
}
pot, ok := pots[p].(float64)
if !ok {
continue
}
prevPrf, ok := prevPrfs[p].(float64)
if !ok {
continue
}
prevPot, ok := prevPots[p].(float64)
if !ok {
continue
}
navg := int(0)
if pot > 1 && prf > 1 && prevPrf > 1 && prevPot > 1 {
avg[p] -= avg[p] / avgw
nval := (prf - prevPrf) / (pot - prevPot)
if pot == prevPot {
nval = 0
}
avg[p] += (100 * nval) / avgw
navg = int(avg[p])
}
val = append(val, navg)
}
v["labActivityP60t"] = val
}
return 200, frames
}
func getDatesGraphData(ctx context.Context, interval string) ([]map[string]int, error) {
rows, derr := dbpool.Query(ctx, `SELECT date_trunc($1, g.time_started)::text || '+00', count(g.time_started)
FROM games as g
WHERE g.time_started > now() - '1 year 7 days'::interval
GROUP BY date_trunc($1, g.time_started)
ORDER BY date_trunc($1, g.time_started)`, interval)
if derr != nil {
if derr == pgx.ErrNoRows {
return []map[string]int{}, nil
}
return []map[string]int{}, derr
}
defer rows.Close()
ret := []map[string]int{}
for rows.Next() {
var d string
var c int
err := rows.Scan(&d, &c)
if err != nil {
return []map[string]int{}, err
}
ret = append(ret, map[string]int{d: c})
}
return ret, nil
}
func APIgetDatesGraphData(_ http.ResponseWriter, r *http.Request) (int, any) {
ret, err := getDatesGraphData(r.Context(), mux.Vars(r)["interval"])
if err != nil {
return 500, err
}
return 200, ret
}
func APIgetDayAverageByHour(_ http.ResponseWriter, r *http.Request) (int, any) {
rows, derr := dbpool.Query(r.Context(), `select count(gg) as c, extract('hour' from time_started) as d from games as gg group by d order by d`)
if derr != nil {
return 500, derr
}
defer rows.Close()
re := make(map[int]int)
for rows.Next() {
var d, c int
err := rows.Scan(&c, &d)
if err != nil {
return 500, err
}
re[d] = c
}
return 200, re
}
func APIgetUniquePlayersPerDay(_ http.ResponseWriter, r *http.Request) (int, any) {
return http.StatusNotImplemented, nil
rows, derr := dbpool.Query(r.Context(),
`SELECT d::text, count(r.p)
FROM (SELECT distinct unnest(gg.players) as p, date_trunc('day', gg.timestarted) AS d FROM games AS gg) as r
WHERE d > now() - '1 year 7 days'::interval
GROUP BY d
ORDER BY d DESC`)
if derr != nil {
if derr == pgx.ErrNoRows {
return 204, nil
}
return 500, derr
}
defer rows.Close()
re := make(map[string]int)
for rows.Next() {
var d string
var c int
err := rows.Scan(&d, &c)
if err != nil {
return 500, err
}
re[d] = c
}
return 200, re
}
func APIgetMapNameCount(_ http.ResponseWriter, r *http.Request) (int, any) {
rows, derr := dbpool.Query(r.Context(), `select map_name, count(*) as c from games group by map_name order by c desc limit 30`)
if derr != nil {
return 500, derr
}
defer rows.Close()
re := make(map[string]int)
for rows.Next() {
var c int
var n string
err := rows.Scan(&n, &c)
if err != nil {
return 500, derr
}
re[n] = c
}
return 200, re
}
func APIgetReplayFile(w http.ResponseWriter, r *http.Request) (int, any) {
params := mux.Vars(r)
gids := params["gid"]
gid, err := strconv.Atoi(gids)
if err != nil {
return 400, nil
}
replaycontent, err := getReplayFromStorage(r.Context(), gid)
if err == nil {
log.Println("Serving replay from replay storage, gid ", gids)
w.Header().Set("Content-Disposition", "attachment; filename=\"autohoster-game-"+gids+".wzrp\"")
w.Header().Set("Content-Length", strconv.Itoa(len(replaycontent)))
w.Write(replaycontent)
return -1, nil
} else if err != errReplayNotFound {
log.Printf("ERROR getting replay from storage: %v game id is %d", err, gid)
return 500, err
}
return 204, nil
}
func APIgetClassChartGame(_ http.ResponseWriter, r *http.Request) (int, any) {
params := mux.Vars(r)
gid := params["gid"]
reslog := "0"
derr := dbpool.QueryRow(r.Context(), `SELECT coalesce(research_log, '{}') FROM games WHERE id = $1;`, gid).Scan(&reslog)
if derr != nil {
if derr == pgx.ErrNoRows {
return 204, nil
}
return 500, derr
}
if reslog == "-1" {
return 204, nil
}
var resl []resEntry
err := json.Unmarshal([]byte(reslog), &resl)
if err != nil {
return 500, err
}
return 200, CountClassification(resl)
}
func APIgetRatingCategories(_ http.ResponseWriter, r *http.Request) (int, any) {
var ret []byte
err := dbpool.QueryRow(r.Context(), `select json_agg(rating_categories) from rating_categories`).Scan(&ret)
if err != nil {
return 500, err
}
return 200, ret
}