-
Notifications
You must be signed in to change notification settings - Fork 6
/
bot.js
2210 lines (2059 loc) · 107 KB
/
bot.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
/*********************************************************************
* JAVASCRIPT DISCORD RECORDER AND SOUNDBOARD BOT - JS DRaSB
*
* This is a JavaScript Node.js Discord bot based on discord.js library
* that is meant to perform automatic recording of a discord channel
* and play music/sounds as a soundboard or a playlist bot.
*
* DRaSB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3.
*
* JS_DRaSB Copyright 2018-2019 - Anton Grushin
*
*
* bot.js
* Main bot executable.
*********************************************************************/
var Discord = require('discord.js');
const ytdl = require('ytdl-core');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const https = require('https');
const client = new Discord.Client();
const async = require("async");
//var heapdump = require('heapdump');
const { PassThrough } = require('stream'); //For piping file stream to ffmpeg
//Load bot parts
//const config = require('./config.js');
const utils = require('./utils.js');
var db = require('./database.js');
//Config
var opt = require('./opt.js');
var config = opt.opt;
//Classes from DiscordJs for refreshing
const AudioPlayer = require('discord.js/src/client/voice/player/AudioPlayer');
//technical variables
var BotReady = false; //This turns true when we are connected to Discord server
var RecordsDBReady = false;
var LastChannelChangeTimeMs = Date.now(); //Time in ms when we did last channel change so we can wait until new join to stop command flooding
var ChannelWaitingToJoin = null;
var PlayingQueue = [];
var GetFileQueue = [];
var PausingThePlayback = false;
var CurrentPlayingSound = {};
var CurrentVolume = 0.0;
var queueDBWrite = [];
var lastQueueElements = [];
var ffmpegPlaybackCommands = [];
var soundIsPlaying = false;
var PreparingToPlaySound = false;
var LastPlaybackTime = Date.now();
// =============== HELPER FUNCTIONS ===============
//Return user tag or nam depending on PlaybackStatusMessagesTagPeople option
function getUserTagName(user) {
if (config.PlaybackStatusMessagesTagPeople)
return "<@" + user.id + ">";
else {
let output = getUserName(user);
return (output != false ? output : "");
}
}
//Get the name of the User or return false if he is not part of the guild
function getUserName(User) {
let member = client.guilds.get(config.guildId).members.get(User.id);
if (member) {
if (member.nickname)
return member.nickname;
else
return User.username;
}
else
return false;
}
//Get total duration of the queue
function getQueueDuration() {
let totalDuration = 0;
for (i in PlayingQueue) {
if (PlayingQueue[i]['duration']) {
totalDuration += PlayingQueue[i]['duration'];
if (PlayingQueue[i]['played'])
totalDuration -= PlayingQueue[i]['played'] / 1000;
}
}
return totalDuration;
}
//Calculate volume value using global config and personal volume level, inputs percentage 0.0-100.0, outputs 0.0-1.0
function calcVolumeToSet(personalVol) {
//config.VolumeBotGlobal - this is considered 100% volume
return (personalVol * (config.VolumeBotGlobal / 100)) / 100;
}
//Return amount of members in a voice channel (excluding bots)
function countChannelMembers(channel) {
if (channel)
return channel.members.filter(member => !member.user.bot).size;
else
return 0;
}
//Send Informational message on a channel
function sendInfoMessage(message, channel, user = null) {
if (BotReady && message.length > 0) {
utils.report("InfoMessage: " + (user != null ? user.username + ", " : "") + message, 'c');
let channelToSendTo = channel;
if (config.RestrictCommandsToSingleChannel && channel.type != "dm")
channelToSendTo = client.channels.get(config.ReportChannelId);
if (channelToSendTo) {
channelToSendTo.send((user != null ? "<@" + user.id + ">, " : "") + message)
.then(sentMsg => {
if (config.InfoMessagesDelete && channelToSendTo.type != "dm") {
setTimeout(() => {
sentMsg.delete()
.catch(error => utils.report("Couldn't delete informational message on channel '" + channelToSendTo.name + "'. Error: " + error, 'r'));
}, config.InfoMessagedDeleteTimeout * 1000);
}
})
.catch(error => utils.report("Couldn't send a message to channel '" + channelToSendTo.name + "'. Error: " + error, 'r'));
}
else
utils.report("'ReportChannelId' that you specified in the config file is not avaliable to the bot! Can't send messages there.", 'r');
}
}
//Send Playback Status message
function playbackMessage(message) {
utils.report("Playback: " + message, 'g');
channelToSendTo = client.channels.get(config.ReportChannelId);
if (config.PlaybackStatusMessagesSend) {
if (channelToSendTo) {
channelToSendTo.send(message)
.catch(error => utils.report("Couldn't send a message to channel '" + channelToSendTo.name + "'. Error: " + error, 'r'));
}
else
utils.report("'ReportChannelId' that you specified in the config file is not avaliable to the bot! Can't send messages there.", 'r');
}
}
//Send message or several if it exceeds Character limit
function breakMessage(message, usedCount = 0, beginMessage="", endMessage="", backwards=false) {
let result = [];
if (message.length > config.MessageCharacterLimit - usedCount) {
let cutted = message.split('\n');
let thisChunk = "";
//If its backwards we cut message from the end
if (backwards) {
for (i in cutted) {
if (thisChunk.length + cutted[cutted.length - i - 1].length <= config.MessageCharacterLimit - (beginMessage.length + endMessage.length + 2 + usedCount))
//thisChunk += cutted[i] + "\n";
thisChunk = cutted[cutted.length - i - 1] + "\n" + thisChunk;
else {
result.push(beginMessage + thisChunk + endMessage);
thisChunk = cutted[i];
}
}
return result;
}
else {
for (i in cutted) {
if (thisChunk.length + cutted[i].length <= config.MessageCharacterLimit - (beginMessage.length + endMessage.length + 2 + usedCount)) {
thisChunk += cutted[i] + "\n";
}
else {
result.push(beginMessage + thisChunk + endMessage);
thisChunk = cutted[i] + "\n";
}
}
//Add last chunk if it exists
if (thisChunk.length > 0)
result.push(beginMessage + thisChunk + endMessage);
return result;
}
}
else
return [beginMessage + message + endMessage];
}
//Return voiceChannel from a Member or return current voice channel that bot is on right now
function getVoiceChannel(Member) {
let currConnection = getCurrentVoiceConnection();
if (Member.voiceChannel)
return Member.voiceChannel;
else if (currConnection)
return currConnection.channel;
else
return null;
}
function prepareForPlaybackOnChannel(guildMember, permissionLevel = {}, joinStrict = false) {
return new Promise((resolve, reject) => {
if (guildMember.voiceChannel || getCurrentVoiceConnection()) {
if (getVoiceChannel(guildMember)) {
checkChannelJoin(getVoiceChannel(guildMember))
.then((connection) => { return resolve(connection); })
.catch(error => {
utils.report("Couldn't join channel. Error: " + error, 'r');
return resolve(null);
});
}
else {
sendInfoMessage("I dont have permission to join that channel!", client.channels.get(config.ReportChannelId), guildMember.user);
return resolve(null);
}
}
else {
sendInfoMessage("Join a voice channel first!", client.channels.get(config.ReportChannelId), guildMember.user);
return resolve(null);
}
});
}
//Return true if guildmember has specified bit of permission
function checkPermission(guildmember, bit=31, channel=null, postMessage=true) {
let permission = 0;
//We count bits from right to left
//SummonBot: 0
//DismissBot: 1
//PlayFiles: 2
//PlayYoutubeLinks: 3
//UploadLocalAudioFiles: 4
//DeleteLocalAudioFiles: 5
//RecieveListOfLocalAudios 6
//PauseResumeSkipPlayback 7
//RejoinChannel 8
//StopPlaybackClearQueue 9
//RenameLocalAudioFiles 10
//SetVolumeAbove100 11
//HideOwnRecords 12
//PlayRecordsIfWasOnTheChannel 13
//PlayAnyonesRecords: 14
//PlayRandomQuote 15
//RepeatLastPlayback 16
//DeleteOwnLocalAudioFiles 17
//RenameOwnLocalAudioFiles 18
//RequestSoundFilesSending 19
//If he is admin
if (config.permissions.AdminsList.indexOf(guildmember.user.id) > -1)
return true;
//If member is in the Blacklist
else if (config.permissions.BlackList.indexOf(guildmember.user.id) > -1)
return false;
//If Permission level is (Blacklist) or (Whitelist and Member has proper role)
else if (config.permissions.PermissionsLevel == 0 || (config.permissions.PermissionsLevel == 1 && guildmember.roles.array().some(Role => { return config.permissions.UserRolesList.includes(Role.id) || config.permissions.UserRolesList.includes(Role.name); }))) {
//Sum up permission bits
permission += config.permissions.User.SummonBot << 0;
permission += config.permissions.User.DismissBot << 1;
permission += config.permissions.User.PlayFiles << 2;
permission += config.permissions.User.PlayYoutubeLinks << 3;
permission += config.permissions.User.UploadLocalAudioFiles << 4;
permission += config.permissions.User.DeleteLocalAudioFiles << 5;
permission += config.permissions.User.RecieveListOfLocalAudios << 6;
permission += config.permissions.User.PauseResumeSkipPlayback << 7;
permission += config.permissions.User.RejoinChannel << 8;
permission += config.permissions.User.StopPlaybackClearQueue << 9;
permission += config.permissions.User.RenameLocalAudioFiles << 10;
permission += config.permissions.User.SetVolumeAbove100 << 11;
permission += config.permissions.User.HideOwnRecords << 12;
permission += config.permissions.User.PlayRecordsIfWasOnTheChannel << 13;
permission += config.permissions.User.PlayAnyonesRecords << 14;
permission += config.permissions.User.PlayRandomQuote << 15;
permission += config.permissions.User.RepeatLastPlayback << 16;
permission += config.permissions.User.DeleteOwnLocalAudioFiles << 17;
permission += config.permissions.User.RenameOwnLocalAudioFiles << 18;
permission += config.permissions.User.RequestSoundFilesSending << 19;
}
let result = (permission & (1 << bit)) > 0;
if (!result && postMessage)
sendInfoMessage("You don't have permission for that! :pensive:", channel ? channel : client.channels.get(config.ReportChannelId), guildmember.user);
return result;
}
//Recreate Audio Player to avoid buffer overloading and as a result delayed playback
function recreatePlayer(connection=null) {
let foundConnection = null;
if (connection)
foundConnection = connection;
else if (getCurrentVoiceConnection())
foundConnection = getCurrentVoiceConnection();
if (foundConnection) {
delete foundConnection.player;
foundConnection.player = new AudioPlayer(foundConnection);
}
}
//Return current client voice connection or null if there is none
function getCurrentVoiceConnection() {
if (client.voiceConnections ? client.voiceConnections.array().length > 0 : false)
return client.voiceConnections.array()[0];
else
return null;
}
//Write stats to database
function writeQueueToDB() {
if (queueDBWrite.length > 0) {
let dbTransaction = db.getDB().transaction(() => {
while (queueDBWrite.length > 0) {
let element = queueDBWrite.shift();
if (element.function == 'userPlayedSoundsInc') {
db.userPlayedSoundsInc(element.argument);
}
else if (element.function == 'soundPlayedInc') {
db.soundPlayedInc(element.argument);
}
else if (element.function == 'userPlayedRecsInc') {
db.userPlayedRecsInc(element.argument);
}
else if (element.function == 'userPlayedYoutubeInc') {
db.userPlayedYoutubeInc(element.argument);
}
else if (element.function == 'recordingAdd') {
db.recordingAdd(element.argument.target, element.argument.time, element.argument.duration, element.argument.userid, element.argument.filesize, element.argument.ignorePhrase, element.argument.channel, element.argument.usersListening );
}
}
});
dbTransaction();
}
}
// =============== SOUND FUNCTIONS ===============
//Destroy all voice recievers
function recieversDestroy() {
let connection = getCurrentVoiceConnection();
if (connection) {
if (config.logging.ConsoleReport.ChannelJoiningLeaving) utils.report("Leaving channel '" + connection.channel.name + "'!", 'g', config.logging.LogFileReport.ChannelJoiningLeaving);
db.AddUserActivity(0, connection.channel.id, 1);
connection.channel.leave();
}
}
//Start recording on currently connected channel
function startRecording(connection) {
return new Promise((resolve, reject) => {
//For some reason in order to recieve any incoming voice data from other members we need to send something first, therefore we are sending a very short sound and start the recording right after
const dispatcher = connection.playFile(path.resolve(__dirname, config.folders.Sounds, '00_empty.mp3'));
dispatcher.on('end', () => {
utils.report("Starting recording of '" + connection.channel.name + "' channel.", 'g')
const receiver = connection.createReceiver();
connection.on('speaking', (user, speaking) => {
if (speaking) {
const audioStream = receiver.createPCMStream(user);
let chunkCount = 0;
let totalStreamSize = 0;
let fileTimeNow = utils.fileTimeNow();
let tempfile = path.resolve(__dirname, config.folders.Temp, fileTimeNow.file + '_' + utils.sanitizeFilename(user.username));
const writable = fs.createWriteStream(tempfile + '.pcm');
audioStream.on('data', (chunk) => {
chunkCount++;
totalStreamSize += chunk.length;
});
//Write the data to the temp file
audioStream.pipe(writable);
audioStream.on('end', () => {
//Each chunk is 20 ms
let durationMs = chunkCount * 20;
if (config.logging.ConsoleReport.RecordDebugMessages) utils.report("Got " + chunkCount + " chunks with total size of " + totalStreamSize + " bytes from user '" + getUserName(user) + "'.", 'c', config.logging.LogFileReport.RecordDebugMessages); //debug message
if (durationMs > config.RecordingsDurationSkipThresholdMs) {
//let outputFile = path.resolve(__dirname, config.folders.VoiceRecording, fileTimeNow + '_' + utils.cutFillString(user.id, 20) + '_' + utils.cutFillString(durationMs, 10, '0') + '_' + utils.sanitizeFilename(getUserName(user)) + '.' + config.RecordingAudioContainer)
let targetFile = path.resolve(__dirname, config.folders.VoiceRecording, fileTimeNow.file + '_' + user.id + '_' + durationMs + '_' + utils.sanitizeFilename(getUserName(user)) + '.' + config.RecordingAudioContainer);
let FFcommand = ffmpeg(tempfile + '.pcm', { niceness: 20 })
.noVideo()
.inputOptions([
'-f', 's16le',
'-ac', '2',
'-ar', '48000'
])
.audioCodec(config.RecordingAudioCodec)
.audioBitrate(config.RecordingAudioBitrate)
.on('error', function (err) {
utils.report("ffmpeg reported error: " + err, 'r')
})
.on('end', function (stdout, stderr) {
if (config.logging.ConsoleReport.RecFilesSavedAndProcessed) utils.report("Saved recording of '" + user.username + "' with duration of " + durationMs + " ms (" + chunkCount + " chunks).", 'c', config.logging.LogFileReport.RecFilesSavedAndProcessed);
fs.unlink(tempfile + '.pcm', err => {
if (err) utils.report("Couldn't delete temp file '" + tempfile + "'. Error: " + err, 'r');
});
//Add to the database
fs.stat(targetFile, (err, stats) => {
if (!err) {
//db.recordingAdd(targetFile, fileTimeNow.now.getTime(), durationMs, user.id, stats.size, false, connection.channel.id, countChannelMembers(connection.channel));
queueDBWrite.push({ function: 'recordingAdd', argument: { target: targetFile, time: fileTimeNow.now.getTime(), duration: durationMs, userid: user.id, filesize: stats.size, ignorePhrase: false, channel: connection.channel.id, usersListening: countChannelMembers(connection.channel) } });
}
else
utils.report("Couldn't read file property of '" + targetFile + "'. Error: " + err, 'r');
});
})
.on('codecData', format => {
if (config.logging.ConsoleReport.RecordDebugMessages) utils.report("ffmpeg reports stream properties. Duration:" + format['duration'] + ", audio: " + format['audio_details'] + ".", 'c', config.logging.LogFileReport.RecordDebugMessages); //debug message
})
.on('start', function (commandLine) {
//if (config.logging.ConsoleReport.FfmpegDebug) utils.report('Spawned Ffmpeg with command: ' + commandLine, 'w', config.logging.LogFileReport.FfmpegDebug); //debug message
})
.output(targetFile)
.run();
}
else
fs.unlink(tempfile + '.pcm', err => {
if (err) utils.report("Couldn't delete temp file '" + tempfile + "'. Error: " + err, 'r');
});
});
}
})
connection.on('error', (err) => utils.report("There was an error in voice connection: " + err, 'r'));
return resolve(dispatcher);
});
dispatcher.on('error', error => utils.report("Couldn't play sound file '" + path.resolve(__dirname, config.folders.Sounds, '00_empty.mp3') + "' on'" + connection.channel.name + "' channel. Error: " + error, 'r'));
});
}
//Join voice channel actions
function joinVoiceChannel(channel) {
return new Promise((resolve, reject) => {
//First, delete all previously created recievers if we have any
recieversDestroy();
//Join the channel
channel.join()
.then(connection => {
if (config.logging.ConsoleReport.ChannelJoiningLeaving) utils.report("Joined channel '" + channel.name + "'!", 'g', config.logging.LogFileReport.ChannelJoiningLeaving);
db.AddUserActivity(0, channel.id, 0);
//If we have Voice Recording enabled, launch it
if (config.EnableRecording) {
startRecording(connection)
.then(() => { return resolve(connection); });
}
//Actions performed, empty the queue
LastChannelChangeTimeMs = Date.now();
ChannelWaitingToJoin = null;
})
.catch(error => {
utils.report("Couldn't join channel '" + channel.name + "'. Error: " + error, 'r');
return reject(error);
});
//Actions performed, empty the queue
LastChannelChangeTimeMs = Date.now();
ChannelWaitingToJoin = null;
});
}
//Join voice channel queue function
// We have channel that we want to join stored in 'ChannelWaitingToJoin', this is our joining
// queue (technically its not queue, only last channel since we dont need others but who cares).
// We check time since last joining. If it passed, we join strait away if not, we delay the function.
// If we dont do this and bot joins channels without waiting too quickly, we will get situation
// when we technically didnt leave previous channel and still have recievers on it resulting in bot crash
// due to VoiceConnection.authenticateFailed Error: Connection not established within 15 seconds
function joinVoiceChannelQueue(channel) {
return new Promise((resolve, reject) => {
//if channel exists
if (channel.name && channel.joinable) {
//If there is a channel in the queue, just reset the variable, command is queued, so dont run it again
if (ChannelWaitingToJoin) {
if (config.logging.ConsoleReport.ChannelDebugJoinQueue) utils.report("Channel join queue: There is a channel in the queue '" + ChannelWaitingToJoin.name + "', setting new channel: '" + channel.name + "'!", 'c', config.logging.LogFileReport.ChannelDebugJoinQueue); //debug message
ChannelWaitingToJoin = channel;
//Return Promise in expected time of channel changing plus 100ms
// todo: find a better solution for this, this is a very nasty way:
// it will return resolve() even if joining operation failed
setTimeout(() => {
let connToReturn = getCurrentVoiceConnection()
if (connToReturn)
return resolve(connToReturn);
throw new Error("Couldn't join channel in given time. Try again.")
}, (config.ChannelJoiningQueueWaitTimeMs - (Date.now() - LastChannelChangeTimeMs) + 100));
}
else {
let JoinHappendMsAgo = Date.now() - LastChannelChangeTimeMs;
if (JoinHappendMsAgo >= config.ChannelJoiningQueueWaitTimeMs) {
//We can run it without waiting
if (config.logging.ConsoleReport.ChannelDebugJoinQueue) utils.report("Channel join queue: Joining '" + channel.name + "' channel without any delay!", 'c', config.logging.LogFileReport.ChannelDebugJoinQueue); //debug message
joinVoiceChannel(channel)
.then((connection) => { return resolve(connection); })
.catch(error => { return reject(error); });
}
else {
//Delay joining
ChannelWaitingToJoin = channel;
if (config.logging.ConsoleReport.ChannelDebugJoinQueue) utils.report("Channel join queue: Delaying joining '" + ChannelWaitingToJoin.name + "' channel by " + Math.floor(config.ChannelJoiningQueueWaitTimeMs - JoinHappendMsAgo) + " ms!", 'c', config.logging.LogFileReport.ChannelDebugJoinQueue); //debug message
setTimeout(() => {
joinVoiceChannel(ChannelWaitingToJoin)
.then((connection) => { return resolve(connection); })
.catch(error => { return reject(error); });
}, (config.ChannelJoiningQueueWaitTimeMs - JoinHappendMsAgo));
}
}
}
else
return reject("No permission to join the channel.");
});
}
//Check for arguments in the command
function checkForEmptyArguments(args = [], channel = null, author = null) {
let noArguments = true;
for (i in args) {
if (args[i].length > 0) {
noArguments = false;
break;
}
}
if (noArguments)
sendInfoMessage("You did not specify any arguments in your command!", channel, author);
return noArguments;
}
//Check if we are on the channel, if we are - do nothing, if not - join it
function checkChannelJoin(channel) {
return new Promise((resolve, reject) => {
let haveConnection = false;
let connToReturn = getCurrentVoiceConnection();
if (connToReturn) {
haveConnection = true;
return resolve(connToReturn);
}
//No connection found, create new one
if (channel) {
if (!haveConnection) {
joinVoiceChannelQueue(channel)
.then((connection) => { return resolve(connection); })
.catch(error => { return reject(error); });
}
}
else
throw new Error("Join a voice channel first!")
});
}
//Set current volume level to desired value
function setVolume(volume, time) {
let currConnection = getCurrentVoiceConnection();
if (currConnection) {
let iterations = Math.floor(time / 20);
let volDelta = (volume - CurrentVolume) / iterations;
//Each packet sent is 20ms long, so no need to change it more often since it won't have any effect
volumeIterate(currConnection.dispatcher, iterations, 20, volDelta, CurrentVolume);
CurrentVolume = volume;
}
}
//Smoothly change the volume by iterations with a wait period
function volumeIterate(dispatcher, itLeft, waitperiod, volumeChange, volumeNow) {
if (itLeft > 0) {
let newVolume = volumeNow + volumeChange;
//console.log("VolumeIteration: # " + itLeft + ", waitPeriod: " + waitperiod+" ms,volumeChange: " + volumeChange + ", newVolumeSet: " + newVolume); //Debug
dispatcher.setVolume(newVolume);
CurrentVolume = newVolume;
setTimeout(() => {
volumeIterate(dispatcher, itLeft - 1, waitperiod, volumeChange, newVolume);
}, waitperiod);
}
}
//What to do when ffmpeg stream is ready to be executed
function executeFFMPEG(connection, PlaybackOptions, inputObject, inputList, mode = { how: 'concat' }) {
const processed = utils.processStream(inputObject, inputList, mode);
if (processed) {
//Redirect to an output
let target = utils.get(inputObject, 'flags.target');
if (target) {
PreparingToPlaySound = false;
target = utils.targetFileCheck(inputObject);
if (target) {
let tempFile = path.resolve(__dirname, config.folders.Temp, target);
let targetFile = path.resolve(__dirname, config.folders.Sounds, target);
processed
.audioCodec(config.ConvertUploadedAudioCodec)
.audioBitrate(config.ConvertUploadedAudioBitrate)
.output(tempFile)
.on('end', function (stdout, stderr) {
//Move file to Sounds dir
utils.moveFile(tempFile, targetFile)
.then(() => {
utils.checkAudioFormat(targetFile)
.then(resultNew => {
fs.stat(targetFile, (err, stats) => {
if (!err) {
let transaction = db.getDB().transaction(() => {
db.userUploadedSoundsInc(inputObject.user.id); //Increment value in DB for statistics
db.soundUpdateAdd(path.parse(targetFile).name + path.parse(targetFile).ext, resultNew['metadata']['format']['duration'], fs.statSync(targetFile).size, resultNew['metadata']['format']['bitrate'], inputObject.user.id);
});
transaction();
sendInfoMessage("File saved! Now you can play it using **" + config.CommandCharacter + path.parse(targetFile).name.toLowerCase() + "** command.", client.channels.get(config.ReportChannelId), inputObject.user.user);
if (inputObject.type == 'file') {
utils.report(getUserName(inputObject.user.user) + " resaved file '" + inputObject.filename + "' with duration of " + resultNew['metadata']['format']['duration'] + " seconds as a command '" + path.parse(targetFile).name.toLowerCase() + "'.", 'm');
}
else if (inputObject.type == 'recording' && inputObject.mode.how == 'phrase') {
utils.report(getUserName(inputObject.user.user) + " saved quote said by '" + db.getUserGuildName(inputObject.searchresult.author) + "' at " + utils.getDateFormatted(inputObject.limits.start, "D MMM YYYY, HH:mm z") + " with duration of " + resultNew['metadata']['format']['duration'] + " seconds as a command '" + path.parse(targetFile).name.toLowerCase() + "'.", 'm');
}
else if (inputObject.type == 'youtube') {
utils.report(getUserName(inputObject.user.user) + " saved YouTube '" + inputObject.title.substring(0, config.YoutubeTitleLengthLimit) + "' (" + inputObject.link + ") with result duration of " + resultNew['metadata']['format']['duration'] + " seconds as a command '" + path.parse(targetFile).name.toLowerCase() + "'.", 'm');
}
}
else {
utils.report("Couldn't read file property of '" + targetFile + "'. Error: " + err, 'r');
sendInfoMessage("Something went wrong while processing the file :pensive: ", client.channels.get(config.ReportChannelId), inputObject.user.user);
}
});
});
//db.scanSoundsFolder();
})
.catch(err => {
sendInfoMessage("There was an error while performing file move! Operation was not finished.", client.channels.get(config.ReportChannelId), inputObject.user.user);
utils.report("Couldn't move file '" + tempFile + "' to '" + targetFile + "'. Check permissions or disk space.", 'r');
});
})
.on('start', function (commandLine) {
if (config.logging.ConsoleReport.FfmpegDebug) utils.report('Spawned Ffmpeg with command: ' + commandLine, 'w', config.logging.LogFileReport.FfmpegDebug); //debug message
sendInfoMessage("Started processing... Please, wait (this may take a while).", client.channels.get(config.ReportChannelId), inputObject.user.user);
//ffmpegPlaybackCommands.push(command);
})
.on('error', function (err) {
utils.report("ffmpeg reported " + err, 'r');
if (process.platform === "linux")
processed.kill('SIGSTOP'); //This does not work on Windows
//command.kill();
})
.run();
}
else {
sendInfoMessage("Can't execute it! (Bad filename?)", client.channels.get(config.ReportChannelId), inputObject.user.user);
}
}
//Play on current channel
else {
connection.playConvertedStream(processed, PlaybackOptions);
//Attach event listeners
attachEventsOnPlayback(connection);
//Report information
if (inputObject.type == 'file') {
playbackMessage(":musical_note: Playing file `" + CurrentPlayingSound.filename + "`" + utils.flagsToString(inputObject.flags) + ", duration " + utils.humanTime(CurrentPlayingSound.duration) + ". Requested by " + getUserTagName(CurrentPlayingSound.user) + "." + (inputObject.played ? " Resuming from " + Math.round(inputObject.played / 1000) + " second!" : ""));
}
else if (inputObject.type == 'recording') {
if ((inputObject.chunkIndex == 1 || !inputObject.chunkIndex) && inputObject.mode.how == 'sequence')
playbackMessage(":record_button: Playing recording of `" + utils.getDateFormatted(inputObject.limits.start, "D MMM YYYY, HH:mm") + " - " + utils.getDateFormatted(inputObject.limits.end, "HH:mm z") + "` period" + utils.flagsToString(inputObject.flags) + ", duration " + utils.humanTime(inputObject.duration / 1000) + ". Requested by " + getUserTagName(CurrentPlayingSound.user) + "." + (inputObject.played ? " Resuming from " + Math.round(inputObject.played / 1000) + " second!" : ""));
else if (inputObject.mode.how == 'phrase') {
//Get name of that user
//let quotedUser = client.guilds.get(config.guildId).members.get()
let userName = "<@" + inputObject.searchresult.author + ">";
let guildUserName = db.getUserGuildName(inputObject.searchresult.author);
if (guildUserName)
userName = "**" + guildUserName + "**";
playbackMessage(":speaking_head: Playing quote of " + userName + " `" + utils.getDateFormatted(inputObject.limits.start, "D MMM YYYY, HH:mm z") + "`" + utils.flagsToString(inputObject.flags) + ", duration " + utils.humanTime(inputObject.duration / 1000) + ". Requested by " + getUserTagName(inputObject.user) + "." + (inputObject.played ? " Resuming from " + Math.round(inputObject.played / 1000) + " second!" : ""));
}
}
else if (inputObject.type == 'youtube') {
playbackMessage(":musical_note: Playing Youtube `" + inputObject.title.substring(0, config.YoutubeTitleLengthLimit) + "`" + utils.flagsToString(inputObject.flags) + " (duration " + utils.humanTime(inputObject.duration) + "). Requested by " + getUserTagName(inputObject.user) + ". <" + inputObject.link + ">");
}
}
}
}
//Add sound to the playing queue
function addToQueue(soundToPlay, method = 'append') {
//Append to the end of the queue
if (method == 'append') {
PlayingQueue.push(soundToPlay);
}
//Add as first element in the queue shifting all others
else {
PlayingQueue.unshift(soundToPlay);
}
}
//Attach event listener to connection dispatcher when playback starts
function attachEventsOnPlayback(connection) {
//What to do in the end of the playback
connection.dispatcher.on('end', (reason) => {
checkedDataStart = null;
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("Finished playing! Reason: " + reason, 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
soundIsPlaying = false;
handleQueue(reason);
LastPlaybackTime = Date.now();
//Recreate player in 1 second if nothing else is playing and write stats to DB
setTimeout(() => {
if (!soundIsPlaying && !PreparingToPlaySound) {
recreatePlayer();
writeQueueToDB();
}
}, 1000);
});
connection.dispatcher.on('start', () => {
//For debugging responce timings
if (config.logging.ConsoleReport.DelayDebug) {
utils.report(utils.msCount("Playback") + " Started playing!.", 'c', config.logging.LogFileReport.DelayDebug); //debug message
}
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("Started playing!", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
PreparingToPlaySound = false;
soundIsPlaying = true;
//console.log(connection.player);
});
connection.dispatcher.on('speaking', (message) => {
//For debugging responce timings
if (config.logging.ConsoleReport.DelayDebug) {
utils.report(utils.msCount("Playback", 'reset') + " Dispatcher debug: " + message, 'c', config.logging.LogFileReport.DelayDebug); //debug message
}
});
connection.dispatcher.on('error', (error) => {
if (config.logging.ConsoleReport.DelayDebug) utils.report(utils.msCount("Playback", 'reset') + " Error playing!.", 'c', config.logging.LogFileReport.DelayDebug); //debug message
utils.report('Dispatcher error while playing the file: ' + error, 'r');
PreparingToPlaySound = false;
soundIsPlaying = false;
LastPlaybackTime = Date.now();
});
}
//Send file
function sendSoundFile(file, channel, filename=null) {
return new Promise((resolve, reject) => {
if (BotReady) {
let channelUserName = (channel.type == "dm" ? "user '" + utils.get(client.guilds.get(config.guildId).members.get(channel.id), 'name') + "'" : "channel '" + channel.name + "'") + " (" + channel.id + ")";
// Send a local file
channel.send({
files: [{
attachment: file,
name: filename ? filename : path.parse(file).name + path.parse(file).ext
}]
})
.then(message => {
utils.report('Sent file "' + path.parse(file).name + path.parse(file).ext + '" of size ' + Math.round(utils.get(message.attachments.first(), 'filesize') / 1024) + ' Kb to ' + channelUserName, 'm');
return resolve();
})
.catch(error => {
utils.report('Error sending the file: "' + file + '": ' + error, 'r');
return resolve(error);
});
}
});
}
//Process and send sound file if requested
function processRequestedFileQueue() {
if (GetFileQueue.length) {
inputObject = GetFileQueue.shift();
if (inputObject.type == 'file') {
//If there are no effects, return original file without reencoding
if (!utils.get(inputObject, "flags.effects")) {
sendSoundFile(path.resolve(__dirname, config.folders.Sounds, inputObject.filename), inputObject.flags.getCommandChannel);
processRequestedFileQueue();
}
//else, create new file
else {
const processed = utils.processStream(inputObject, [{ file: path.resolve(__dirname, config.folders.Sounds, inputObject.filename) }], { how: 'concat' }, true);
if (processed) {
let targetFile = path.resolve(__dirname, config.folders.Temp, utils.sanitizeFilename(inputObject.filename) + '_withEffects' + '.' + config.RecordingAudioContainer);
processed
.audioCodec(config.RecordingAudioCodec)
.audioBitrate(config.RecordingAudioBitrate)
.on('error', function (err) {
utils.report("ffmpeg reported error: " + err, 'r');
utils.deleteFile(targetFile);
})
.on('end', function (stdout, stderr) {
sendSoundFile(targetFile, inputObject.flags.getCommandChannel)
.then(() => utils.deleteFile(targetFile));
processRequestedFileQueue();
})
.on('codecData', format => {
if (config.logging.ConsoleReport.RecordDebugMessages) utils.report("ffmpeg reports stream properties. Duration:" + format['duration'] + ", audio: " + format['audio_details'] + ".", 'c', config.logging.LogFileReport.RecordDebugMessages); //debug message
})
.on('start', function (commandLine) {
//if (config.logging.ConsoleReport.FfmpegDebug) utils.report('Spawned Ffmpeg with command: ' + commandLine, 'w', config.logging.LogFileReport.FfmpegDebug); //debug message
})
.output(targetFile)
.run();
}
}
}
else if (inputObject.type == 'recording') {
let lastChunkReportTime = new Date();
let totalDurationMs = inputObject.searchresult.totalAudioDuration;
let chunkCount = inputObject.chunks ? inputObject.chunks : 1;
let chunksArray = [];
let startTime = new Date(inputObject.searchresult.startTime);
chunksArray.push(inputObject);
for (let c = 1; c < chunkCount; c++) {
let nextChunkResult = db.makeRecFileList(chunksArray[chunksArray.length - 1].searchresult.endTime, chunksArray[chunksArray.length - 1].mode, config.SearchHoursPeriod * 3600000, chunksArray[chunksArray.length - 1].usersList);
let QueueElement = { 'type': 'recording', 'searchresult': nextChunkResult, 'usersList': chunksArray[chunksArray.length - 1].usersList, 'mode': chunksArray[chunksArray.length - 1].mode, 'chunkIndex': chunksArray[chunksArray.length - 1].chunkIndex + 1, 'chunks': chunksArray[chunksArray.length - 1].chunks, 'user': chunksArray[chunksArray.length - 1].user, 'flags': chunksArray[chunksArray.length - 1].flags, 'duration': chunksArray[chunksArray.length - 1].duration };
if (nextChunkResult) {
chunksArray.push(QueueElement);
totalDurationMs += nextChunkResult.totalAudioDuration;
//console.log("Iteration " + c + " of " + chunkCount + ".Adding chunk #" + QueueElement.chunkIndex + " to the list.");
}
}
let chunkFilesList = [];
//console.log("Reporting " + chunkCount + " chunks with total duration of " + Math.round(totalDurationMs / 60000) + " minutes.");
//First, save all chunks as separate files
async.eachLimit(chunksArray, config.FileRequestsParallelProcessLimit, (chunkObject, callback) => {
const processed = utils.processStream(chunkObject, chunkObject.searchresult.list, { how: chunkObject.searchresult.method, channels: chunkObject.searchresult.channelsToMix }, true);
if (processed) {
let targetFile = path.resolve(__dirname, config.folders.Temp, "recChunk_" + utils.pad(chunkObject.chunkIndex, 3) + utils.fileTimeNow(new Date(chunkObject.searchresult.startTime)).file + '.' + config.RecordingAudioContainer);
//console.log("Creating chunk #" + chunkObject.chunkIndex + " of " + chunkFilesList.length + " total (Used " + chunkObject.searchresult.list.length + " files).");
processed
.audioCodec(config.RecordingAudioCodec)
.audioBitrate(config.RecordingAudioBitrate)
.on('error', function (err) {
utils.report("ffmpeg reported error: " + err, 'r');
utils.deleteFile(targetFile);
})
.on('end', function (stdout, stderr) {
//sendSoundFile(targetFile, chunkObject.flags.getCommandChannel)
// .then(() => utils.deleteFile(targetFile));
chunkFilesList[chunkCount > 1 ? chunkObject.chunkIndex - 1 : 0] = targetFile;
//Periodically report progress
if (Date.now() - lastChunkReportTime >= 5000) {
utils.report("Creating chunks: " + chunkObject.chunkIndex + "/" + chunkCount + " (" + (Math.round(10000 * chunkObject.chunkIndex / chunkCount) / 100) + " %) done...", 'c', false);
sendInfoMessage("Creating combined file (" + (Math.round(100 * chunkObject.chunkIndex / chunkCount)) + "% done so far), please wait...", inputObject.flags.getCommandChannel, inputObject.user.user);
lastChunkReportTime = Date.now();
}
callback();
})
.on('codecData', format => {
if (config.logging.ConsoleReport.RecordDebugMessages) utils.report("ffmpeg reports stream properties. Duration:" + format['duration'] + ", audio: " + format['audio_details'] + ".", 'c', config.logging.LogFileReport.RecordDebugMessages); //debug message
})
.on('start', function (commandLine) {
//if (config.logging.ConsoleReport.FfmpegDebug) utils.report('Spawned Ffmpeg with command: ' + commandLine, 'w', config.logging.LogFileReport.FfmpegDebug); //debug message
})
.output(targetFile)
.run();
//executeFFMPEG(connection, PlaybackOptions, inputObject, inputObject.searchresult.list, { how: inputObject.searchresult.method, channels: inputObject.searchresult.channelsToMix });
}
}, () => {
//Second, combine all chunks to one file and send it
//Create concat file for ffmpeg
let concatTextContents = "";
chunkFilesList.forEach(element => {
concatTextContents += "file '"+element + "'\n";
});
let concateFile = path.resolve(__dirname, config.folders.Temp, utils.fileTimeNow(new Date(startTime)).file) + "_conc.txt";
fs.writeFile(concateFile, concatTextContents, function (err, data) {
if (!err) {
let targetFile = path.resolve(__dirname, config.folders.Temp, utils.fileTimeNow(new Date(startTime)).file + '_' + Math.round(totalDurationMs/60000) + 'minutes' + '.' + config.RecordingAudioContainer);
let FFcommand = ffmpeg(concateFile, { niceness: 20 })
.inputOptions(['-f concat', '-safe 0'])
.audioCodec('copy')
.on('error', function (err) {
utils.report("ffmpeg reported error: " + err, 'r');
utils.deleteFiles(chunkFilesList);
utils.deleteFile(concateFile);
})
.on('end', function (stdout, stderr) {
utils.deleteFiles(chunkFilesList);
utils.deleteFile(concateFile);
processRequestedFileQueue();
//Add to the database
fs.stat(targetFile, (err, stats) => {
if (!err) {
if (stats.size < 8000000)
sendSoundFile(targetFile, inputObject.flags.getCommandChannel)
.then(() => utils.deleteFile(targetFile));
else
utils.report("File '" + path.parse(targetFile).name + path.parse(targetFile).ext + "' was too big to be sent (" + Math.round(stats.size / 1048576) + " Mb). Take it from Temp folder please! ", 'y');
//queueDBWrite.push({ function: 'recordingAdd', argument: { target: targetFile, time: fileTimeNow.now.getTime(), duration: durationMs, userid: user.id, filesize: stats.size, ignorePhrase: false, channel: connection.channel.id, usersListening: countChannelMembers(connection.channel) } });
}
else
utils.report("Couldn't read file property of '" + targetFile + "'. Error: " + err, 'r');
});
})
.on('codecData', format => {
if (config.logging.ConsoleReport.RecordDebugMessages) utils.report("ffmpeg reports stream properties. Duration:" + format['duration'] + ", audio: " + format['audio_details'] + ".", 'c', config.logging.LogFileReport.RecordDebugMessages); //debug message
})
.on('start', function (commandLine) {
//if (config.logging.ConsoleReport.FfmpegDebug) utils.report('Spawned Ffmpeg with command: ' + commandLine, 'w', config.logging.LogFileReport.FfmpegDebug); //debug message
})
.output(targetFile)
.run();
}
else {
utils.report("Error while writing concat txt file: " + err, 'r');
utils.deleteFiles(chunkFilesList);
}
});
});
}
}
}
//Playing next sound in the queue
function playQueue(connection) {
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("playQueue PASSED!", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
if (!PreparingToPlaySound) {
PreparingToPlaySound = true;
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("PreparingToPlaySound PASSED", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
//First we check if we are on a channel
if (connection.channel) {
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("connection.channel PASSED", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
//If nothing is playing and there is still somethign in the queue
if (!soundIsPlaying && PlayingQueue.length > 0) {
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("soundIsPlaying PASSED", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
//Get next sound from the queue
let inputObject = PlayingQueue.shift();
let PlaybackOptions = {};
//If it does not have a target, remember this command in the history
if (!utils.get(inputObject, 'flags.target'))
addHistoryPlaybackElement(inputObject);
if (inputObject.type == 'file') {
if (config.logging.ConsoleReport.SoundsPlaybackDebug) utils.report("inputObject.type PASSED", 'c', config.logging.LogFileReport.SoundsPlaybackDebug); //debug message
CurrentPlayingSound = { 'type': 'file', 'path': path.resolve(__dirname, config.folders.Sounds, inputObject.filename), 'filename': inputObject.filename, 'duration': inputObject.duration, 'user': inputObject.user, 'flags': inputObject.flags };
if (inputObject.played) CurrentPlayingSound['played'] = inputObject.played;
CurrentVolume = inputObject.flags.volume ? calcVolumeToSet(inputObject.flags.volume > 100 ? (checkPermission(inputObject.user, 11) ? inputObject.flags.volume : 100 ) : inputObject.flags.volume) : calcVolumeToSet(db.getUserVolume(inputObject.user.id));
PlaybackOptions = { 'volume': CurrentVolume, 'passes': config.VoicePacketPasses, 'bitrate': 'auto' };
if (inputObject.played) PlaybackOptions['seek'] = inputObject.played / 1000;
if (config.logging.ConsoleReport.DelayDebug) utils.report(utils.msCount("Playback") + " Creating File dispatcher...", 'c', config.logging.LogFileReport.DelayDebug); //debug message
queueDBWrite.push({ function: 'userPlayedSoundsInc', argument: inputObject.user.id });
queueDBWrite.push({ function: 'soundPlayedInc', argument: inputObject.filename });
//db.userPlayedSoundsInc(inputObject.user.id); //Increment value in DB for statistics
//db.soundPlayedInc(inputObject.filename); //Increment value in DB for statistics
//let ffstream = utils.processStream([{ file: path.resolve(__dirname, config.folders.Sounds, inputObject.filename) }], inputObject.flags, utils.get(inputObject, 'flags.target'));
//connection.playConvertedStream(ffstream, PlaybackOptions);
executeFFMPEG(connection, PlaybackOptions, inputObject, [{ file: path.resolve(__dirname, config.folders.Sounds, inputObject.filename) }]);
}
//QueueElement = { 'type': 'recording', 'searchresult': found, 'user': guildMember, 'flags': additionalFlags };
else if (inputObject.type == 'recording') {
if (inputObject.chunks) {
//If its not the last chunk, add next one to the queue
if (inputObject.chunkIndex < inputObject.chunks) {
let nextChunkResult = db.makeRecFileList(inputObject.searchresult.endTime, inputObject.mode, config.SearchHoursPeriod * 3600000, inputObject.usersList);
let QueueElement = { 'type': 'recording', 'searchresult': nextChunkResult, 'usersList': inputObject.usersList, 'mode': inputObject.mode, 'chunkIndex': inputObject.chunkIndex + 1, 'chunks': inputObject.chunks, 'user': inputObject.user, 'flags': inputObject.flags, 'duration': inputObject.duration };
PlayingQueue.unshift(QueueElement);
}
utils.report('Playing next recording chunk #' + inputObject.chunkIndex + ' of ' + inputObject.chunks, 'g');
}
CurrentPlayingSound = { 'type': 'recording', 'searchresult': inputObject.searchresult, 'duration': inputObject.duration, 'user': inputObject.user, 'flags': inputObject.flags };
CurrentVolume = inputObject.flags.volume ? calcVolumeToSet(inputObject.flags.volume) : calcVolumeToSet(db.getUserVolume(inputObject.user.id));
PlaybackOptions = { 'volume': CurrentVolume, 'passes': config.VoicePacketPasses, 'bitrate': 'auto' };
if (config.logging.ConsoleReport.DelayDebug) utils.report(utils.msCount("Playback") + " Creating File dispatcher...", 'c', config.logging.LogFileReport.DelayDebug); //debug message
queueDBWrite.push({ function: 'userPlayedRecsInc', argument: inputObject.user.id });
//db.userPlayedRecsInc(inputObject.user.id); //Increment value in DB for statistics
//let ffstream = utils.processStream(inputObject.searchresult.list, inputObject.flags, utils.get(inputObject, 'flags.target'), { how: inputObject.searchresult.method, channels: inputObject.searchresult.channelsToMix });
//connection.playConvertedStream(ffstream, PlaybackOptions);
executeFFMPEG(connection, PlaybackOptions, inputObject, inputObject.searchresult.list, { how: inputObject.searchresult.method, channels: inputObject.searchresult.channelsToMix });
}
else if (inputObject.type == 'youtube') {
let YtOptions = { quality: 'highestaudio' };
let recievedInfo = false;
let YTinfo = {};
if (config.UseAudioOnlyFilterForYoutube) YtOptions['filter'] = 'audioonly';
//'begin' parameter should be greather than 6 seconds: https://github.com/fent/node-ytdl-core/issues/129
// sometimes its not working
if (inputObject.played && inputObject.played > 7000 && !config.UseAudioOnlyFilterForYoutube) YtOptions['begin'] = Math.floor(inputObject.played / 1000) + "s";
if (config.logging.ConsoleReport.DelayDebug) utils.report(utils.msCount("Playback") + " creating stream... for '" + inputObject["link"]+"'", 'c', config.logging.LogFileReport.DelayDebug); //debug message
queueDBWrite.push({ function: 'userPlayedYoutubeInc', argument: inputObject.user.id });
//db.userPlayedYoutubeInc(inputObject.user.id); //Increment value in DB for statistics
//Create the stream