Repository navigation
Expand file tree
/
Copy pathnode.go
More file actions
351 lines (283 loc) · 7.78 KB
/
Copy pathnode.go
File metadata and controls
351 lines (283 loc) · 7.78 KB
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
package disgolink
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/disgoorg/disgolink/v2/lavalink"
)
type Status string
// Indicates how far along the client is to connecting
const (
StatusConnecting Status = "CONNECTING"
StatusConnected Status = "CONNECTED"
StatusReconnecting Status = "RECONNECTING"
StatusDisconnected Status = "DISCONNECTED"
)
var ErrNodeAlreadyConnected = errors.New("node already connected")
var _ Node = (*nodeImpl)(nil)
type Node interface {
Lavalink() Client
Config() NodeConfig
Rest() RestClient
Stats() lavalink.Stats
Status() Status
SessionID() string
Version(ctx context.Context) (string, error)
Info(ctx context.Context) (*lavalink.Info, error)
Update(ctx context.Context, update lavalink.SessionUpdate) error
LoadTracks(ctx context.Context, identifier string) (*lavalink.LoadResult, error)
LoadTracksHandler(ctx context.Context, identifier string, handler AudioLoadResultHandler)
DecodeTrack(ctx context.Context, encodedTrack string) (*lavalink.Track, error)
DecodeTracks(ctx context.Context, encodedTracks []string) ([]lavalink.Track, error)
Open(ctx context.Context) error
Close()
}
type NodeConfig struct {
Name string `json:"name"`
Address string `json:"address"`
Password string `json:"password"`
Secure bool `json:"secure"`
SessionID string `json:"session_id"`
}
func (c NodeConfig) RestURL() string {
scheme := "http"
if c.Secure {
scheme += "s"
}
return fmt.Sprintf("%s://%s", scheme, c.Address)
}
func (c NodeConfig) WsURL() string {
scheme := "ws"
if c.Secure {
scheme += "s"
}
return fmt.Sprintf("%s://%s%s", scheme, c.Address, EndpointWebSocket)
}
type nodeImpl struct {
lavalink Client
config NodeConfig
rest RestClient
conn *websocket.Conn
connMu sync.Mutex
status Status
stats lavalink.Stats
sessionID string
}
func (n *nodeImpl) Lavalink() Client {
return n.lavalink
}
func (n *nodeImpl) Config() NodeConfig {
return n.config
}
func (n *nodeImpl) Rest() RestClient {
return n.rest
}
func (n *nodeImpl) Status() Status {
return n.status
}
func (n *nodeIm
10BC8
pl) Stats() lavalink.Stats {
return n.stats
}
func (n *nodeImpl) SessionID() string {
return n.sessionID
}
func (n *nodeImpl) Version(ctx context.Context) (string, error) {
return n.rest.Version(ctx)
}
func (n *nodeImpl) Info(ctx context.Context) (*lavalink.Info, error) {
return n.rest.Info(ctx)
}
func (n *nodeImpl) Update(ctx context.Context, update lavalink.SessionUpdate) error {
_, err := n.rest.UpdateSession(ctx, n.sessionID, update)
return err
}
func (n *nodeImpl) LoadTracks(ctx context.Context, identifier string) (*lavalink.LoadResult, error) {
return n.rest.LoadTracks(ctx, identifier)
}
func (n *nodeImpl) LoadTracksHandler(ctx context.Context, identifier string, handler AudioLoadResultHandler) {
result, err := n.LoadTracks(ctx, identifier)
if err != nil {
handler.LoadFailed(err)
return
}
switch result.LoadType {
case lavalink.LoadTypeTrackLoaded:
handler.TrackLoaded(result.Tracks[0])
case lavalink.LoadTypePlaylistLoaded:
handler.PlaylistLoaded(lavalink.Playlist{
Info: result.PlaylistInfo,
Tracks: result.Tracks,
})
case lavalink.LoadTypeSearchResult:
handler.SearchResultLoaded(result.Tracks)
case lavalink.LoadTypeNoMatches:
handler.NoMatches()
case lavalink.LoadTypeLoadFailed:
handler.LoadFailed(result.Exception)
}
}
func (n *nodeImpl) DecodeTrack(ctx context.Context, encodedTrack string) (*lavalink.Track, error) {
return n.rest.DecodeTrack(ctx, encodedTrack)
}
func (n *nodeImpl) DecodeTracks(ctx context.Context, encodedTracks []string) ([]lavalink.Track, error) {
return n.rest.DecodeTracks(ctx, encodedTracks)
}
func (n *nodeImpl) Open(ctx context.Context) error {
return n.reconnectTry(ctx, 0, false)
}
func (n *nodeImpl) open(ctx context.Context, reconnecting bool) error {
n.lavalink.Logger().Debug("opening connection to node...")
n.connMu.Lock()
defer n.connMu.Unlock()
if n.conn != nil {
return ErrNodeAlreadyConnected
}
if reconnecting {
n.status = StatusReconnecting
} else {
n.status = StatusConnecting
}
header := http.Header{
"Authorization": []string{n.config.Password},
"User-Id": []string{n.lavalink.UserID().String()},
"Client-Name": []string{fmt.Sprintf("%s/%s", Name, Version)},
}
if n.config.SessionID != "" {
header.Add("Session-Id", n.config.SessionID)
}
conn, _, err := websocket.DefaultDialer.DialContext(ctx, n.config.WsURL(), header)
if err != nil {
return err
}
_, data, err := conn.ReadMessage()
if err != nil {
return err
}
message, err := lavalink.UnmarshalMessage(data)
if err != nil {
return fmt.Errorf("failed to unmarshal ready message. error: %w", err)
}
ready, ok := message.(lavalink.ReadyMessage)
if !ok {
return fmt.Errorf("expected ready message but got %T", message)
}
n.sessionID = ready.SessionID
if n.config.SessionID != "" {
if ready.Resumed {
n.lavalink.Logger().Info("successfully resumed session with id: %s", n.config.SessionID)
} else {
n.lavalink.Logger().Warn("failed to resume session with id: ", n.config.SessionID)
}
}
n.status = StatusConnected
conn.SetCloseHandler(func(code int, text string) error {
return nil
})
n.conn = conn
go n.listen(conn)
n.Lavalink().ForPlugins(func(plugin Plugin) {
if pl, ok := plugin.(PluginEventHandler); ok {
pl.OnNodeOpen(n)
}
})
return nil
}
func (n *nodeImpl) Close() {
n.Lavalink().ForPlugins(func(plugin Plugin) {
if pl, ok := plugin.(PluginEventHandler); ok {
pl.OnNodeClose(n)
}
})
n.status = StatusDisconnected
if n.conn != nil {
if err := n.conn.Close(); err != nil {
n.lavalink.Logger().Errorf("error while closing wsconn: %s", err)
}
}
}
func (n *nodeImpl) reconnectTry(ctx context.Context, try int, reconnecting bool) error {
delay := time.Duration(try) * 2 * time.Second
if delay > 30*time.Second {
delay = 30 * time.Second
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
if err := n.open(ctx, reconnecting); err != nil {
if err == ErrNodeAlreadyConnected {
return err
}
n.lavalink.Logger().Error("failed to reconnect node. error: ", err)
n.status = StatusDisconnected
return n.reconnectTry(ctx, try+1, reconnecting)
}
return nil
}
func (n *nodeImpl) reconnect() {
if err := n.reconnectTry(context.Background(), 0, true); err != nil {
n.lavalink.Logger().Error("failed to reopen node. error: ", err)
}
}
func (n *nodeImpl) listen(conn *websocket.Conn) {
defer n.lavalink.Logger().Debug("exiting listen goroutine...")
loop:
for {
_, data, err := conn.ReadMessage()
if err != nil {
n.connMu.Lock()
sameConnection := n.conn == conn
n.connMu.Unlock()
if !sameConnection {
return
}
if !errors.Is(err, net.ErrClosed) {
n.Close()
go n.reconnect()
}
break loop
}
n.lavalink.Logger().Debug("received message: ", string(data))
n.Lavalink().ForPlugins(func(plugin Plugin) {
if pl, ok := plugin.(PluginEventHandler); ok {
pl.OnNodeMessageIn(n, data)
}
})
m, err := lavalink.UnmarshalMessage(data)
if err != nil {
n.lavalink.Logger().Errorf("error while unmarshalling ws data: %s", err)
return
}
switch message := m.(type) {
case lavalink.UnknownMessage:
n.Lavalink().ForPlugins(func(plugin Plugin) {
if pl, ok := plugin.(OpPlugin); ok {
pl.OnOpInvocation(n, message.Data)
}
})
case lavalink.StatsMessage:
n.stats = lavalink.Stats(message)
case lavalink.PlayerUpdateMessage:
player := n.lavalink.ExistingPlayer(message.GuildID)
if player == nil {
continue
}
player.OnPlayerUpdate(message.State)
case lavalink.Event:
player := n.lavalink.ExistingPlayer(message.GuildID())
if player == nil {
continue
}
player.OnEvent(message)
}
}
}