-
Notifications
You must be signed in to change notification settings - Fork 4
/
node.go
378 lines (325 loc) · 8.44 KB
/
node.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
package lavalink
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
type NodeStatus string
// Indicates how far along the client is to connecting
const (
Connecting NodeStatus = "CONNECTING"
Connected NodeStatus = "CONNECTED"
Reconnecting NodeStatus = "RECONNECTING"
Disconnected NodeStatus = "DISCONNECTED"
)
type Node interface {
Lavalink() Lavalink
Send(cmd OpCommand) error
ConfigureResuming(key string, timeoutSeconds int) error
Open(ctx context.Context) error
Close()
Name() string
RestClient() RestClient
RestURL() string
Config() NodeConfig
Stats() *Stats
Status() NodeStatus
}
type NodeConfig struct {
Name string `json:"name"`
Host string `json:"host"`
Port string `json:"port"`
Password string `json:"password"`
Secure bool `json:"secure"`
ResumingKey string `json:"resumingKey"`
}
type nodeImpl struct {
config NodeConfig
lavalink Lavalink
conn *websocket.Conn
status NodeStatus
statusMu sync.Mutex
stats *Stats
available bool
restClient RestClient
}
func (n *nodeImpl) RestURL() string {
scheme := "http"
if n.config.Secure {
scheme += "s"
}
return fmt.Sprintf("%s://%s:%s", scheme, n.config.Host, n.config.Port)
}
func (n *nodeImpl) Lavalink() Lavalink {
return n.lavalink
}
func (n *nodeImpl) Config() NodeConfig {
return n.config
}
func (n *nodeImpl) RestClient() RestClient {
return n.restClient
}
func (n *nodeImpl) Name() string {
return n.config.Name
}
func (n *nodeImpl) Send(cmd OpCommand) error {
n.statusMu.Lock()
defer n.statusMu.Unlock()
if n.status != Connected {
return fmt.Errorf("node is %s and cannot send a cmd to the node", n.status)
}
data, err := json.Marshal(cmd)
if err != nil {
return err
}
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(PluginEventHandler); ok {
plugin.OnNodeMessageOut(n, data)
}
}
if err = n.conn.WriteMessage(websocket.TextMessage, data); err != nil {
return fmt.Errorf("error while sending to lavalink websocket: %w", err)
}
return nil
}
func (n *nodeImpl) ConfigureResuming(key string, timeoutSeconds int) error {
return n.Send(ConfigureResumingCommand{
Key: key,
Timeout: timeoutSeconds,
})
}
func (n *nodeImpl) Status() NodeStatus {
return n.status
}
func (n *nodeImpl) Stats() *Stats {
return n.stats
}
func (n *nodeImpl) reconnect() error {
n.statusMu.Lock()
defer n.statusMu.Unlock()
n.status = Reconnecting
if err := n.open(context.TODO(), 0); err != nil {
n.status = Disconnected
return err
}
n.status = Connected
return nil
}
func (n *nodeImpl) listen() {
defer func() {
n.lavalink.Logger().Info("shut down listen goroutine")
}()
for {
if n.conn == nil {
return
}
_, data, err := n.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
n.lavalink.Logger().Error("error while reading from lavalink websocket. error: ", err)
n.Close()
if err = n.reconnect(); err != nil {
n.lavalink.Logger().Error("error while reconnecting to lavalink websocket. error: ", err)
}
}
return
}
n.lavalink.Logger().Trace("received: ", string(data))
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(PluginEventHandler); ok {
plugin.OnNodeMessageIn(n, data)
}
}
var v UnmarshalOp
if err = json.Unmarshal(data, &v); err != nil {
n.lavalink.Logger().Error("error while unmarshalling op. error: ", err)
continue
}
switch op := v.Op.(type) {
case UnknownOp:
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(OpPlugin); ok {
plugin.OnOpInvocation(n, op.Data)
}
if plugin, ok := pl.(OpPlugins); ok {
for _, ext := range plugin.OpPlugins() {
if ext.Op() == op.Op() {
ext.OnOpInvocation(n, op.Data)
}
}
}
}
case PlayerUpdateOp:
n.onPlayerUpdate(op)
case OpEvent:
n.onEvent(op)
case StatsOp:
n.onStatsEvent(op)
default:
n.lavalink.Logger().Warnf("unexpected op received: %T, data: ", op, string(data))
}
}
}
func (n *nodeImpl) onPlayerUpdate(playerUpdate PlayerUpdateOp) {
if player := n.lavalink.ExistingPlayer(playerUpdate.GuildID); player != nil {
player.OnPlayerUpdate(playerUpdate.State)
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnPlayerUpdate(player, playerUpdate.State)
}
})
return
}
n.lavalink.Logger().Warnf("player update received for unknown player: %s", playerUpdate.GuildID)
}
func (n *nodeImpl) onEvent(event OpEvent) {
player := n.lavalink.ExistingPlayer(event.GuildID())
if player == nil {
return
}
switch e := event.(type) {
case TrackEvent:
track, err := n.lavalink.DecodeTrack(e.Track())
if err != nil {
n.lavalink.Logger().Errorf("error while decoding track: %s", err)
return
}
if playingTrack := player.PlayingTrack(); playingTrack != nil {
track.SetUserData(playingTrack.UserData())
}
switch ee := e.(type) {
case TrackStartEvent:
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnTrackStart(player, track)
}
})
case TrackEndEvent:
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnTrackEnd(player, track, ee.Reason)
}
})
case TrackExceptionEvent:
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnTrackException(player, track, ee.Exception)
}
})
case TrackStuckEvent:
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnTrackStuck(player, track, ee.ThresholdMs)
}
})
}
case WebsocketClosedEvent:
player.EmitEvent(func(l any) {
if listener := l.(PlayerEventListener); listener != nil {
listener.OnWebSocketClosed(player, e.Code, e.Reason, e.ByRemote)
}
})
case UnknownEvent:
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(EventPlugin); ok {
plugin.OnEventInvocation(n, e.Data)
}
if plugin, ok := pl.(EventPlugins); ok {
for _, ext := range plugin.EventPlugins() {
if ext.Event() == e.Event() {
ext.OnEventInvocation(n, e.Data)
}
}
}
}
default:
n.lavalink.Logger().Warnf("unexpected event received: %T, data: ", event)
return
}
}
func (n *nodeImpl) onStatsEvent(stats StatsOp) {
n.stats = &stats.Stats
}
func (n *nodeImpl) open(ctx context.Context, delay time.Duration) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
scheme := "ws"
if n.config.Secure {
scheme += "s"
}
header := http.Header{}
header.Add("Authorization", n.config.Password)
header.Add("User-Id", n.lavalink.UserID().String())
header.Add("Client-Name", fmt.Sprintf("%s/%s", Name, Version))
if n.config.ResumingKey != "" {
header.Add("Resume-Key", n.config.ResumingKey)
}
var (
err error
rs *http.Response
)
n.conn, rs, err = websocket.DefaultDialer.DialContext(ctx, fmt.Sprintf("%s://%s:%s", scheme, n.config.Host, n.config.Port), header)
if err != nil {
n.lavalink.Logger().Warnf("error while connecting to lavalink websocket, retrying in %f seconds: %s", delay.Seconds(), err)
if delay > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
} else {
delay = 1 * time.Second
}
if delay < 30*time.Second {
delay *= 2
}
return n.open(ctx, delay)
}
if n.config.ResumingKey != "" {
if rs.Header.Get("Session-Resumed") == "true" {
n.lavalink.Logger().Info("successfully resumed session with key: %s", n.config.ResumingKey)
} else {
n.lavalink.Logger().Warn("failed to resume session with key: ", n.config.ResumingKey)
}
}
go n.listen()
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(PluginEventHandler); ok {
plugin.OnNodeOpen(n)
}
}
return err
}
func (n *nodeImpl) Open(ctx context.Context) error {
n.statusMu.Lock()
defer n.statusMu.Unlock()
n.status = Connecting
if err := n.open(ctx, 0); err != nil {
n.status = Disconnected
return err
}
n.status = Connected
return nil
}
func (n *nodeImpl) Close() {
n.statusMu.Lock()
defer n.statusMu.Unlock()
for _, pl := range n.Lavalink().Plugins() {
if plugin, ok := pl.(PluginEventHandler); ok {
plugin.OnNodeDestroy(n)
}
}
n.status = Disconnected
if n.conn != nil {
if err := n.conn.Close(); err != nil {
n.lavalink.Logger().Errorf("error while closing wsconn: %s", err)
}
}
}