-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
338 lines (325 loc) · 9.03 KB
/
query.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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/rumblefrog/go-a2s"
"go.etcd.io/bbolt"
"rkfg.me/ns2query/db"
)
const (
timeFormat = "2 Jan 2006 15:04:05 -0700"
)
func (srv *ns2server) serverStatus() *discordgo.MessageSend {
specSlots := srv.SpecSlots
playerSlots := srv.PlayerSlots - len(srv.players)
freeSlots := playerSlots + srv.SpecSlots
if freeSlots < specSlots {
specSlots = freeSlots
}
if playerSlots < 0 {
playerSlots = 0
}
msg := discordgo.MessageSend{Embed: &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s [%s]", srv.Name, srv.currentMap),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Players",
Value: fmt.Sprint(len(srv.players)),
Inline: true,
},
{
Name: "Player slots",
Value: fmt.Sprint(playerSlots),
Inline: true,
},
{
Name: "Spectator slots",
Value: fmt.Sprint(specSlots),
Inline: true,
},
},
Footer: &discordgo.MessageEmbedFooter{Text: fmt.Sprintf("Skill: %d", srv.avgSkill)},
},
}
if srv.failures > config.FailureLimit && srv.downSince != nil {
msg.Embed.Title = fmt.Sprintf("%s [%s] currently DOWN since %s", srv.Name, srv.currentMap, srv.downSince.Format(timeFormat))
}
playersCount := len(srv.players)
if playersCount < config.Seeding.AlmostFull {
msg.Embed.Color = 0x009900
} else if playersCount < srv.PlayerSlots {
msg.Embed.Color = 0xcc9900
} else if playersCount >= srv.PlayerSlots {
msg.Embed.Color = 0xff3300
}
if len(srv.regularNames) > 0 {
msg.Embed.Fields = append(msg.Embed.Fields, &discordgo.MessageEmbedField{
Name: "Regulars",
Value: strings.Join(srv.regularNames, ", "),
})
}
return &msg
}
func maybeMention(stateName string) string {
if roleID, ok := config.Seeding.PingRoles[stateName]; ok {
return fmt.Sprintf("<@&%s>", roleID)
}
return ""
}
func (srv *ns2server) maybeNotify() {
playersCount := len(srv.players)
newState := empty
if playersCount < config.Seeding.Seeding {
newState = empty
} else if playersCount < config.Seeding.AlmostFull {
newState = seedingstarted
} else if playersCount < srv.PlayerSlots {
newState = almostfull
} else if playersCount < srv.PlayerSlots+srv.SpecSlots {
newState = specsonly
} else {
newState = full
}
if newState > srv.serverState && newState <= srv.maxStateToMessage {
srv.lastStatePromotion = time.Now()
srv.serverState = newState
if srv.lastStateAnnounced != newState {
srv.lastStateAnnounced = newState
msg := srv.serverStatus()
switch newState {
case seedingstarted:
msg.Content = maybeMention("seeding")
msg.Embed.Description = "Seeding started! Players on the server: " + srv.playersString()
srv.maxStateToMessage = specsonly
sendChan <- message{MessageSend: msg}
case almostfull:
msg.Content = maybeMention("almost_full")
msg.Embed.Description = "Server is almost full!"
n := time.Now()
srv.sessionStart = &n
sendChan <- message{MessageSend: msg}
case specsonly:
msg.Content = maybeMention("full")
msg.Embed.Description = "Server is full but you can still make it!"
srv.maxStateToMessage = seedingstarted
sendChan <- message{MessageSend: msg}
}
}
} else {
if time.Since(srv.lastStatePromotion).Seconds() > float64(config.Seeding.Cooldown) {
srv.serverState = newState
if newState == empty {
// if the server goes empty we should allow seeding messages again
srv.lastStateAnnounced = empty
if config.Seeding.NotifyEmpty && srv.sessionStart != nil {
msg := srv.serverStatus()
msg.Embed.Description = fmt.Sprintf("Session is now over. Total time: %s", time.Since(*srv.sessionStart).Truncate(time.Second).String())
msg.Embed.Color = 0x666666
sendChan <- message{MessageSend: msg}
srv.sessionStart = nil
}
}
}
}
}
func (srv *ns2server) queryServer() error {
client, err := a2s.NewClient(srv.Address, a2s.TimeoutOption(config.QueryTimeout))
if err != nil {
return fmt.Errorf("error creating client: %w", err)
}
defer client.Close()
errorcount := 0
info, err := client.QueryInfo()
if err != nil {
log.Printf("server info query: %s", err)
errorcount++
} else {
srv.currentMap = info.Map
}
rules, err := client.QueryRules()
if err != nil {
log.Printf("rules query: %s", err)
errorcount++
} else {
srv.avgSkill = 0
avgSkillStr := rules.Rules["AverageSkill"]
if avgSkillStr != "nan" && avgSkillStr != "" {
avgSkill, err := strconv.ParseFloat(avgSkillStr, 32)
if err != nil {
log.Printf("parsing avg skill: %s", err)
} else {
srv.avgSkill = int(avgSkill)
}
}
}
playersInfo, err := client.QueryPlayer()
if err != nil {
log.Printf("player query: %s", err)
errorcount++
} else {
srv.players = srv.players[:0]
for _, p := range playersInfo.Players {
srv.players = append(srv.players, p.Name)
}
}
srv.maybeNotify()
if errorcount > 2 {
return fmt.Errorf("all server queries failed")
}
return nil
}
func (srv *ns2server) serverLoop() {
for {
err := srv.queryServer()
if err != nil {
log.Printf("Error: %s", err)
if neterr, ok := errors.Unwrap(err).(*net.OpError); ok && neterr.Op == "write" {
log.Println("Error during sending data (our IP changed?), restarting myself")
close(srv.restartChan)
return
}
srv.failures++
if srv.failures > config.FailureLimit && srv.downSince == nil {
now := time.Now().In(time.UTC)
srv.downSince = &now
sendChan <- message{MessageSend: &discordgo.MessageSend{Content: srv.formatDowntimeMsg(true)}}
}
} else {
if srv.failures > config.FailureLimit && srv.downSince != nil {
sendChan <- message{MessageSend: &discordgo.MessageSend{Content: srv.formatDowntimeMsg(false)}}
srv.downSince = nil
}
srv.failures = 0
}
select {
case <-time.After(config.QueryInterval):
case <-srv.restartChan:
log.Printf("Restart request received, stopping server polling: %s [%s]", srv.Name, srv.Address)
return
}
}
}
func (srv *ns2server) checkRegulars(ids []uint32) {
for k, v := range srv.regularTimeouts {
if v != nil && time.Now().After(*v) {
delete(srv.regularTimeouts, k)
}
}
bdb.View(func(t *bbolt.Tx) error {
steamBucket := db.NewSteamToDiscordBucket(t)
srv.regularNames = srv.regularNames[:0]
for _, id := range ids {
name, err := steamBucket.GetValue(id)
if err == nil {
srv.regularNames = append(srv.regularNames, name)
if _, exists := srv.newRegulars[id]; !exists {
if srv.regularTimeouts[id] == nil {
log.Printf("Adding regular to announce %s", name)
srv.newRegulars[id] = regular{id: id, name: name}
} else {
newTimeout := time.Now().Add(srv.RegularTimeout)
srv.regularTimeouts[id] = &newTimeout
}
}
}
}
return nil
})
}
func (srv *ns2server) getPlayerIDs() (result []uint32, err error) {
httpClient := http.Client{Timeout: time.Second * 3}
resp, err := httpClient.Get(srv.IDURL)
if err != nil {
return nil, fmt.Errorf("error querying %s: %w", srv.IDURL, err)
} else {
err = json.NewDecoder(resp.Body).Decode(&result)
}
return
}
func (srv *ns2server) announceRegulars() {
defer func() {
srv.newRegulars = map[uint32]regular{}
srv.announceScheduled = false
}()
ids, err := srv.getPlayerIDs()
if err != nil {
log.Printf("Error getting IDs: %s", err)
return
}
msg := ""
idmap := map[uint32]struct{}{} // players currently on the server
for _, id := range ids {
idmap[id] = struct{}{}
}
for id, r := range srv.newRegulars {
if _, ok := idmap[id]; ok { // only announce those who are playing
if msg != "" {
msg += ", "
}
msg += r.name
newTimeout := time.Now().Add(srv.RegularTimeout)
srv.regularTimeouts[id] = &newTimeout
}
}
if msg != "" {
channelID := srv.RegularChannelID
if channelID == "" {
channelID = config.ChannelID
}
sendChan <- message{MessageSend: &discordgo.MessageSend{
Embed: &discordgo.MessageEmbed{
Title: fmt.Sprintf("%s [%s]", srv.Name, srv.currentMap),
Footer: &discordgo.MessageEmbedFooter{Text: "Recently joined"},
Description: msg,
Color: 0x00aaff,
},
}, channelID: channelID}
}
}
func (srv *ns2server) idsLoop() {
var announceChan <-chan time.Time
srv.newRegulars = map[uint32]regular{}
for {
ids, err := srv.getPlayerIDs()
if err != nil {
log.Printf("Error decoding ids: %s", err)
continue
}
srv.checkRegulars(ids)
if len(srv.newRegulars) == 0 {
// make sure this never fires too early if there are no queued regulars
announceChan = time.After(srv.QueryIDInterval * 5)
} else {
if !srv.announceScheduled {
announceChan = time.After(srv.AnnounceDelay)
srv.announceScheduled = true
}
}
select {
case <-time.After(srv.QueryIDInterval):
case <-announceChan:
srv.announceRegulars()
case <-srv.restartChan:
log.Printf("Restart request received, stopping steam ids polling: %s [%s]", srv.Name, srv.Address)
return
}
}
}
func (srv *ns2server) query() {
srv.currentMap = "<unknown>"
srv.avgSkill = 0
srv.maxStateToMessage = full
srv.lastStateAnnounced = empty
go srv.serverLoop()
if srv.IDURL != "" {
go srv.idsLoop()
}
}