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
/
players.go
314 lines (306 loc) · 10.2 KB
/
players.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
package main
import (
"context"
"encoding/hex"
"errors"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/jackc/pgx/v4"
)
type PlayerLeaderboard struct {
ID int
Name string
Hash string
Elo int
Elo2 int
Autoplayed int
Autolost int
Autowon int
Userid int
Timeplayed int `json:",omitempty"`
Rwon float64 `json:",omitempty"`
Rlost float64 `json:",omitempty"`
LastGame int `json:",omitempty"`
}
func PlayersHandler(w http.ResponseWriter, r *http.Request) {
identSpecifier, err := hex.DecodeString(mux.Vars(r)["id"])
if err != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Incorrectly formatted identity key or hash (please ensure it has even number of characters when specifying beginning of sha256 hash of public key)"})
return
}
var identID int
var identName string
var identPubKey string
var identHash string
err = dbpool.QueryRow(r.Context(), `select id, name, encode(pkey, 'hex'), hash from identities where pkey = $1 or hash ^@ encode($1, 'hex')`, identSpecifier).Scan(&identID, &identName, &identPubKey, &identHash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Player not found, identity in url can be hex encoded public key or it's sha256 hash"})
return
}
if !errors.Is(err, context.Canceled) {
log.Println(err)
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "request error"})
return
}
}
basicLayoutLookupRespond("player", w, r, map[string]any{
"Player": map[string]any{
"Name": identName,
"IdentityPubKey": identPubKey,
"IdentityHash": identHash,
},
})
// var pp PlayerLeaderboard
// pp.ID = pid
// type renameEntry struct {
// Oldname string
// Newname string
// Time string
// }
// renames := []renameEntry{}
// ChartGamesByPlayercount := newSC("Games by player count", "Game count", "Player count")
// ChartGamesByBaselevel := newSC("Games by base level", "Game count", "Base level")
// ChartGamesByAlliances := newSC("Games by alliance type (2x2+)", "Game count", "Alliance type")
// ChartGamesByScav := newSC("Games by scavengers", "Game count", "Scavengers")
// RatingHistory := map[string]eloHist{}
// ResearchClassificationTotal := map[string]int{}
// ResearchClassificationRecent := map[string]int{}
// AltCount := 0
// err = dbpool.QueryRow(r.Context(), `
// SELECT name, hash, elo, elo2, autoplayed, autolost, autowon, coalesce((SELECT id FROM accounts WHERE players.id = accounts.wzprofile2), -1)
// FROM players WHERE id = $1`, pid).Scan(&pp.Name, &pp.Hash, &pp.Elo, &pp.Elo2, &pp.Autoplayed, &pp.Autolost, &pp.Autowon, &pp.Userid)
// if err != nil {
// if err == pgx.ErrNoRows {
// basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Player not found"})
// } else if r.Context().Err() == context.Canceled {
// return
// } else {
// basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Database query error: " + err.Error()})
// }
// return
// }
// err = RequestMultiple(func() error {
// var o, n, t string
// _, err := dbpool.QueryFunc(r.Context(), `select oldname, newname, "time"::text from plrenames where id = $1 order by "time" desc;`,
// []any{pid}, []any{&o, &n, &t}, func(_ pgx.QueryFuncRow) error {
// renames = append(renames, renameEntry{Oldname: o, Newname: n, Time: t})
// return nil
// })
// return err
// }, func() error {
// return dbpool.QueryRow(r.Context(), `select coalesce(avg(p.elo2), 0)
// from games as g
// cross join unnest(g.players) as up
// join players as p on up = p.id
// where
// array[$1::int] <@ g.players and
// calculated = true and
// finished = true and
// g.usertype[array_position(g.players, $1)] = 'winner' and
// g.usertype[array_position(g.players, up)] = 'loser' and
// ratingdiff[1] != 0`, pid).Scan(&pp.Rwon)
// }, func() error {
// return dbpool.QueryRow(r.Context(), `select coalesce(avg(p.elo2), 0)
// from games as g
// cross join unnest(g.players) as up
// join players as p on up = p.id
// where
// array[$1::int] <@ g.players and
// calculated = true and
// finished = true and
// g.usertype[array_position(g.players, $1)] = 'loser' and
// g.usertype[array_position(g.players, up)] = 'winner' and
// ratingdiff[1] != 0`, pid).Scan(&pp.Rlost)
// }, func() error {
// var k, c int
// var ut string
// _, err := dbpool.QueryFunc(r.Context(),
// `select array_position(players, -1)-1 as pc, coalesce(usertype[array_position(players, $1)], '') as ut, count(id) as c
// from games
// where
// array[$1::int] <@ players and
// calculated = true and
// finished = true
// group by pc, ut
// order by pc, ut`,
// []any{pid}, []any{&k, &ut, &c},
// func(_ pgx.QueryFuncRow) error {
// switch ut {
// case "loser":
// ChartGamesByPlayercount.appendToColumn(fmt.Sprintf("%dp", k), "Lost", chartSCcolorLost, c)
// case "winner":
// ChartGamesByPlayercount.appendToColumn(fmt.Sprintf("%dp", k), "Won", chartSCcolorWon, c)
// }
// return nil
// })
// return err
// }, func() error {
// var k, c int
// var ut string
// _, err := dbpool.QueryFunc(r.Context(),
// `select baselevel, usertype[array_position(players, $1)] as ut, count(id)
// from games
// where
// array[$1::int] <@ players and
// calculated = true and
// finished = true
// group by baselevel, ut
// order by baselevel, ut`,
// []any{pid}, []any{&k, &ut, &c},
// func(_ pgx.QueryFuncRow) error {
// switch ut {
// case "loser":
// ChartGamesByBaselevel.appendToColumn(fmt.Sprintf(`<img class="icons icons-base%d">`, k), "Lost", chartSCcolorLost, c)
// case "winner":
// ChartGamesByBaselevel.appendToColumn(fmt.Sprintf(`<img class="icons icons-base%d">`, k), "Won", chartSCcolorWon, c)
// }
// return nil
// })
// return err
// }, func() error {
// var k, c int
// _, err := dbpool.QueryFunc(r.Context(),
// `select alliancetype, count(id)
// from games
// where
// array[$1::int] <@ players and
// calculated = true and
// finished = true and
// array_position(players, -1)-1 > 2
// group by alliancetype`,
// []any{pid}, []any{&k, &c},
// func(_ pgx.QueryFuncRow) error {
// if k == 1 {
// return nil
// }
// ChartGamesByAlliances.appendToColumn(fmt.Sprintf(`<img class="icons icons-alliance%d">`, templatesAllianceToClassI(k)), "", chartSCcolorNeutral, c)
// return nil
// })
// return err
// }, func() error {
// var k, c int
// _, err := dbpool.QueryFunc(r.Context(),
// `select scavs::int, count(id)
// from games
// where
// array[$1::int] <@ players and
// calculated = true and
// finished = true
// group by scavs`,
// []any{pid}, []any{&k, &c},
// func(_ pgx.QueryFuncRow) error {
// ChartGamesByScav.appendToColumn(fmt.Sprintf(`<img class="icons icons-scav%d">`, k), "", chartSCcolorNeutral, c)
// return nil
// })
// return err
// }, func() error {
// var err error
// ResearchClassificationTotal, ResearchClassificationRecent, err = getPlayerClassifications(pid)
// return err
// }, func() error {
// var err error
// RatingHistory, err = getRatingHistory(pid)
// return err
// }, func() error {
// return dbpool.QueryRow(r.Context(), `select count(*) from players where hash = any((select distinct hash from chatlog where ip = any((select distinct ip from chatlog where hash = any((select hash from players where hash = any((select distinct hash from chatlog where ip = any((select distinct ip from chatlog where hash = $1)))) order by id desc)) order by ip desc))));`, pp.Hash).Scan(&AltCount)
// })
// if err != nil {
// if err == pgx.ErrNoRows {
// basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Player not found"})
// } else if r.Context().Err() == context.Canceled {
// return
// } else {
// basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msgred": true, "msg": "Database query error: " + err.Error()})
// }
// return
// }
// basicLayoutLookupRespond("player", w, r, map[string]any{
// "Player": pp,
// "Renames": renames,
// "ChartGamesByPlayercount": ChartGamesByPlayercount.calcTotals(),
// "ChartGamesByBaselevel": ChartGamesByBaselevel.calcTotals(),
// "ChartGamesByAlliances": ChartGamesByAlliances.calcTotals(),
// "ChartGamesByScav": ChartGamesByScav.calcTotals(),
// "RatingHistory": RatingHistory,
// "ResearchClassificationTotal": ResearchClassificationTotal,
// "ResearchClassificationRecent": ResearchClassificationRecent,
// "AltCount": AltCount,
// })
}
type eloHist struct {
Rating int
}
func getRatingHistory(pid int) (map[string]eloHist, error) {
rows, derr := dbpool.Query(context.Background(),
`SELECT
id,
coalesce(ratingdiff, '{0,0,0,0,0,0,0,0,0,0,0}'),
to_char(timestarted, 'YYYY-MM-DD HH24:MI'),
players
FROM games
where
array[$1::int] <@ players
AND finished = true
AND calculated = true
AND hidden = false
AND deleted = false
order by timestarted asc`, pid)
if derr != nil {
if derr == pgx.ErrNoRows {
return nil, nil
}
return nil, derr
}
defer rows.Close()
h := map[string]eloHist{}
prevts := ""
for rows.Next() {
var gid int
var rdiff []int
var timestarted string
var players []int
err := rows.Scan(&gid, &rdiff, ×tarted, &players)
if err != nil {
return nil, err
}
k := -1
for i, p := range players {
if p == pid {
k = i
break
}
}
if k < 0 || k >= len(rdiff) {
log.Printf("Game %d is broken (k %d) players %v diffs %v", gid, k, players, rdiff)
continue
}
rDiff := rdiff[k]
if prevts == "" {
h[timestarted] = eloHist{
Rating: 1400 + rDiff,
}
} else {
ph := h[prevts]
h[timestarted] = eloHist{
Rating: ph.Rating + rDiff,
}
}
prevts = timestarted
}
return h, nil
}
func APIgetElodiffChartPlayer(_ http.ResponseWriter, r *http.Request) (int, any) {
params := mux.Vars(r)
pid, err := strconv.Atoi(params["pid"])
if err != nil {
return 400, nil
}
h, err := getRatingHistory(pid)
if err != nil {
return 500, err
}
return 200, h
}