forked from waiwong614/alexa-tube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1322 lines (1015 loc) · 48.7 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
'use strict';
const AWS = require('aws-sdk');
const dropboxV2Api = require('dropbox-v2-api');
var search = require('youtube-search');
var google = require('./node_modules/googleapis');
const ytdl = require('ytdl-core');
var Stream = require('stream');
var url = 'http://youtube.com/watch?v='
var fs = require('fs');
var API_KEY = process.env['API_KEY'];
var dropbox_token = process.env['DROPBOX_TOKEN'];
var ffmpeg = require('fluent-ffmpeg');
const dropbox = dropboxV2Api.authenticate({
token: dropbox_token
});
const audioOutput = '/tmp/sound.m4a'
const mainOutput = '/tmp/output.m4a'
const dbfile = 'audio.mp4'
var maxdata = 1048576000 // default max data limit - this is deliberately set to 1000MB rather than 1 Gig to allow headroom for settings.js transfers plus any other skills running
var datachargerate = 0.090 // this is the AWS Data transfer charge per Gigabyte first 10 TB / month data transfer out beyond the global free tier
var destructrequestactive = false
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
var maxresults = 25
var partsize = 60*30 // size of the audio chunks in seconds
if (process.env['PART_SIZE_SECS']){
partsize = process.env['PART_SIZE_SECS']
console.log('Partsize over-ridden to ', partsize)
}
if (process.env['MAX_RESULTS']){
maxresults = process.env['MAX_RESULTS']
console.log('Max results over-ridden to ', maxresults)
}
if (process.env['MAX_DATA']){
maxdata = process.env['MAX_DATA']
console.log('Max data over-ridden to ', maxdata)
}
if (process.env['CHARGE_PER_GIG']){
datachargerate = process.env['CHARGE_PER_GIG']
console.log('Data charge rate over-ridden to ', datachargerate)
}
var opts = {
maxResults: maxresults,
type: 'video',
key: API_KEY
};
var settings = new Object();
var streamURL;
exports.handler = function(event, context) {
var player = new alextube(event, context);
player.handle();
};
var alextube = function (event, context) {
this.event = event;
this.context = context;
};
alextube.prototype.handle = function () {
var requestType = this.event.request.type;
var userId = this.event.context ? this.event.context.System.user.userId : this.event.session.user.userId;
console.log(JSON.stringify(this.event))
if (requestType === "LaunchRequest") {
this.speak('Welcome to youtube. What are you searching for?', true)
} else if (requestType === "IntentRequest") {
var intent = this.event.request.intent;
if (!process.env['API_KEY']){
this.speak('API KEY Environment Variable not set!')
}
if (!process.env['DROPBOX_TOKEN']){
this.speak('DROPBOX TOKEN Environment Variable not set!')
}
if (destructrequestactive == true && intent.name === "DestructCode") {
console.log('Recieved Destuct')
destructrequestactive = false;
this.raisemax()
} else if (destructrequestactive == false && intent.name === "DestructCode") {
console.log('Recieved Destuct')
this.speak('You must ask to raise the data limit before using this code')
} else if (destructrequestactive == true && intent.name !== "DestructCode") {
console.log('Did not receive Destuct code')
destructrequestactive = false;
this.speak('You did not give a correct code')
}
else {
destructrequestactive = false
}
if (intent.name === "SearchIntent") {
var foundTitle;
var searchFunction = this
console.log('Starting Search Intent')
var alexaUtteranceText = this.event.request.intent.slots.search.value;
console.log ('Search term is : - '+ alexaUtteranceText);
if (!alexaUtteranceText){
searchFunction.speak("I'm sorry I didn't understand what you said")
}
search(alexaUtteranceText, opts, function(err, results) {
if(err) {
console.log(err)
searchFunction.speakWithCard('I got an error from the Youtube API. Check the API Key has been copied into the Lambda environment variable properly, with no extra spaces before or after the Key', 'YOUTUBE API ERROR', 'I got an error from the Youtube API. \nCheck the API Key has been copied into the API_KEY Lambda environment variable properly, with no extra spaces before or after the Key')
}
else {
console.log('number of results is', results.length)
settings.results = results
settings.currentresult = 0
settings.previousURL = null;
settings.previousresult = 0;
var tracksettings= [];
var playlist=[];
for (var count = 0; count <= results.length-1; count++) {
playlist[count] = 'Track ' + (count +1) +': ' + results[count].title
var object = {
"id": count,
"title": results[count].title,
"duration": null,
"parts": null,
"currentpart": 0
}
tracksettings.push(object)
}
settings.tracksettings = tracksettings;
settings.playlist = playlist
searchFunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
searchFunction.speakWithCard('I got an error from the Dropbox API. Check the API Token has been copied into the Lambda environment variable properly, with no extra spaces before or after the Token', 'YOUTUBE DROPBOX ERROR', 'I got an error from the Dropbox API. \nCheck the Token has been copied into the DROPBOX_TOKEN Lambda environment variable properly, with no extra spaces before or after the Token')
} else {
searchFunction.loadSettings(function(err, result) {
if (err) {
searchFunction.speak('There was an error loading settings from dropbox')
} else {
if (typeof settings.autoplay == 'undefined'){
console.log('No autoplay setting exists - creating')
settings.autoplay ='on'
}
if (typeof settings.shuffle == 'undefined'){
console.log('No shuffle setting exists - creating')
settings.shuffle = 'off'
}
if (typeof settings.loop == 'undefined'){
console.log('No loop setting exists - creating')
settings.loop = 'off'
}
if (typeof settings.dataused == 'undefined'){
console.log('No dataused setting exists - creating')
settings.dataused = 0
}
if (typeof settings.maxdata == 'undefined'){
console.log('No maxdata setting exists - creating')
settings.maxdata = maxdata
}
if (typeof settings.currentmonth == 'undefined'){
console.log('No month setting exists - creating')
var timedate = new Date();
settings.currentmonth = timedate.getMonth();
}
var timedatecheck = new Date();
var currentmonth = timedatecheck.getMonth();
if (settings.currentmonth !== currentmonth )
console.log('******New month detected - resetting stats*******')
settings.currentmonth = currentmonth
settings.dataused = 0
settings.maxdata = maxdata
if (settings.shuffle == 'on'){
settings.currentresult = Math.floor((Math.random() * (results.length-1) ));
}
if (settings.dataused >= settings.maxdata){
searchFunction.speakWithCard('Maximum monthly data usage exceeded', 'WARNING', 'Maximum monthly data usage exceeded')
}
console.log('Max data usage setting in GB ', settings.maxdata/1048576)
console.log('Current data usage in GB ', settings.dataused/1048576)
searchFunction.processResult(0, null, 0);
}
});
}
});
}
});
} else if (intent.name === "NowPlayingIntent") {
console.log('Starting Now playing Intent')
var nowfunction = this;
this.loadSettings(function(err, result) {
if (err) {
nowfunction.speak('There was an error loading settings from dropbox')
} else {
var currentresult = settings.currentresult
var enqueuestatus = settings.enqueue
if (enqueuestatus == true){
console.log('Song already enqueued')
currentresult--
}
var results = settings.results
var title = results[currentresult].title
var cardTitle = "📺 Playing - " + title + ' 📺'
var cardText = nowfunction.createPlaylist(currentresult)
nowfunction.speakWithCard('Currently Playing ' + title, cardTitle, cardText)
}
});
}
else if (intent.name === "AutoOn") {
console.log('Starting Auto On Intent')
this.autoMode('on')
} else if (intent.name === "AutoOff") {
console.log('Starting Auto Off Intent')
this.autoMode('off')
}else if (intent.name === "ResetLimit") {
console.log('Received Reset limit')
this.resetmax()
}else if (intent.name === "RaiseLimit") {
console.log('Received Raise limit')
destructrequestactive = true;
this.speak('Request to raise data limit received. Please give the authorisation code', true)
} else if (intent.name === "NumberIntent") {
console.log('Starting number Intent')
var number = this.event.request.intent.slots.number.value;
this.numberedTrack(number)
}else if (intent.name === "AMAZON.StopIntent") {
console.log('Starting number Intent')
console.log('Running STOP intent')
this.stop();
} else if (intent.name === "AMAZON.PauseIntent") {
console.log('Running pause intent')
this.stop();
} else if (intent.name === "AMAZON.CancelIntent") {
this.speak(' ')
} else if (intent.name === "AMAZON.NextIntent") {
this.next();
} else if (intent.name === "AMAZON.PreviousIntent") {
this.previous();
} else if (intent.name === "AMAZON.ShuffleOffIntent") {
this.shuffle('off');
} else if (intent.name === "AMAZON.ShuffleOnIntent") {
this.shuffle('on');
}else if (intent.name === "AMAZON.LoopOnIntent") {
this.loop('on');
}else if (intent.name === "AMAZON.LoopOffIntent") {
this.loop('off');
}else if (intent.name === "AMAZON.RepeatIntent") {
this.speak('Repeat is not supported by the youtube skill');
}else if (intent.name === "AMAZON.StartOverIntent") {
this.numberedTrack(1)
}else if (intent.name === "AMAZON.HelpIntent") {
this.help()
} else if (intent.name === "AMAZON.ResumeIntent") {
console.log('Resume called')
var resumefunction = this;
this.loadSettings(function(err, result) {
if (err) {
resumefunction.speak('There was an error loading settings from dropbox')
} else {
var lastPlayed = settings.lastplayed
var offsetInMilliseconds = 0;
var token = resumefunction.createToken;
var results = resumefunction.results;
var currentresult = settings.currentresult
var previousresult = settings.previousresult
var currenturl = settings.currentURL;
if (lastPlayed !== null) {
console.log(lastPlayed);
offsetInMilliseconds = lastPlayed.request.offsetInMilliseconds;
token = settings.currenttoken;
}
if (offsetInMilliseconds < 0){
offsetInMilliseconds = 0
}
if (settings.enqueue == true){
console.log('RESUME INTENT Track already enqueued')
settings.enqueue = false
var tracksettings = settings.tracksettings[currentresult]
var currentpart = tracksettings.currentpart
var totalparts = tracksettings.parts
console.log('RESUME INTENT CurrentResult is', currentresult)
console.log('RESUME INTENT Currentpart is', currentpart)
console.log('RESUME INTENT Offset is', offsetInMilliseconds)
if (currentresult !== previousresult){
//
console.log('RESUME INTENT Next track already cued')
settings.currentresult = previousresult
currentpart = settings.tracksettings[previousresult].currentpart
resumefunction.processResult(currentpart, null, offsetInMilliseconds)
} else {
// assume we are on the same track so play the previous part
console.log('RESUME INTENT Next part already cued')
tracksettings.currentpart--;
if (tracksettings.currentpart < 0){
tracksettings.currentpart = 0
}
console.log('RESUME INTENT Queueing part ', tracksettings.currentpart)
settings.tracksettings[currentresult].currentpart = tracksettings.currentpart;
resumefunction.processResult(tracksettings.currentpart, null,offsetInMilliseconds)
}
} else {
console.log('current URL is ' + currenturl)
resumefunction.resume(currenturl, offsetInMilliseconds, token);
}
}
});
}
}
else if (requestType === "AudioPlayer.PlaybackStopped") {
console.log('Playback stopped')
var playbackstoppedfunction = this;
this.loadSettings(function(err, result) {
if (err) {
playbackstoppedfunction.speak('There was an error loading settings from dropbox')
} else {
settings.lastplayed = playbackstoppedfunction.event
playbackstoppedfunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
}
});
}
});
}
else if (requestType === "AudioPlayer.PlaybackPause") {
console.log('Playback paused')
}
else if (requestType === "AudioPlayer.AudioPlayer.PlaybackFailed") {
console.log('Playback failed')
console.log(this.event.request.error.message)
}
else if (requestType === "AudioPlayer.PlaybackStarted") {
console.log('Playback started')
var playbackstartedfunction = this;
console.log(playbackstartedfunction.event)
this.loadSettings(function(err, result) {
if (err) {
playbackstartedfunction.speak('There was an error loading settings from dropbox')
} else {
settings.lastplayed = playbackstartedfunction.event
settings.enqueue = false;
settings.currentlyplaying = playbackstartedfunction.event
var results = settings.results
var currentresult = settings.currentresult
settings.currenttitle = results[currentresult].title
playbackstartedfunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
}
});
}
});
}
else if (requestType === "AudioPlayer.PlaybackNearlyFinished") {
console.log('Playback nearly finished')
var finishedfunction = this;
var token = this.event.request.token;
console.log('Token from request is', token)
// PlaybackNearlyFinished Directive are prone to be delivered multiple times during the same audio being played.
//If an audio file is already enqueued, exit without enqueuing again.
this.loadSettings(function(err, result) {
if (err) {
finishedfunction.speak('There was an error loading settings to dropbox')
} else {
if (settings.enqueue == true){
console.log("NEARLY FINISHED Track already enqueued")
} else {
console.log("NEARLY FINISHED Nothing already enqueued")
var results = settings.results
var current = settings.currentresult
settings.currenttoken = token
var tracksettings = settings.tracksettings[current]
var currentpart = tracksettings.currentpart
var totalparts = tracksettings.parts
console.log('NEARLY FINISHED Currentpart is', currentpart)
console.log('NEARLY FINISHED Total parts ', totalparts)
if (currentpart <= (totalparts -2)){
currentpart++
settings.tracksettings[current].currentpart = currentpart
console.log('NEARLY FINISHED Queueing part ', currentpart)
settings.enqueue = true
finishedfunction.processResult(currentpart, 'enqueue', 0);
} else {
console.log('NEARLY FINISHED No parts left - queueing next track')
settings.previousresult = current
if (settings.shuffle == 'on'){
settings.currentresult = Math.floor((Math.random() * (results.length-1) ));
settings.tracksettings[settings.currentresult].currentpart = 0
settings.enqueue = true
finishedfunction.processResult(0, 'enqueue', 0);
}
else if (current >= results.length-1){
if (settings.loop == 'on'){
settings.currentresult = 0
settings.tracksettings[settings.currentresult].currentpart = 0
settings.enqueue = true
finishedfunction.processResult(0, 'enqueue', 0);
} else {
console.log('end of results reached')
}
} else if(settings.autoplay == 'off'){
console.log('Autoplay is off')
}
else {
current++;
settings.currentresult = current;
settings.enqueue = true
finishedfunction.processResult(0, 'enqueue', 0);
}
}
}
}
});
}
};
alextube.prototype.play = function (audioURL, offsetInMilliseconds, tokenValue) {
var results = settings.results
var currentresult = settings.currentresult
var title = results[currentresult].title
var playlistText = this.createPlaylist(currentresult);
var responseText = 'Playing Track ' + (currentresult + 1)+ '. ' + title;
var response = {
version: "1.0",
response: {
shouldEndSession: true,
"outputSpeech": {
"type": "PlainText",
"text": responseText,
},
"card": {
"type": "Standard",
"title": "📺 Playing - " + title + ' 📺',
"text": playlistText
},
directives: [
{
type: "AudioPlayer.Play",
playBehavior: "REPLACE_ALL",
audioItem: {
stream: {
url: audioURL,
token: tokenValue,
expectedPreviousToken: null,
offsetInMilliseconds: offsetInMilliseconds
}
}
}
]
}
};
console.log('Play Response is')
console.log(JSON.stringify(response))
this.context.succeed(response);
};
alextube.prototype.resume = function (audioURL, offsetInMilliseconds, tokenValue) {
var resumeResponse = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Play",
playBehavior: "REPLACE_ALL",
audioItem: {
stream: {
url: audioURL,
streamFormat: "AUDIO_MP4",
expectedPreviousToken: null,
offsetInMilliseconds: offsetInMilliseconds,
//offsetInMilliseconds: 0,
token: tokenValue
}
}
}
]
}
};
console.log('Resume Response is')
console.log(JSON.stringify(resumeResponse))
this.context.succeed(resumeResponse);
};
alextube.prototype.enqueue = function (audioURL, offsetInMilliseconds, tokenValue, previousToken) {
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Play",
playBehavior: "ENQUEUE",
audioItem: {
stream: {
url: audioURL,
streamFormat: "AUDIO_MP4",
token: tokenValue,
expectedPreviousToken: previousToken,
offsetInMilliseconds: offsetInMilliseconds
}
}
}
]
}
};
console.log('Enqueue Response is')
console.log(JSON.stringify(response))
this.context.succeed(response);
};
alextube.prototype.stop = function () {
console.log("Sending stop response")
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Stop"
}
]
}
};
this.context.succeed(response);
};
alextube.prototype.next = function () {
console.log("Next function")
var nextfunction = this;
var playingtoken = this.event.request.token;
this.loadSettings(function(err, result) {
if (err) {
nextfunction.speak('There was an error loading settings from dropbox')
} else {
var enqueuestatus = settings.enqueue
var currenttoken = settings.currenttoken
var url = settings.currentURL
var results = settings.results
var current = settings.currentresult
var previous = settings.previousresult
if (enqueuestatus == true && current !== previous){
console.log('Song already enqueued')
nextfunction.play(url, 0, currenttoken)
}
else if (settings.shuffle == 'on'){
settings.currentresult = Math.floor((Math.random() * (results.length-1) ));
nextfunction.processResult(0, null, 0);
} else{
console.log('Enqueuing song')
if (current >= results.length-1){
if (settings.loop == 'on'){
settings.currentresult = 0
nextfunction.processResult(0, null, 0);
} else {
nextfunction.speak('End of playlist reached')
}
} else {
current++;
settings.currentresult = current;
nextfunction.processResult(0, null, 0);
}
}
}
});
};
alextube.prototype.nextResult = function () {
console.log("Next Result function")
var nextfunction = this;
var results = settings.results
var current = settings.currentresult
if (current >= results.length-1){
nextfunction.speak('End of playlist reached')
} else {
current++;
settings.currentresult = current;
nextfunction.processResult(0, null, 0);
}
};
alextube.prototype.previous = function () {
console.log("Previous function")
var previousfunction = this;
var playingtoken = this.event.request.token;
this.loadSettings(function(err, result) {
if (err) {
previousfunction.speak('There was an error loading settings from dropbox')
} else {
var enqueuestatus = settings.enqueue
var currenttoken = settings.currenttoken
var url = settings.currentURL
var results = settings.results
var current = settings.currentresult
if (enqueuestatus == true){
console.log('Song already enqueued')
current = current - 2
if (current < 0){
previousfunction.speak('Already at beginning of playlist')
} else {
settings.currentresult = current;
previousfunction.processResult(0, null, 0);
}
} else {
console.log('Enqueuing song')
current = current -1
if (current < 0){
previousfunction.speak('Already at beginning of playlist')
} else {
settings.currentresult = current;
previousfunction.processResult(0, null, 0);
}
}
}
});
};
alextube.prototype.processResult = function (partnumber, enqueue, offset) {
console.log("Processing result")
if(enqueue){
settings.enqueue = true
}
if(!offset){
offset=0
}
var results = settings.results
var currentresult = settings.currentresult
var url = results[currentresult].id;
var foundTitle = results[currentresult].title;
var playFunction = this;
var audioStreamInfo = ytdl.getInfo(url, { filter: function(format) { return format.container === 'm4a'; } }, function (err,info){
console.log(info)
var contentduration = info.length_seconds
settings.tracksettings[currentresult].duration = contentduration
console.log ('Duration is ', contentduration)
// ignore contetn lobger than 7 hours as the Lambda function will run out of space!!!
if (contentduration > 60*60*7){
console.log('Audio longer than 7 hours - for track', currentresult)
settings.playlist[currentresult] = settings.playlist[currentresult] + 'TRACK TOO LONG TO PLAY!'
playFunction.nextResult();
} else if (contentduration = 0){
console.log('Audio not found', currentresult)
settings.playlist[currentresult] = settings.playlist[currentresult] + 'TRACK NOT PLAYABLE!'
playFunction.nextResult();
} else {
var parts = Math.ceil(contentduration / partsize)
settings.tracksettings[currentresult].parts = parts
console.log ('Number of parts is ', parts)
if (!partnumber ){
partnumber = 0
}
else if (partnumber > (parts-1) || partnumber < 0){
console.log('Part number invalid')
partnumber = 0
}
console.log('Part to be processed is ', partnumber)
settings.tracksettings[currentresult].currentpart = partnumber
var starttime = partsize * partnumber
console.log ('start secs ', starttime)
ytdl(url, { filter: format => {
return format.container === 'm4a'; } })
// Write audio to file since ffmpeg supports only one input stream.
.pipe(fs.createWriteStream(audioOutput))
.on('finish', () => {
var test = ffmpeg()
// .input(ytdl(url, { filter: format => {
// return format.container === 'm4a'; } }))
//.videoCodec('copy')
.input(audioOutput)
.inputFormat('m4a')
.seekInput(starttime)
.duration(partsize)
.audioCodec('copy')
.outputOptions('-movflags faststart')
.save(mainOutput)
.on('error', console.error)
.on('end', () => {
fs.unlink(audioOutput, err => {
if(err) console.error(err);
var stats = fs.statSync(mainOutput)
var fileSizeInBytes = stats.size
var overalldata = settings.dataused + fileSizeInBytes
console.log('Max data usage setting in GB ', settings.maxdata/1000000.0)
console.log('Current data usage in GB ', settings.dataused/1000000.0)
console.log('Data usage following this song in GB ', overalldata/1000000.0)
if (overalldata >= settings.maxdata){
playFunction.speakWithCard('Maximum monthly data usage reached', 'WARNING', 'Maximum monthly data usage reached')
} else {
settings.dataused = overalldata;
playFunction.upload(enqueue, offset);
}
});
});
// test.pipe(dropboxUploadStream);
});
}
})
};
alextube.prototype.speak = function (responseText, ask) {
//console.log('speaking result')
var session = true
if (ask){
session = false
}
var response = {
version: "1.0",
"sessionAttributes": {},
response: {
"outputSpeech": {
"type": "PlainText",
"text": responseText,
},
"shouldEndSession": session
}
};
this.context.succeed(response);
};
alextube.prototype.speakWithCard = function (responseText, cardTitle, cardText) {
//console.log('speaking result')
var response = {
version: "1.0",
"sessionAttributes": {},
response: {
"outputSpeech": {
"type": "PlainText",
"text": responseText,
},
"card": {
"type": "Standard",
"title": cardTitle,
"text": cardText
},
"shouldEndSession": true
}
};
this.context.succeed(response);
};
alextube.prototype.autoMode = function (mode) {
console.log('changing auto play mode')
var autofunction = this;
this.loadSettings(function(err, result) {
if (err) {
autofunction.speak('There was an error loading settings from dropbox')
} else {
settings.autoplay = mode
settings.enqueue = false
autofunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
autofunction.speak('Autoplay mode is ' + mode)
}
});
}
});
};
alextube.prototype.shuffle = function (mode) {
var shufflefunction = this;
this.loadSettings(function(err, result) {
if (err) {
shufflefunction.speak('There was an error loading settings from dropbox')
} else {
settings.shuffle = mode
settings.enqueue = false
shufflefunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
shufflefunction.speak('Shuffle mode is ' + mode)
}
});
}
});
};
alextube.prototype.loop = function (mode) {
console.log('changing shuffle mode')
var loopfunction = this;
this.loadSettings(function(err, result) {
if (err) {
loopfunction.speak('There was an error loading settings from dropbox')
} else {
settings.loop = mode
settings.enqueue = false
loopfunction.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
loopfunction.speak('Loop mode is ' + mode)
}
});
}
});
};
alextube.prototype.resetmax = function () {
console.log('Resetting data limit')
var resetfunction = this;
this.loadSettings(function(err, result) {
if (err) {
resetfunction.speak('There was an error loading settings from dropbox')
} else {
settings.maxdata = maxdata