-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2870 lines (2452 loc) · 132 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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* TODO: add Soundcloud support (https://github.com/inspiredtolive/music-bot/blob/7a9a7df0b4bf2ec6f8161709b5e3e0383de2f1bc/lib/module.js)
instead of request node-fetch (with json method)
loading metadata via soundcloud api: line 14
loading stream via soundcloud api: line 91
*/
const _ = undefined;
var config = require('./config.json');
if(config.https){
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
var httpsServer = https.createServer({
key: fs.readFileSync('/etc/letsencrypt/live/foramitti.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/foramitti.com/fullchain.pem')
},app);
httpsServer.listen(8081);
var io = require('socket.io').listen(httpsServer);
}
else var io = require('socket.io')(8081);
const anchorme = require("anchorme").default;
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const ytsr = require('ytsr');
const ytpl = require('ytpl');
const fetch = require('node-fetch');
const mailTransport = require('nodemailer').createTransport({
host: 'mail.foramitti.com',
port: 587,
auth: config.email,
tls: {
rejectUnauthorized: false
}
});
var mongodb;
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true, useUnifiedTopology: true}, (err,client)=>{
if(err) console.log('Error while connecting to MongoDB', err);
else mongodb = client.db('pnp');
});
const mysql = require('mysql');
mysql.connectResolves = [];
mysql.query = async function(query){
if(!mysql.connectionReady){
await new Promise(resolve => mysql.connectResolves.push(resolve));
}
try{
return await new Promise((resolve, reject) => {
mysql.connection.query(query, (err, result)=>{
if(err) reject(err);
else resolve(result);
});
});
}
catch(e){
throw new Error(e);
}
};
mysql.safeConnect = function(connectionConfig) {
this.connection = this.createConnection(connectionConfig);
this.connection.connect((err)=>{
if(err){
console.log('Error while connecting to MySQL: ',err);
setTimeout(()=>this.safeConnect(connectionConfig), 2000);
}
else{
this.connectionReady = true;
for(let resolve of this.connectResolves) resolve();
}
});
this.connection.on('error', (err)=>{
this.connectionReady = false;
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
console.log('Lost MySQL connection, reconnecting...');
this.safeConnect(connectionConfig);
} else {
throw err;
}
});
}
mysql.safeConnect(config.mysql);
// these methods are not complete!!! they just cover hex entities
String.prototype.encodeHTML = function(){
return this.replace(/[^ \{\|\}~!#\$%\(\)\*\+,-./\d:;\=\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\]\\\^_]/gi, (match) => '&#x'+match.charCodeAt(0).toString(16)+';');
}
String.prototype.decodeHTML = function(){
return this.replace(/&#x([\dabcdef]+);/gi, (match, numString) => String.fromCharCode(parseInt(numString, 16)));
}
Object.defineProperty(String.prototype, "encodeHTML", {enumerable: false});
Object.defineProperty(String.prototype, "decodeHTML", {enumerable: false});
Math.sum = function(...summands){
let s = 0;
for(let x of summands){
s += parseFloat(x);
}
return s;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Discord.TextChannel.prototype.confirm = async function confirm(msgTxt, func, ...args){
let reply = await this.send(msgTxt);
let toggle = true;
reply.awaitReactions(
(reaction, user) => {
if(toggle && reaction.emoji.name === '✅' && user !== this.guild.me.user){
toggle = false;
func(...args);
}
},
{ time: 120000 }
);
reply.react('✅');
};
Discord.TextChannel.prototype.sendPages = function sendPages(pages){
let channel = this;
if(typeof pages == 'string'){
let tmpPages = [];
let offset = 0;
while(pages.length - offset > 1800){
let newOffset = pages.lastIndexOf('\n',offset + 1800);
let skip = 1;
if(newOffset - offset < 800){
newOffset = pages.lastIndexOf(' ',offset + 1800);
if(newOffset - offset < 800){
newOffset = offset + 1800;
skip = 0;
}
}
tmpPages.push(pages.slice(offset,newOffset));
offset = newOffset+skip;
}
tmpPages.push(pages.slice(offset));
pages = tmpPages;
}
async function sendPage(i){
let reply = await channel.send(pages[i] + '\n\n[page '+(i+1)+'/'+pages.length+']');
let toggle = true;
reply.awaitReactions(
(reaction, user) => {
if(!toggle || user === this.guild.me.user) return;
if(i < pages.length-1 && reaction.emoji.name === '➡️'){
toggle = false;
sendPage(i+1);
}
else if(i > 0 && reaction.emoji.name === '⬅️'){
toggle = false;
sendPage(i-1);
}
},
{ time: 180000 }
);
if(i > 0) reply.react('⬅️');
if(i < pages.length-1) reply.react('➡️');
}
sendPage(0);
};
Object.defineProperty(Discord.TextChannel.prototype, "confirm", {enumerable: false});
Object.defineProperty(Discord.TextChannel.prototype, "sendPages", {enumerable: false});
Discord.Guild.prototype.getRoles = async function getRoles(){
return (await this.roles.fetch())
.cache.filter(role => !['ADMIN','@everyone','Rythm','PnPBot'].includes(role.name)).array();
}
Object.defineProperty(Discord.Guild.prototype, "getRoles", {enumerable: false});
function getReferenceName(name){
return name.toLowerCase().replace(/\s+/g,'_').replace(/[^\w]/g,'');
}
const Duration = {
parseISO8601(iso8601Duration) { // returns seconds
var matches = iso8601Duration.match(/(-)?P(?:([.,\d]+)Y)?(?:([.,\d]+)M)?(?:([.,\d]+)W)?(?:([.,\d]+)D)?(?:T(?:([.,\d]+)H)?(?:([.,\d]+)M)?(?:([.,\d]+)S)?)?/);
return ((matches[1] === undefined)?1:-1)*(
(matches[8] === undefined ? 0 : parseFloat(matches[8])) +
(matches[7] === undefined ? 0 : parseFloat(matches[7])) * 60 +
(matches[6] === undefined ? 0 : parseFloat(matches[6])) * 3600 +
(matches[5] === undefined ? 0 : parseFloat(matches[5])) * 86400 +
(matches[4] === undefined ? 0 : parseFloat(matches[4])) * 604800 +
(matches[3] === undefined ? 0 : parseFloat(matches[3])) * 2592000 +
(matches[2] === undefined ? 0 : parseFloat(matches[2])) * 31536000
);
},
parseClockFormat(durationString){
let duration = durationString.split(':').map(x => parseInt(x)).reverse();
if(duration.some(x => Number.isNaN(x))) throw new Error('invalid format');
return duration[0] + (duration[1] ? (duration[1]*60) : 0) + (duration[2] ? (duration[2]*3600) : 0);
},
convertSeconds(seconds){
let durationObject = {
sign: seconds < 0 ? '-' : '',
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
if(seconds < 0) seconds = -seconds;
if(seconds >= 31536000){
durationObject.years = Math.floor(seconds/31536000);
seconds = seconds % 31536000;
}
if(seconds >= 2592000){
durationObject.months = Math.floor(seconds/2592000);
seconds = seconds % 2592000;
}
if(seconds >= 604800){
durationObject.weeks = Math.floor(seconds/604800);
seconds = seconds % 604800;
}
if(seconds >= 86400){
durationObject.days = Math.floor(seconds/86400);
seconds = seconds % 86400;
}
if(seconds >= 3600){
durationObject.hours = Math.floor(seconds/3600);
seconds = seconds % 3600;
}
if(seconds >= 60){
durationObject.minutes = Math.floor(seconds/60);
seconds = seconds % 60;
}
durationObject.seconds = seconds;
return durationObject;
}
};
function getURLParameters(url){
if(!url.includes('?')) return {};
return Object.fromEntries(url.split('?')[1].split('&').map(x => {
x = x.split('=');
x[1] = decodeURIComponent(x[1]);
return x;
}));
}
const Youtube = {
parseTimestamps(description){
if(!/\d:\d\d/.test(description)) return [];
let timestamps = [];
for(let line of description.split('\n')){
let match = line.match(/(\d+:)?\d+:\d\d/);
if(!match) continue;
let timestamp = {};
timestamp.time = Duration.parseClockFormat(match[0]);
if(match.index < (line.length - match[0].length)/2){ // timestamp is on the left side of line, e.g. '3:45 - Title of song'
timestamp.name = line.slice(match.index+match[0].length).trim();
}
else{ // timestamp is on the right side of line, e.g. 'Title of song, 3:45'
timestamp.name = line.slice(0, match.index).trim();
}
while(timestamp.name.startsWith('-') || timestamp.name.startsWith(',') || timestamp.name.startsWith(';') || timestamp.name.startsWith(':') ||
timestamp.name.startsWith('|') || timestamp.name.startsWith(')'))
timestamp.name = timestamp.name.slice(1).trim();
while(timestamp.name.endsWith('-') || timestamp.name.endsWith(',') || timestamp.name.endsWith(';') || timestamp.name.endsWith(':') ||
timestamp.name.endsWith('|') || timestamp.name.endsWith('('))
timestamp.name = timestamp.name.slice(0,-1).trim();
timestamps.push(timestamp);
}
timestamps.sort((a,b) => a.time - b.time);
return timestamps;
},
async search(searchPhrase, {type, nextpageRef, limit}){
let data = await ytsr(searchPhrase, {limit, nextpageRef});
if(!data?.items) return {items:[]};
for(let i in data){
if(i != 'items' && i != 'nextpageRef') delete data[i];
}
let items = [];
for(let item of data.items){
if(!type || item.type == type){
if(item.type == 'video'){
if(!item.title) continue;
if(!item.duration) continue;
item.duration = Duration.parseClockFormat(item.duration);
if(!item.duration) continue;
if(!item.thumbnail) item.thumbnail = 'https://i.ytimg.com/vi/invalid/hqdefault.jpg';
if(!item.author) item.author = {name:''};
for(let i in item.author){
if(i != 'name' && i != 'ref') delete item.author[i];
}
item.contentId = item.link?.split('v=')[1];
if(!item.contentId) continue;
if(item.description) item.timestamps = this.parseTimestamps(item.description);
else item.timestamps = [];
for(let i in item){
if(i != 'type' && i != 'title' && i != 'contentId' && i != 'thumbnail' && i != 'author' && i != 'duration' && i != 'timestamps') delete item[i];
}
items.push(item);
}
else if(item.type == 'playlist'){
if(!item.title) continue;
item.length = parseInt(item.length);
if(!item.length) continue;
if(!item.thumbnail) item.thumbnail = 'https://i.ytimg.com/vi/invalid/hqdefault.jpg';
if(!item.author) item.author = {name:''};
for(let i in item.author){
if(i != 'name' && i != 'ref') delete item[i];
}
item.contentId = item.link?.split('list=')[1];
if(!item.contentId) continue;
for(let i in item){
if(i != 'type' && i != 'title' && i != 'contentId' && i != 'thumbnail' && i != 'author' && i != 'length') delete item[i];
}
items.push(item);
}
}
}
data.items = items;
return data;
},
async videoInfo(videoId){
let item = await ytdl.getBasicInfo(videoId);
if(!item.title) throw new Error('no title found for video');
item.duration = parseInt(item.length_seconds);
if(!item.duration) throw new Error('invalid duration');
item.thumbnail = item.playerResponse?.videoDetails?.thumbnail?.thumbnails?.[0]?.url; // 0 for lowest quality
if(!item.thumbnail) item.thumbnail = 'https://i.ytimg.com/vi/invalid/hqdefault.jpg';
if(!item.author) item.author = {name:''};
if(item.author.channel_url) item.author.ref = item.author.channel_url;
for(let i in item.author){
if(i != 'name' && i != 'ref') delete item.author[i];
}
item.contentId = item.video_id;
if(!item.contentId) throw new Error('invalid content id');
if(item.description) item.timestamps = this.parseTimestamps(item.description);
else item.timestamps = [];
for(let i in item){
if(i != 'title' && i != 'contentId' && i != 'thumbnail' && i != 'author' && i != 'duration' && i != 'timestamps') delete item[i];
}
return item;
},
async playlistItems(playlistId){
let data = await ytpl(playlistId,{limit:Infinity});
if(!data?.items) return [];
// more efficient, since no secondary call needed, but does not provide description for timestamp retrieval:
/*let items = [];
for(let item of data.items){
if(!item.title) continue;
if(!item.duration) continue;
item.duration = Duration.parseClockFormat(item.duration);
if(!item.duration) continue;
if(!item.thumbnail) item.thumbnail = 'https://i.ytimg.com/vi/invalid/hqdefault.jpg';
if(!item.author) item.author = {name:''};
for(let i in item.author){
if(i != 'name' && i != 'ref') delete item.author[i];
}
item.contentId = item.id;
if(!item.contentId) continue;
for(let i in item){
if(i != 'title' && i != 'contentId' && i != 'thumbnail' && i != 'author' && i != 'duration') delete item[i];
}
items.push(item);
return items;
}*/
return await Promise.all(data.items.map(x => this.videoInfo(x.id)));
}
};
var objectSets = {
Queue: new Map(),
Song: new Map()
}
class Queue {
static nextId = 0;
constructor(name, songs){
this.id = Queue.nextId++;
if(Queue.nextId >= Number.MAX_SAFE_INTEGER) Queue.nextId = 0;
objectSets.Queue.set(this.id, this);
this.name = name;
this.songs = songs ?? []; // contains actual object references
this.currentSong = null;
}
removeSong(song){
this.songs.splice(this.songs.indexOf(song), 1);
objectSets.Song.delete(song.id);
io.emit('music_updateQueue_'+this.id,{songs: this.songs.map(x => x.id)});
}
addSongs(songs){
this.songs.push(...songs);
io.emit('music_updateQueue_'+this.id,{songs: this.songs.map(x => x.id)});
}
clear(){
for(let song of this.songs) objectSets.Song.delete(song.id);
this.songs = [];
io.emit('music_updateQueue_'+this.id,{songs: this.songs.map(x => x.id)});
}
next(settings){
let index = this.songs.indexOf(this.currentSong);
if(index < 0) return null;
if(settings.autoclean && this.songs.length > 1){
this.songs.splice(index, 1);
io.emit('music_updateQueue_'+this.id,{songs: this.songs.map(x => x.id)});
}
else index++;
if(this.songs.length == 0) return null;
if(settings.shuffle){
if(settings.autoclean && this.songs.length < 2) return null;
return this.songs[Math.floor(Math.random()*this.songs.length)];
}
else if(this.songs[index]) return this.songs[index];
else if(settings.wrapAround) return this.songs[0];
else return null;
}
previous(settings){
let index = this.songs.indexOf(this.currentSong);
if(index < 0) return null;
index--;
if(settings.shuffle) return this.songs[Math.floor(Math.random()*this.songs.length)];
else if(this.songs[index]) return this.songs[index];
else if(settings.wrapAround) return this.songs[this.songs.length-1];
else this.songs[0];
}
moveSong(song, newIndex){
let index = this.songs.indexOf(song);
if(index < 0) return false;
this.songs.splice(index, 1);
this.songs.splice(newIndex, 0, song);
io.emit('music_updateQueue_'+this.id,{songs: this.songs.map(x => x.id)});
return true;
}
rename(newName){
this.name = newName;
io.emit('music_updateQueue_'+this.id,{name: this.name});
}
getData(){
return {
id: this.id,
name: this.name,
songs: this.songs.map(x => x.id)
};
}
}
class Song {
static nextId = 0;
constructor(queue, service, contentId, name, author, thumbnail, duration, timestamps){
this.id = Song.nextId++;
if(Song.nextId >= Number.MAX_SAFE_INTEGER) Song.nextId = 0;
objectSets.Song.set(this.id, this);
this.queue = queue;
this.service = service; // string
this.contentId = contentId; // string
this.name = name; // string
this.author = author; // {name[, ref(url to author)]}
this.thumbnail = thumbnail; // string url
this.duration = duration; // number in seconds
this.timestamps = timestamps ?? []; // array of timestamp objects: {name, time<number in seconds>}
}
getStream(){
if(this.service === 'YouTube'){
return ytdl('https://www.youtube.com/watch?v='+this.contentId, {
filter: 'audioonly',
quality: 'lowestaudio',
highWaterMark: 10485760 // buffer size: 10 megabytes
});
}
else{
return null;
}
}
getData(){
return {
id: this.id,
service: this.service,
contentId: this.contentId,
name: this.name,
author: this.author,
thumbnail: this.thumbnail,
duration: this.duration,
timestamps: this.timestamps
};
}
static async getFromURL(url, queue){
if(url.startsWith('https://')) url = url.substring(8);
if(url.startsWith('http://')) url = url.substring(7);
if(url.startsWith('www.')) url = url.substring(4);
if(this.isCollection(url)) return (await this.getCollection(url, queue));
return [await this.getSingle(url, queue)];
}
static async getSingle(url, queue){
// var urlParameters = getURLParameters(url);
if(url.startsWith('youtube.com/watch')){
if(!ytdl.validateURL(url)) throw 'Not a valid youtube url';
let ytData;
try{
ytData = await Youtube.videoInfo(url);
}
catch(e){
throw 'Unable to fetch video meta data. Error: '+e.stack;
}
if(!ytData) throw 'Unable to fetch video meta data.';
return new Song(queue, 'YouTube', ytData.contentId, ytData.title, ytData.author, ytData.thumbnail, ytData.duration, ytData.timestamps);
}
}
static async getCollection(url, queue){
var songs = [];
// var urlParameters = getURLParameters(url);
if(url.startsWith('youtube.com/playlist')){
if(!ytpl.validateURL(url)) throw 'Not a valid youtube url';
let ytData;
try{
ytData = await Youtube.playlistItems(await ytpl.getPlaylistID(url));
}
catch(e){
throw 'Unable to fetch playlist data. Error: '+e.stack;
}
if(!ytData) throw 'Unable to fetch playlist data.';
for(let x of ytData){
songs.push(new Song(queue, 'YouTube', x.contentId, x.title, x.author, x.thumbnail, x.duration, x.timestamps));
}
}
return songs;
}
static isCollection(url){
if(url.startsWith('youtube.com/playlist')) return true;
if(url.startsWith('youtube.com/watch')) return false;
}
}
var discord = {
client: new Discord.Client(),
PREFIX: config.discord.commandPrefix,
server: {
async init(guild){
this.guild = guild;
this.music.guild = guild;
let promises = [];
for(let memberId of (await guild.members.fetch()).keyArray()){
promises.push(this.initUser(memberId));
}
await Promise.all(promises);
this.music.checkStreamHealth();
this.ready();
},
initUser(id){
return mongodb.collection('DiscordUser').updateOne(
{_id:id},
{$setOnInsert:{
notifications:{
discord: false,
email: [],
push: [],
telegram: []
}
}},
{upsert: true}
);
},
music: {
currentQueue: new Queue('Default'),
currentSong: null,
playing: false,
startedPlayingFrom: 0,
voiceConnection: null,
dispatcher: null,
stream: null,
lastVoiceChannel: null,
streamHealthLastTimestamp: null,
streamHealthCheckingPause: false,
settings: {
autoplay: true,
loop: false,
wrapAround: true,
autoclean: false,
shuffle: false
},
async checkStreamHealth(){
if(this.playing && !this.streamHealthCheckingPause){
let timestamp = await this.getCurrentPostion();
if(this.streamHealthLastTimestamp == timestamp){
console.log('stream died -> restart from ', this.streamHealthLastTimestamp);
// stream died -> restart from last timestamp
await this.destroyDispatcher();
this.play(this.streamHealthLastTimestamp);
}
this.streamHealthLastTimestamp = timestamp;
}
setTimeout(()=>this.checkStreamHealth(), 3000);
},
abortPauseStreamHealthChecking: ()=>{},
pauseStreamHealthChecking(duration=60){
// duration in seconds
this.abortPauseStreamHealthChecking();
this.streamHealthCheckingPause = true;
let aborted = false;
this.abortPauseStreamHealthChecking = ()=>{
aborted = true;
}
setTimeout(()=>{
if(!aborted) this.streamHealthCheckingPause = false;
}, duration * 1000);
},
async joinVoiceChannel(msg){
await this.onready;
// if no message given, join the last voice channel
if(!msg){
if(await this.getVoiceConnection()) return true;
if(this.lastVoiceChannel){
this.voiceConnection = await this.lastVoiceChannel.join();
}
else{
throw 'No message given to retrieve author\'s voice channel, nor remembers the last voice connection.';
}
}
// else join the same voice channel as the author of the message
else if(!msg.guild?.voice || !this.voiceConnection){
if(!msg.member?.voice){
msg.channel.send('The bot is currently not in a Voice Channel. Please first join a voice channel to indicate where the bot should join.');
return false;
}
this.lastVoiceChannel = msg.member.voice.channel;
this.voiceConnection = await msg.member.voice.channel.join();
}
else if(msg.member.voice?.channel && msg.member.voice.channel !== msg.guild.voice.channel){
msg.channel.send('command from member in another voice channel -> changing channel');
this.lastVoiceChannel = msg.member.voice.channel;
this.voiceConnection = await msg.member.voice.channel.join();
}
this.voiceConnection.on('disconnect',()=>{
this.voiceConnection = null;
this.dispatcher = null;
this.playing = false;
io.emit('music_playing',false);
});
return true;
},
async play(position=0){
// postion in seconds
await this.onready;
if(this.currentQueue.songs.length === 0 || !(await this.getVoiceConnection())){
console.log('unable to play (no songs or no voice connection)', this.currentQueue.songs.length, await this.getVoiceConnection());
return false; // unable to play (no songs or no voice connection)
}
if(await this.getDispatcher()) return await this.resume(); // if already playing nothing to do
this.pauseStreamHealthChecking();
if(!this.currentSong){ // if no current song, take first song of current queue
this.currentSong = this.currentQueue.currentSong = this.currentQueue.songs[0];
io.emit('music_currentSong',this.currentSong.id);
}
let stream = this.currentSong.getStream();
this.dispatcher = (await this.getVoiceConnection()).play(stream, {
seek: position,
highWaterMark: 48
});
this.playing = true;
this.startedPlayingFrom = position;
io.emit('music_playing',true);
io.emit('music_syncTime',position);
this.dispatcher.on('finish', () => this.handleEndOfStream());
return true;
},
handleEndOfStream(){
this.dispatcher = null;
if(!this.settings.autoplay || this.currentQueue.songs.length === 0){
this.playing = false;
io.emit('music_playing', false);
this.dispatcher = null;
return;
}
if(this.settings.loop) this.play();
else this.next();
},
async skipToTime(position){
await this.onready;
// postion in seconds
if(this.currentSong?.duration<position) return false;
await this.destroyDispatcher();
this.play(position);
return true;
},
async getCurrentPostion(){
await this.onready;
let dispatcher = await this.getDispatcher();
if(!dispatcher) return null;
return this.startedPlayingFrom + (dispatcher.streamTime/1000); // in seconds
},
async resume(){
await this.onready;
let dispatcher = await this.getDispatcher();
if(!dispatcher) return await this.play();
if(this.playing) return true;
dispatcher.resume();
this.playing = true;
io.emit('music_playing',true);
return true;
},
async pause(){
await this.onready;
let dispatcher = await this.getDispatcher();
if(!dispatcher) return false;
dispatcher.pause();
this.playing = false;
io.emit('music_playing',false);
return true;
},
async stop(){
await this.onready;
let dispatcher = await this.getDispatcher();
if(!dispatcher) return false;
await this.destroyDispatcher();
(await this.getVoiceConnection()).disconnect();
this.playing = false;
io.emit('music_playing',false);
io.emit('music_syncTime',0);
return true;
},
async next(){
await this.onready;
await this.destroyDispatcher();
let song = this.currentQueue.next(this.settings);
if(song){
this.currentSong = this.currentQueue.currentSong = song;
io.emit('music_currentSong',this.currentSong.id);
this.play();
}
else{
this.playing = false;
io.emit('music_playing',false);
io.emit('music_syncTime',0);
}
},
async previous(){
await this.onready;
await this.destroyDispatcher();
let song = this.currentQueue.previous(this.settings);
if(song){
this.currentSong = this.currentQueue.currentSong = song;
io.emit('music_currentSong',this.currentSong.id);
this.play();
}
else{
this.playing = false;
io.emit('music_playing',false);
io.emit('music_syncTime',0);
}
},
async playSong(songId){
await this.onready;
let song = objectSets.Song.get(songId);
if(!song) return false;
if(song == this.currentSong) return true;
await this.destroyDispatcher();
this.currentQueue.currentSong = null;
this.currentQueue = song.queue;
this.currentSong = this.currentQueue.currentSong = song;
io.emit('music_currentSong',this.currentSong.id);
this.play();
return true;
},
async skipToIndex(index){
if(index < 0 || index >= this.currentQueue.songs.length) throw 'index out of bound';
let song = this.currentQueue.songs[index];
if(!song) throw 'song not found';
if(song == this.currentSong) return true;
await this.destroyDispatcher();
this.currentSong = this.currentQueue.currentSong = song;
io.emit('music_currentSong',this.currentSong.id);
this.play();
return true;
},
async removeSong(songId){
await this.onready;
let song = objectSets.Song.get(songId);
if(!song) return false;
if(song == this.currentSong){
await this.destroyDispatcher();
this.currentSong = this.currentQueue.currentSong = this.currentQueue.songs[this.currentQueue.songs.indexOf(song)+1];
io.emit('music_currentSong',this.currentSong?.id);
if(this.playing){
if(!this.settings.autoplay || !this.currentSong){
this.playing = false;
io.emit('music_playing', false);
}
else this.play();
}
}
song.queue.removeSong(song);
},
async removeQueue(queueId){
await this.onready;
if(objectSets.Queue.size < 2) throw 'Last queue cannot be removed';
let queue = objectSets.Queue.get(queueId);
if(!queue) return false;
if(this.currentSong?.queue == queue){
await this.destroyDispatcher();
objectSets.Queue.delete(queueId);
this.currentQueue = objectSets.Queue.values().next().value;
this.currentSong = this.currentQueue.currentSong = this.currentQueue.songs[0];
io.emit('music_currentSong',this.currentSong?.id);
if(this.playing){
if(this.currentSong) this.play();
else{
this.playing = false;
io.emit('music_playing',false);
io.emit('music_syncTime',0);
}
}
}
else{
objectSets.Queue.delete(queueId);
}
io.emit('music_removeQueue_'+queueId);
return true;
},
addQueue(name){
let queue = new Queue(name);
io.emit('music_addQueue', queue.getData());
},
async clearQueue(queueId){
await this.onready;
let queue = objectSets.Queue.get(queueId);
if(!queue) return false;
if(this.currentSong?.queue == queue){
await this.destroyDispatcher();
this.playing = false;
io.emit('music_playing',false);
io.emit('music_syncTime',0);
this.currentSong = null;
io.emit('music_currentSong',null);
}
queue.clear();
return true;
},
moveSong(songId, newIndex){
let song = objectSets.Song.get(songId);
if(!song) return false;
return song.queue.moveSong(song, newIndex);
},
addSongs(queueId, songs){
let queue = objectSets.Queue.get(queueId);
if(!queue) return false;
let songObjs = [];
for(let song of songs){
if('service' in song && 'contentId' in song && 'name' in song && 'author' in song && 'thumbnail' in song && 'duration' in song && 'name' in song.author)
songObjs.push(new Song(queue, song.service, song.contentId, song.name, song.author, song.thumbnail, song.duration));
}
queue.addSongs(songObjs);
},
async addURL(queueId, url){
let queue = objectSets.Queue.get(queueId);
if(!queue) throw 'invalid queueId';
let songs = await Song.getFromURL(url, queue);
if(!songs.length) throw 'unable to retrieve songs from URL';