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
/
games.go
484 lines (455 loc) · 12.8 KB
/
games.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"image/png"
"log"
"net/http"
"regexp"
"slices"
_ "sort"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4"
)
type PlayerRating struct {
Elo int
Played int
Won int
Lost int
TimePlayed int
Account int
Category int
}
type Player struct {
Position int
Name string
Team int
Color int
Identity int
IdentityPubKey string
Usertype string
Rating *PlayerRating
Account int
DisplayName string
Props map[string]any
}
type Game struct {
ID int
Version string
Instance int
TimeStarted time.Time
TimeEnded *time.Time
GameTime *int
SettingScavs int
SettingAlliance int
SettingPower int
SettingBase int
MapName string
MapHash string
Mods string
Deleted bool
Hidden bool
Calculated bool
DebugTriggered bool
Players []Player
ReplayFound bool
DisplayCategory int
}
func DbGameDetailsHandler(w http.ResponseWriter, r *http.Request) {
requestedIdentifier := mux.Vars(r)["id"]
tid := time.Now()
err := tid.UnmarshalText([]byte(requestedIdentifier))
if err != nil {
gid, rerr := strconv.Atoi(requestedIdentifier)
if rerr == nil {
var suggestTID time.Time
derr := dbpool.QueryRow(r.Context(), "select time_started from games where id = $1", gid).Scan(&suggestTID)
if derr == nil {
stid, stiderr := suggestTID.MarshalText()
if stiderr == nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": template.HTML(`This looks like a number and not like a game start timestamp, however, database has game with such id: <a href="/games/` + string(stid) + `">link</a>`)})
return
}
}
}
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Invalid id: " + err.Error()})
return
}
req := `select
g.id, g.version, g.instance, g.time_started, g.time_ended, g.game_time,
g.setting_scavs, g.setting_alliance, g.setting_power, g.setting_base,
g.map_name, g.map_hash, g.mods, g.deleted, g.hidden, g.calculated, g.debug_triggered,
g.display_category,
jsonb_pretty(json_agg(json_build_object(
'Position', p.position,
'Name', i.name,
'Team', p.team,
'Usertype', p.usertype,
'Color', p.color,
'Identity', i.id,
'IdentityPubKey', encode(i.pkey, 'hex'),
'Account', a.id,
'DisplayName', coalesce(i.name, a.display_name),
'Rating', (select r from rating as r where r.category = g.display_category and r.account = i.account),
'Props', p.props
))::jsonb) as players
from games as g
join players as p on p.game = g.id
join identities as i on i.id = p.identity
left join accounts as a on a.id = i.account
where g.time_started = $1
group by g.id`
g := Game{}
g.Players = []Player{}
playersJSON := ""
err = dbpool.QueryRow(r.Context(), req, tid).Scan(&g.ID, &g.Version, &g.Instance, &g.TimeStarted, &g.TimeEnded, &g.GameTime,
&g.SettingScavs, &g.SettingAlliance, &g.SettingPower, &g.SettingBase,
&g.MapName, &g.MapHash, &g.Mods, &g.Deleted, &g.Hidden, &g.Calculated, &g.DebugTriggered, &g.DisplayCategory,
&playersJSON)
if err != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Database error: " + err.Error()})
return
}
err = json.Unmarshal([]byte(playersJSON), &g.Players)
if err != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Json unmarshal error: " + err.Error()})
return
}
g.ReplayFound = checkReplayExistsInStorage(r.Context(), g.ID)
// slices.SortFunc(gmsStage[0].Players, func(a Player, b Player) int {
// return a.Position - b.Position
// })
slotColors := [10]int{}
for _, v := range g.Players {
slotColors[v.Position] = v.Color
}
previewImage, err := getMapPreviewWithColors(g.MapHash, slotColors)
if err != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Preview rendering error: " + err.Error()})
return
}
previewImageBuf := bytes.NewBufferString("")
err = png.Encode(previewImageBuf, previewImage)
if err != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Encoding png err: " + err.Error()})
return
}
basicLayoutLookupRespond("gamedetails2", w, r, map[string]any{"Game": g, "Preview": base64.RawStdEncoding.EncodeToString(previewImageBuf.Bytes())})
}
func DbGamesHandler(w http.ResponseWriter, r *http.Request) {
dmapsc := make(chan []string)
var dmaps []string
dmapspresent := false
dtotalc := make(chan int)
var dtotal int
dtotalpresent := false
errc := make(chan error)
go func() {
var mapnames []string
derr := dbpool.QueryRow(r.Context(), `select array_agg(distinct map_name) from games where hidden = false and deleted = false;`).Scan(&mapnames)
if derr != nil && derr != pgx.ErrNoRows {
errc <- derr
return
}
dmapsc <- mapnames
}()
go func() {
var c int
derr := dbpool.QueryRow(r.Context(), `select count(*) from games where hidden = false and deleted = false;`).Scan(&c)
if derr != nil && derr != pgx.ErrNoRows {
errc <- derr
return
}
dtotalc <- c
}()
for !(dmapspresent && dtotalpresent) {
select {
case derr := <-errc:
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Database error: " + derr.Error()})
return
case dmaps = <-dmapsc:
dmapspresent = true
case dtotal = <-dtotalc:
dtotalpresent = true
}
}
basicLayoutLookupRespond("games2", w, r, map[string]any{"Total": dtotal, "Maps": dmaps})
}
func APIgetGames(_ http.ResponseWriter, r *http.Request) (int, any) {
reqLimit := parseQueryInt(r, "limit", 50)
if reqLimit > 200 {
reqLimit = 200
}
if reqLimit <= 0 {
reqLimit = 1
}
reqOffset := parseQueryInt(r, "offset", 0)
if reqOffset < 0 {
reqOffset = 0
}
reqSortOrder := parseQueryStringFiltered(r, "order", "desc", "asc")
fieldmappings := map[string]string{
"TimeStarted": "time_started",
"TimeEnded": "time_ended",
"ID": "id",
"MapName": "map_name",
"GameTime": "game_time",
}
reqSortField := parseQueryStringMapped(r, "sort", "time_started", fieldmappings)
reqFilterJ := parseQueryString(r, "filter", "")
reqFilterFields := map[string]string{}
reqDoFilters := false
if reqFilterJ != "" {
err := json.Unmarshal([]byte(reqFilterJ), &reqFilterFields)
if err == nil && len(reqFilterFields) > 0 {
reqDoFilters = true
}
}
whereplayerscase := ""
wherecase := "WHERE deleted = false AND hidden = false"
whereargs := []any{}
if isSuperadmin(r.Context(), sessionGetUsername(r)) {
wherecase = ""
}
playerPubKey := parseQueryString(r, "player", "")
if playerPubKey != "" {
whereplayerscase = "where $1 = encode(i.pkey, 'hex')"
whereargs = append(whereargs, playerPubKey)
if wherecase == "" {
wherecase = "WHERE g.id = any((select game from plf))"
} else {
wherecase += " AND g.id = any((select game from plf))"
}
}
if reqDoFilters {
val, ok := reqFilterFields["MapName"]
if ok {
whereargs = append(whereargs, val)
if wherecase == "" {
wherecase = "WHERE g.map_name = $1"
} else {
wherecase += fmt.Sprintf(" AND g.map_name = $%d", len(whereargs))
}
}
}
reqSearch := parseQueryString(r, "search", "")
ordercase := fmt.Sprintf("ORDER BY %s %s", reqSortField, reqSortOrder)
orderargs := []any{}
if reqSearch != "" {
orderargs = append(orderargs, reqSearch)
argnum := len(whereargs) + 1
ordercase = fmt.Sprintf("ORDER BY max(similarity(coalesce(i.name, a.display_name), $%d::text)) desc, %s %s", argnum, reqSortField, reqSortOrder)
}
limiter := fmt.Sprintf("LIMIT %d", reqLimit)
offset := fmt.Sprintf("OFFSET %d", reqOffset)
totalsc := make(chan int)
var totals int
totalspresent := false
totalsNoFilterc := make(chan int)
var totalsNoFilter int
totalsNoFilterpresent := false
growsc := make(chan []Game)
var gms []Game
gpresent := false
echan := make(chan error)
go func() {
var c int
req := `select count(*) from games where hidden = false and deleted = false;`
if isSuperadmin(r.Context(), sessionGetUsername(r)) {
req = `select count(*) from games;`
}
derr := dbpool.QueryRow(r.Context(), req).Scan(&c)
if derr != nil {
log.Println(derr)
echan <- derr
return
}
totalsNoFilterc <- c
}()
go func() {
var c int
req := `with plf as (
select *
from players as p
join identities as i on i.id = p.identity
left join accounts as a on a.id = i.account
` + whereplayerscase + `
)
select
count(distinct g.id)
from games as g
join players as p on p.game = g.id
join identities as i on i.id = p.identity
` + wherecase + `
;`
// log.Printf("req %s args %#+v", req, whereargs)
derr := dbpool.QueryRow(r.Context(), req, whereargs...).Scan(&c)
if derr != nil {
log.Println(derr)
echan <- derr
return
}
totalsc <- c
}()
go func() {
req := `with plf as (
select *
from players as p
join identities as i on i.id = p.identity
left join accounts as a on a.id = i.account
` + whereplayerscase + `
)
select
g.id, g.version, g.time_started, g.time_ended, g.game_time,
g.setting_scavs, g.setting_alliance, g.setting_power, g.setting_base,
g.map_name, g.map_hash, g.mods, g.deleted, g.hidden, g.calculated, g.debug_triggered,
g.display_category,
json_agg(json_build_object(
'Position', p.position,
'Name', i.name,
'Team', p.team,
'Usertype', p.usertype,
'Color', p.color,
'Identity', i.id,
'IdentityPubKey', encode(i.pkey, 'hex'),
'Account', a.id,
'DisplayName', coalesce(i.name, a.display_name),
'Rating', (select r from rating as r where r.category = g.display_category and r.account = i.account)
)) as players
from games as g
join players as p on p.game = g.id
join identities as i on i.id = p.identity
left join accounts as a on a.id = i.account
` + wherecase + `
group by g.id
` + ordercase + `
` + limiter + `
` + offset
args := append(whereargs, orderargs...)
// log.Printf("req %s args %#+v", req, args)
gmsStage := []Game{}
rows, err := dbpool.Query(r.Context(), req, args...)
if err != nil {
log.Println(err)
echan <- err
return
}
for rows.Next() {
g := Game{}
playersJSON := ""
err = rows.Scan(&g.ID, &g.Version, &g.TimeStarted, &g.TimeEnded, &g.GameTime,
&g.SettingScavs, &g.SettingAlliance, &g.SettingPower, &g.SettingBase,
&g.MapName, &g.MapHash, &g.Mods, &g.Deleted, &g.Hidden, &g.Calculated, &g.DebugTriggered, &g.DisplayCategory,
&playersJSON)
if err != nil {
echan <- err
return
}
g.Players = []Player{}
err = json.Unmarshal([]byte(playersJSON), &g.Players)
if err != nil {
echan <- err
return
}
slices.SortFunc(g.Players, func(a Player, b Player) int {
return a.Position - b.Position
})
gmsStage = append(gmsStage, g)
}
if err != nil {
echan <- err
return
}
growsc <- gmsStage
}()
for !(gpresent && totalspresent && totalsNoFilterpresent) {
select {
case derr := <-echan:
if derr == pgx.ErrNoRows {
return 200, []byte(`{"total": 0, "totalNotFiltered": 0, "rows": []}`)
}
return 500, derr
case gms = <-growsc:
gpresent = true
case totals = <-totalsc:
totalspresent = true
case totalsNoFilter = <-totalsNoFilterc:
totalsNoFilterpresent = true
}
}
return 200, map[string]any{
"total": totals,
"totalNotFiltered": totalsNoFilter,
"rows": gms,
}
}
func GameTimeToString(t any) string {
switch v := t.(type) {
case int:
return (time.Duration(int(v/1000)) * time.Second).String()
case *int:
if v == nil {
return "nil gametime"
}
return (time.Duration(int(*v/1000)) * time.Second).String()
default:
return "not float64 gametime"
}
}
func GameTimeToStringI(t any) string {
switch v := t.(type) {
case int:
return (time.Duration(v/1000) * time.Second).String()
case *int:
if v == nil {
return "nil gametime"
}
return (time.Duration(*v/1000) * time.Second).String()
default:
return "not int gametime"
}
}
//lint:ignore U1000 for later
func GameTimeInterToString(t any) string {
tt, k := t.(float64)
if k {
return (time.Duration(int(tt/1000)) * time.Second).String()
} else {
return "invalid"
}
}
//lint:ignore U1000 for later
func SecondsToString(t float64) string {
return (time.Duration(int(t)) * time.Second).String()
}
//lint:ignore U1000 for later
func SecondsInterToString(t any) string {
tt, k := t.(float64)
if k {
return (time.Duration(int(tt)) * time.Second).String()
} else {
return "invalid"
}
}
var GameDirRegex = regexp.MustCompile(`\./tmp/wz-(\d+)/`)
func GameDirToWeek(p string) int {
matches := GameDirRegex.FindStringSubmatch(p)
if len(matches) != 2 {
log.Println("No match for game directory")
return -1
}
num, err := strconv.Atoi(matches[1])
if err != nil {
log.Printf("Error atoi: %#+v %#+v", matches, err)
return -1
}
return num / (7 * 24 * 60 * 60)
}
func InstanceIDToWeek(num int) int {
return num / (7 * 24 * 60 * 60)
}