-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
372 lines (295 loc) · 9.31 KB
/
server.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
package botrest
import (
"net/http"
"os"
"strconv"
"time"
"emperror.dev/errors"
"github.com/mrbentarikau/pagst/bot"
"github.com/mrbentarikau/pagst/common"
"github.com/mrbentarikau/pagst/common/internalapi"
"github.com/jonas747/discordgo/v2"
"github.com/jonas747/dstate/v4"
"goji.io"
"goji.io/pat"
)
func RegisterPlugin() {
common.RegisterPlugin(&Plugin{})
}
var (
// _ bot.BotInitHandler = (*Plugin)(nil)
_ internalapi.InternalAPIPlugin = (*Plugin)(nil)
)
var serverLogger = common.GetFixedPrefixLogger("botrest_server")
// type BotRestPlugin interface {
// InitBotRestServer(mux *goji.Mux)
// }
type Plugin struct {
}
func (p *Plugin) PluginInfo() *common.PluginInfo {
return &common.PluginInfo{
Name: "BotREST",
SysName: "botrest",
Category: common.PluginCategoryCore,
}
}
func (p *Plugin) InitInternalAPIRoutes(muxer *goji.Mux) {
if !bot.Enabled {
// bot only routes
return
}
// muxer := goji.NewMux()
muxer.HandleFunc(pat.Get("/:guild/guild"), HandleGuild)
muxer.HandleFunc(pat.Get("/:guild/botmember"), HandleBotMember)
muxer.HandleFunc(pat.Get("/:guild/members"), HandleGetMembers)
muxer.HandleFunc(pat.Get("/:guild/membercolors"), HandleGetMemberColors)
muxer.HandleFunc(pat.Get("/:guild/onlinecount"), HandleGetOnlineCount)
muxer.HandleFunc(pat.Get("/:guild/channelperms/:channel"), HandleChannelPermissions)
muxer.HandleFunc(pat.Get("/node_status"), HandleNodeStatus)
muxer.HandleFunc(pat.Get("/shard_sessions"), HandleGetShardSessions)
muxer.HandleFunc(pat.Post("/shard/:shard/reconnect"), HandleReconnectShard)
// for _, p := range common.Plugins {
// if botRestPlugin, ok := p.(BotRestPlugin); ok {
// botRestPlugin.InitBotRestServer(muxer)
// }
// }
}
func HandleGuild(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
guild := bot.State.GetGuild(gId)
if guild == nil {
internalapi.ServerError(w, r, errors.New("Guild not found"))
return
}
internalapi.ServeJson(w, r, guild)
}
func HandleBotMember(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
member, err := bot.GetMember(gId, common.BotUser.ID)
if err != nil {
internalapi.ServerError(w, r, errors.New("Bot Member not found"))
return
}
internalapi.ServeJson(w, r, member.DgoMember())
}
func HandleGetMembers(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
uIDs, ok := r.URL.Query()["users"]
if !ok || len(uIDs) < 1 {
internalapi.ServerError(w, r, errors.New("No id's provided"))
return
}
if len(uIDs) > 100 {
internalapi.ServerError(w, r, errors.New("Too many ids provided"))
return
}
uIDsParsed := make([]int64, 0, len(uIDs))
for _, v := range uIDs {
parsed, _ := strconv.ParseInt(v, 10, 64)
uIDsParsed = append(uIDsParsed, parsed)
}
memberStates, _ := bot.GetMembers(gId, uIDsParsed...)
members := make([]*discordgo.Member, len(memberStates))
for i, v := range memberStates {
members[i] = v.DgoMember()
}
internalapi.ServeJson(w, r, members)
}
func HandleGetMemberColors(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
uIDs, ok := r.URL.Query()["users"]
if !ok || len(uIDs) < 1 {
internalapi.ServerError(w, r, errors.New("No id's provided"))
return
}
if len(uIDs) > 100 {
internalapi.ServerError(w, r, errors.New("Too many ids provided"))
return
}
guild := bot.State.GetGuild(gId)
if guild == nil {
internalapi.ServerError(w, r, errors.New("Guild not found"))
return
}
uIDsParsed := make([]int64, 0, len(uIDs))
for _, v := range uIDs {
parsed, _ := strconv.ParseInt(v, 10, 64)
uIDsParsed = append(uIDsParsed, parsed)
}
memberStates, _ := bot.GetMembers(gId, uIDsParsed...)
colors := make(map[string]int)
for _, ms := range memberStates {
// Find the highest role this user has with a color
for _, role := range guild.Roles {
if role.Color == 0 {
continue
}
if !common.ContainsInt64Slice(ms.Member.Roles, role.ID) {
continue
}
// Bingo
colors[strconv.FormatInt(ms.User.ID, 10)] = role.Color
break
}
}
internalapi.ServeJson(w, r, colors)
}
func HandleGetOnlineCount(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
count := 0
bot.State.IterateMembers(gId, func(chunk []*dstate.MemberState) bool {
count += len(chunk)
return true
})
internalapi.ServeJson(w, r, count)
}
func HandleChannelPermissions(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
cId, _ := strconv.ParseInt(pat.Param(r, "channel"), 10, 64)
guild := bot.State.GetGuild(gId)
if guild == nil {
internalapi.ServerError(w, r, errors.New("Guild not found"))
return
}
member, err := bot.GetMember(gId, common.BotUser.ID)
if err != nil {
internalapi.ServerError(w, r, errors.New("Could not find bot member"))
return
}
perms, err := guild.GetMemberPermissions(cId, member.User.ID, member.Member.Roles)
if err != nil {
internalapi.ServerError(w, r, errors.WithMessage(err, "Error calculating perms"))
return
}
internalapi.ServeJson(w, r, perms)
}
func HandlePing(w http.ResponseWriter, r *http.Request) {
internalapi.ServeJson(w, r, "pong")
}
type ShardStatus struct {
ShardID int `json:"shard_id"`
TotalEvents int64 `json:"total_events"`
EventsPerSecond float64 `json:"events_per_second"`
ConnStatus discordgo.GatewayStatus `json:"conn_status"`
LastHeartbeatSend time.Time `json:"last_heartbeat_send"`
LastHeartbeatAck time.Time `json:"last_heartbeat_ack"`
NumGuilds int
UnavailableGuilds int
}
func HandleNodeStatus(w http.ResponseWriter, r *http.Request) {
totalEventStats, periodEventStats := bot.EventLogger.GetStats()
numShards := bot.ShardManager.GetNumShards()
result := make([]*ShardStatus, 0, numShards)
processShards := bot.ReadyTracker.GetProcessShards()
// get general shard stats
for _, shardID := range processShards {
shard := bot.ShardManager.Sessions[shardID]
sumEvents := int64(0)
sumPeriodEvents := int64(0)
for j := range totalEventStats[shardID] {
sumEvents += totalEventStats[shardID][j]
sumPeriodEvents += periodEventStats[shardID][j]
}
if shard == nil || shard.GatewayManager == nil {
result[shardID] = &ShardStatus{ConnStatus: discordgo.GatewayStatusDisconnected}
continue
}
beat, ack := shard.GatewayManager.HeartBeatStats()
guilds := bot.State.GetShardGuilds(int64(shardID))
numUnavailable := 0
for _, g := range guilds {
if !g.Available {
numUnavailable++
}
}
result = append(result, &ShardStatus{
ShardID: shardID,
ConnStatus: shard.GatewayManager.Status(),
TotalEvents: sumEvents,
EventsPerSecond: float64(sumPeriodEvents) / bot.EventLoggerPeriodDuration.Seconds(),
LastHeartbeatSend: beat,
LastHeartbeatAck: ack,
NumGuilds: len(guilds),
UnavailableGuilds: numUnavailable,
})
}
hostname, _ := os.Hostname()
internalapi.ServeJson(w, r, &NodeStatus{
Host: hostname,
Shards: result,
ID: common.NodeID,
Uptime: time.Since(bot.Started),
})
}
type shardSessionInfo struct {
ShardID int
SessionID string
}
func HandleGetShardSessions(w http.ResponseWriter, r *http.Request) {
// numShards := bot.ShardManager.GetNumShards()
// result := make([]*ShardStatus, 0, numShards)
processShards := bot.ReadyTracker.GetProcessShards()
result := make([]*shardSessionInfo, 0)
// get general shard stats
for _, shardID := range processShards {
shard := bot.ShardManager.Sessions[shardID]
sessionID, _ := shard.GatewayManager.GetSessionInfo()
result = append(result, &shardSessionInfo{
ShardID: shardID,
SessionID: sessionID,
})
}
internalapi.ServeJson(w, r, result)
}
func HandleReconnectShard(w http.ResponseWriter, r *http.Request) {
sID := pat.Param(r, "shard")
forceReidentify := r.FormValue("reidentify") == "1"
if sID == "*" {
go RestartAll(forceReidentify)
internalapi.ServeJson(w, r, "ok")
return
}
parsed, _ := strconv.ParseInt(sID, 10, 32)
shardcount := bot.ShardManager.GetNumShards()
if parsed < 0 || int(parsed) >= shardcount {
internalapi.ServerError(w, r, errors.New("Unknown shard"))
return
}
if forceReidentify {
err := bot.ShardManager.Sessions[parsed].Close()
if err != nil {
internalapi.ServerError(w, r, errors.New("failed stopping shard: "+err.Error()))
return
}
}
sessionID, sequence := bot.ShardManager.Sessions[parsed].GatewayManager.GetSessionInfo()
var err error
if forceReidentify {
bot.ShardManager.Sessions[parsed].GatewayManager.SetSessionInfo("", 0)
err = bot.ShardManager.Sessions[parsed].GatewayManager.Open()
} else {
err = bot.ShardManager.Sessions[parsed].GatewayManager.Reconnect(forceReidentify)
}
if err != nil {
internalapi.ServerError(w, r, errors.WithMessage(err, "Reconnect"))
return
}
internalapi.ServeJson(w, r, ReconnectResponse{
SessionID: sessionID,
Sequence: sequence,
})
}
type ReconnectResponse struct {
SessionID string `json:"session_id"`
Sequence int64 `json:"sequence"`
}
func RestartAll(reidentify bool) {
serverLogger.Println("Reconnecting all shards re-identify:", reidentify)
for _, v := range bot.ShardManager.Sessions {
err := v.GatewayManager.Reconnect(reidentify)
if err != nil {
serverLogger.WithError(err).Error("Failed reconnecting shard")
}
time.Sleep(time.Second * 5)
}
}