-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
752 lines (616 loc) · 21.3 KB
/
index.js
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/**
* @file index.js
* @author PerformanC <[email protected]>
*/
import event from 'node:events'
import events from './src/events.js'
import utils from './src/utils.js'
import Pws from '@performanc/pwsl-mini'
let Config = {}
let Nodes = {}
let Players = {}
let vcsData = {}
const Event = new event()
/**
* Connects node's WebSocket server for communication.
*
* @param nodes An array of node objects containing connection details.
* @param config Configuration object containing botId, shards, queue, and debug options.
* @throws Error If nodes or config is not provided or not in the expected format.
* @returns Event emitter for listening to LavaLink events.
*/
function connectNodes(nodes, config) {
if (!nodes) throw new Error('No nodes provided.')
if (typeof nodes !== 'object') throw new Error('Nodes must be an array.')
if (!config) throw new Error('No config provided.')
if (typeof config !== 'object') throw new Error('Config must be an object.')
if (!config.botId) throw new Error('No botId provided.')
if (typeof config.botId !== 'string') throw new Error('BotId must be a string.')
if (!config.shards) throw new Error('No shards provided.')
if (typeof config.shards !== 'number') throw new Error('Shards must be a number.')
if (config.queue && typeof config.queue !== 'boolean') throw new Error('Queue must be a boolean.')
Config = {
botId: config.botId,
shards: config.shards,
queue: config.queue ?? false
}
nodes.forEach((node) => {
if (!node.hostname) throw new Error('No hostname provided.')
if (typeof node.hostname !== 'string') throw new Error('Hostname must be a string.')
if (!node.password) throw new Error('No password provided.')
if (typeof node.password !== 'string') throw new Error('Password must be a string.')
if (typeof node.secure !== 'boolean') throw new Error('Secure must be a boolean.')
if (!node.port) node.port = 2333
Nodes[node.hostname] = {
...node,
connected: false,
sessionId: null
}
let ws = new Pws(`ws${node.secure ? 's' : ''}://${node.hostname}${node.port ? `:${node.port}` : ''}/v4/websocket`, {
headers: {
Authorization: node.password,
'Num-Shards': config.shards,
'User-Id': config.botId,
'Client-Name': 'FastLink/2.4.2 (https://github.com/PerformanC/FastLink)'
}
})
ws.on('open', () => events.open(Event, node.hostname))
ws.on('message', (data) => {
const tmp = events.message(Event, data, node.hostname, Config, Nodes, Players)
Nodes = tmp.Nodes
Players = tmp.Players
})
ws.on('close', async () => {
const tmp = await events.close(Event, ws, node, Config, Nodes, Players, vcsData)
Nodes = tmp.Nodes
Players = tmp.Players
ws = tmp.ws
vcsData = tmp.vcsData
})
ws.on('error', (err) => events.error(Event, err, node.hostname))
})
return Event
}
/**
* Checks if any node is connected.
*
* @returns The boolean if any node is connected or not.
*/
function anyNodeAvailable() {
return Object.values(Nodes).filter((node) => node?.connected).length === 0 ? false : true
}
function getRecommendedNode() {
const nodes = Object.values(Nodes).filter((node) => node?.connected)
if (nodes.length === 0) throw new Error('No node connected.')
return nodes.sort((a, b) => (a.stats.systemLoad / a.stats.cores) * 100 - (b.stats.systemLoad / b.stats.cores) * 100)[0]
}
/**
* Represents a player for an audio streaming service.
*
* @class Player
*/
class Player {
/**
* Constructs a Player object.
*
* @param guildId The ID of the guild that will be associated with the player.
* @throws Error If the guildId is not provided, or if they are of invalid type.
*/
constructor(guildId) {
if (!guildId) throw new Error('No guildId provided.')
if (typeof guildId !== 'string') throw new Error('GuildId must be a string.')
this.guildId = guildId
}
/**
* Retrieves the player local information.
*
* @returns The player local information.
*/
get info() {
return Players[this.guildId]
}
/**
* Retrieves the node tied to the player.
*
* @returns The node tied to the player.
*/
get node() {
return Players[this.guildId]?.node
}
/**
* Creates a player for the guild.
*
* @throws Error If a player already exists for the guild.
*/
createPlayer() {
if (Players[this.guildId])
throw new Error('Player already exists. Use playerCreated() to check if a player exists.')
const node = getRecommendedNode().hostname
Players[this.guildId] = {
connected: false,
playing: false,
paused: false,
volume: 100,
node,
loop: null,
guildWs: null
}
if (Config.queue) Players[this.guildId].queue = []
else Players[this.guildId].track = null
}
/**
* Verifies if a player exists for the guild.
*
* @returns The boolean if the player exists or not.
*/
playerCreated() {
return Players[this.guildId] ? true : false
}
/**
* Connects to a voice channel.
*
* @param voiceId The ID of the voice channel to connect to.
* @param options Options for the connection, deaf or mute.
* @param sendPayload A function for sending payload data.
* @throws Error If the voiceId or sendPayload is not provided, or if they are of invalid type.
*/
connect(voiceId, options, sendPayload) {
if (voiceId === undefined) throw new Error('No voiceId provided.')
if (typeof voiceId !== 'string' && voiceId !== null) throw new Error('VoiceId must be a string.')
if (!options) options = {}
if (typeof options !== 'object') throw new Error('Options must be an object.')
if (!sendPayload) throw new Error('No sendPayload provided.')
if (typeof sendPayload !== 'function') throw new Error('SendPayload must be a function.')
Players[this.guildId].connected = voiceId !== null
sendPayload(this.guildId, {
op: 4,
d: {
guild_id: this.guildId,
channel_id: voiceId,
self_mute: options.mute ?? false,
self_deaf: options.deaf ?? false
}
})
}
/**
* Loads a track.
*
* @param search The search query for the track.
* @return The loaded track data.
* @throws Error If the search is not provided or is of invalid type.
*/
loadTrack(search) {
if (!search) throw new Error('No search provided.')
if (typeof search !== 'string') throw new Error('Search must be a string.')
return this.makeRequest(`/loadtracks?identifier=${encodeURIComponent(search)}`, {
method: 'GET'
})
}
/**
* Loads lyrics for a given track.
*
* @param track The track to load lyrics for.
* @param lang The language to load lyrics for. Optional.
* @throws Error If the track is not provided or is of invalid type.
* @return A Promise that resolves to the loaded lyrics data.
*/
loadLyrics(track, lang) {
if (!track) throw new Error('No track provided.')
if (typeof track !== 'string') throw new Error('Track must be a string.')
if (lang && typeof lang != 'string') throw new Error('Lang must be a string.')
return this.makeRequest(`/loadlyrics?encodedTrack=${encodeURIComponent(track)}${lang ? `&language=${lang}`: ''}`, {
method: 'GET'
})
}
/**
* Updates the player state.
*
* @param body The body of the update request.
* @param noReplace Flag to specify whether to replace the existing track or not. Optional.
* @throws Error If the body is not provided or is of invalid type.
*/
update(body, noReplace) {
if (!body) throw new Error('No body provided.')
if (typeof body !== 'object') throw new Error('Body must be an object.')
if (body.track?.encoded && Config.queue) {
Players[this.guildId].queue.push(body.track.encoded)
if (Players[this.guildId].queue.length !== 1 && Object.keys(body).length !== 1) {
delete body.track.encoded
if (!body.track.userData)
delete body.track
}
if (Players[this.guildId].queue.length !== 1 && Object.keys(body).length === 1)
return;
} else if (body.track?.encoded === null) Players[this.guildId].queue = []
if (body.tracks?.encodeds) {
if (!Config.queue)
throw new Error('Queue is disabled.')
if (Players[this.guildId].queue.length === 0) {
Players[this.guildId].queue = body.tracks.encodeds
delete body.tracks
this.makeRequest(`/sessions/${Nodes[this.node].sessionId}/players/${this.guildId}`, {
body: {
...body,
track: {
...body.track,
encoded: Players[this.guildId].queue[0]
}
},
method: 'PATCH'
})
} else Players[this.guildId].queue.push(...body.tracks.encodeds)
return;
}
if (body.paused !== undefined) {
Players[this.guildId].playing = !body.paused
Players[this.guildId].paused = body.paused
}
if (body.volume !== undefined && body.filters?.volume === undefined)
Players[this.guildId].volume = body.volume || (body.filters?.volume * 100)
this.makeRequest(`/sessions/${Nodes[this.node].sessionId}/players/${this.guildId}?noReplace=${noReplace !== true ? false : true}`, {
body,
method: 'PATCH'
})
}
/**
* Destroys the player.
*/
destroy() {
this.makeRequest(`/sessions/${Nodes[this.node].sessionId}/players/${this.guildId}`, {
method: 'DELETE'
})
delete Players[this.guildId]
}
/**
* Gets the queue of tracks.
*
* @return The queue of tracks.
* @throws Error If the queue is disabled.
*/
getQueue() {
if (!Config.queue) throw new Error('Queue is disabled.')
return Players[this.guildId].queue
}
/**
* Skips the currently playing track.
*
* @return The queue of tracks, or null if there is no queue.
* @throws Error If the queue is disabled
*/
skipTrack() {
if (!Config.queue) throw new Error('Queue is disabled.')
if (Players[this.guildId].queue.length === 1)
return false
Players[this.guildId].queue.shift()
this.makeRequest(`/sessions/${Nodes[this.node].sessionId}/players/${this.guildId}`, {
body: {
track: {
encoded: Players[this.guildId].queue[0]
}
},
method: 'PATCH'
})
return Players[this.guildId].queue
}
/**
* Sets the loop state of the player.
*
* @param loop The loop state to set.
* @return The loop state of the player.
*/
loop(loop) {
if (!Config.queue) throw new Error('Queue is disabled.')
if (![ 'track', 'queue', null ].includes(loop))
throw new Error('Loop must be track, queue, or null.')
return Players[this.guildId].loop = loop
}
/**
* Shuffles the queue of tracks.
*
* @return The shuffled queue of tracks, or false if there are less than 3 tracks in the queue. The current playing track will not be shuffled.
* @throws Error If the queue is disabled.
*/
shuffle() {
if (!Config.queue) throw new Error('Queue is disabled.')
if (Players[this.guildId].queue.length < 3)
return false
Players[this.guildId].queue.forEach((_, i) => {
if (i === 0) return;
const j = Math.floor(Math.random() * (i + 1))
const temp = Players[this.guildId].queue[i]
Players[this.guildId].queue[i] = Players[this.guildId].queue[j]
Players[this.guildId].queue[j] = temp
})
return Players[this.guildId].queue
}
/**
* Decodes a track.
*
* @param track The array to decode.
* @throws Error If a track is not provided or if track is not a string.
* @return A Promise that resolves to the decoded data.
*/
decodeTrack(track) {
if (!track) throw new Error('No track provided.')
if (typeof track !== 'string') throw new Error('Track must be a string.')
return this.makeRequest(`/decodetrack?encodedTrack=${encodeURIComponent(track)}`, {
method: 'GET'
})
}
/**
* Decodes an array of tracks.
*
* @param tracks The array of tracks to decode.
* @throws Error If no tracks are provided or if tracks is not an array.
* @return A Promise that resolves to the decoded data.
*/
decodeTracks(tracks) {
if (!tracks) throw new Error('No tracks provided.')
if (typeof tracks !== 'object') throw new Error('Tracks must be an array.')
return this.makeRequest(`/decodetracks`, {
body: tracks,
method: 'POST'
})
}
/**
* Listens to the voice channel. NodeLink only.
*
* @returns An event emitter for listening to voice events. open, startSpeaking, endSpeaking, close, error
*/
listen() {
const voiceEvents = new event()
Players[this.guildId].guildWs = new Pws(`ws://${Nodes[this.node].hostname}${Nodes[this.node].port ? `:${Nodes[this.node].port}` : ''}/connection/data`, {
headers: {
Authorization: Nodes[this.node].password,
'user-id': Config.botId,
'guild-id': this.guildId,
'Client-Name': 'FastLink/2.4.2 (https://github.com/PerformanC/FastLink)'
}
})
.on('open', () => {
voiceEvents.emit('open')
})
.on('message', (data) => {
data = JSON.parse(data)
if (data.type == 'startSpeakingEvent') {
voiceEvents.emit('startSpeaking', data.data)
}
if (data.type == 'endSpeakingEvent') {
voiceEvents.emit('endSpeaking', data.data)
}
})
.on('close', () => {
voiceEvents.emit('close')
})
.on('error', (err) => {
voiceEvents.emit('error', err)
})
return voiceEvents
}
/**
* Stops listening to the voice channel.
*
* @returns The boolean if the player is connected or not.
*/
stopListen() {
const guildWs = Players[this.guildId].guildWs
if (!guildWs) return false
guildWs.close()
Players[this.guildId].guildWs = null
return true
}
makeRequest(path, options) {
return utils.makeNodeRequest(Nodes, this.node, `/v4${path}`, options)
}
}
/**
* Updates the session data for the node.
*
* @param node The node to update session data for.
* @param data The session data to update.
* @throws Error If the data is not provided or is of invalid type.
*/
function updateSession(node, data) {
if (!data) throw new Error('No data provided.')
if (typeof data !== 'object') throw new Error('Data must be an object.')
utils.makeNodeRequest(Nodes, node, `/v4/sessions/${Nodes[node].sessionId}`, {
body: data,
method: 'PATCH'
})
}
/**
* Retrieves the player for a given guild.
*
* @param guildId The guild to retrieve player from.
* @param node The node to retrieve player from.
*
* @throws Error If no guildId is provided or if guildId is not a string.
* @throws Error If no node is provided or if node is not a string.
* @throws Error If player does not exist.
*
* @returns A Promise that resolves to the retrieved player data.
*/
function getPlayer(guildId, node) {
if (!guildId) throw new Error('No guildId provided.')
if (typeof guildId !== 'string') throw new Error('GuildId must be a string.')
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Players[guildId]) throw new Error('Player does not exist.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, `/v4/sessions/${Nodes[node].sessionId}/players/${guildId}`, { method: 'GET' })
}
/**
* Retrieves the players for a given node.
*
* @param node The node to retrieve players from.
* @throws Error If no node is provided or if node is not a string.
* @return A Promise that resolves to the retrieved player data.
*/
function getPlayers(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/v4/sessions', { method: 'GET' })
}
/**
* Retrieves all local players.
*
* @returns The local players.
*/
function getAllLocalPlayers() {
return Players
}
/**
* Retrieves the info for a given node.
*
* @param node The node to retrieve info from.
* @throws Error If no node is provided or if node is not a string.
* @return A Promise that resolves to the retrieved info data.
*/
function getInfo(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/v4/info', { method: 'GET' })
}
/**
* Retrieves the stats for a given node.
*
* @param node The node to retrieve stats from.
* @throws Error If no node is provided or if node is not a string.
* @return A Promise that resolves to the retrieved stats data.
*/
function getStats(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/v4/stats', { method: 'GET' })
}
/**
* Retrieves the version for a given node.
*
* @param node The node to retrieve version from.
* @throws Error If no node is provided or if node is not a string.
* @return A Promise that resolves to the retrieved version data.
*/
function getVersion(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/version', { method: 'GET' })
}
/**
* Retrieves the router planner status for a given node.
*
* @param node The node to retrieve router planner status from.
* @throws Error If no node is provided or if node is not a string.
* @return A Promise that resolves to the retrieved router planner status data.
*/
function getRouterPlannerStatus(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/v4/routerplanner/status', { method: 'GET' })
}
/**
* Unmarks a failed address for a given node.
*
* @param node The node to unmark failed address from.
* @param address The address to unmark.
* @throws Error If no node is provided or if node is not a string.
* @returns A Promise that resolves when the request is complete.
*/
function unmarkFailedAddress(node, address) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
if (!address) throw new Error('No address provided.')
if (typeof address !== 'string') throw new Error('Address must be a string.')
return utils.makeNodeRequest(Nodes, node, `/v4/routerplanner/free/address?address=${encodeURIComponent(address)}`, {
method: 'GET',
body: { address }
})
}
/**
* Unmarks all failed addresses for a given node.
*
* @param node The node to unmark failed addresses from.
* @throws Error If no node is provided or if node is not a string.
* @returns A Promise that resolves when the request is complete.
*/
function unmarkAllFailedAddresses(node) {
if (!node) throw new Error('No node provided.')
if (typeof node !== 'string') throw new Error('Node must be a string.')
if (!Nodes[node]) throw new Error('Node does not exist.')
return utils.makeNodeRequest(Nodes, node, '/v4/routerplanner/free/all', { method: 'GET' })
}
/**
* Handles raw data received from an external source.
*
* @param data The raw data from Discord to handle.
* @throws Error If data is not provided or if data is not an object.
*/
function handleRaw(data) {
function _sendInfo() {
const player = new Player(data.d.guild_id)
if (!player.playerCreated()) return;
player.update({
voice: {
token: vcsData[data.d.guild_id].server.token,
endpoint: vcsData[data.d.guild_id].server.endpoint,
sessionId: vcsData[data.d.guild_id].sessionId
}
})
}
switch (data.t) {
case 'VOICE_SERVER_UPDATE': {
if (!vcsData[data.d.guild_id]) {
Event.emit('debug', '[FastLink] Voice server update received from Discord, but no data from "voice state update" found. This is only possible if the provided botId is incorrect.')
return;
}
if (vcsData[data.d.guild_id].server?.endpoint === data.d.endpoint) return;
vcsData[data.d.guild_id].server = {
token: data.d.token,
endpoint: data.d.endpoint
}
_sendInfo()
break
}
case 'VOICE_STATE_UPDATE': {
if (data.d.member.user.id !== Config.botId) return;
if (data.d.channel_id === null) return delete vcsData[data.d.guild_id]
if (vcsData[data.d.guild_id]?.sessionId === data.d.session_id) return;
vcsData[data.d.guild_id] = {
...vcsData[data.d.guild_id],
sessionId: data.d.session_id
}
if (vcsData[data.d.guild_id].server) _sendInfo()
break
}
}
}
export default {
node: {
updateSession,
connectNodes,
anyNodeAvailable
},
player: {
Player,
getPlayers,
getPlayer,
getAllLocalPlayers
},
routerPlanner: {
getRouterPlannerStatus,
unmarkFailedAddress,
unmarkAllFailedAddresses
},
other: {
getInfo,
getStats,
getVersion,
handleRaw
},
type: 'LavaLink v4'
}