-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
1314 lines (1165 loc) · 46.8 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');
const util = require('util');
var fs = require('fs');
var request = require("request");
var dropbox_token = process.env['DROPBOX_TOKEN'];
var media_bucket = process.env['MEDIA_BUCKET'];
// var ffmpeg = require('fluent-ffmpeg');
const dropbox = dropboxV2Api.authenticate({
token: dropbox_token
});
const videoOutput = '/tmp/file.mp4'
const mainOutput = '/tmp/output.mp4'
const dbfile = 'file.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
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
var maxresults = 10;
var partsize = 60*5; // size of the video chunks in seconds
var settings = new Object();
var streamURL;
exports.handler = function(event, context) {
var player = new alexaplayer(event, context);
player.handle();
};
var alexaplayer = function (event, context) {
this.event = event;
this.context = context;
};
alexaplayer.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('Event:');
console.log(JSON.stringify(this.event));
if (this.supportsDisplay()) console.log('Supports display');
else console.log('Does not support display');
if (requestType === "LaunchRequest") {
if (this.supportsDisplay()) {
var content = {
"hasDisplaySpeechOutput" : 'Welcome to Dropbox Player. What do you want to play?',
"hasDisplayRepromptText" : 'Just say what do you want to play or, if you do not know, say play demo',
"simpleCardTitle" : 'Dropbox Player',
"simpleCardContent" : 'Listen or watch your favourite videos with less click, click, click and more wow',
"bodyTemplateTitle" : 'Welcome to Dropbox Player. What do you want to play?',
"bodyTemplateContent" : 'Just say what do you want to play or, if you do not know, say demo',
"templateToken" : "dropboxPlayerListTemplate",
"askOrTell" : ":ask",
"sessionAttributes": {}
};
renderTemplate.call(this, content);
} else {
this.speak('Welcome to Dropbox Player. What do you want to listen?', 'Welcome to Dropbox Player', 'Listen or watch your favourite videos with less click, click, click and more wow')
}
} else if (requestType === "IntentRequest") {
var intent = this.event.request.intent;
if (!process.env['DROPBOX_TOKEN']){
this.speak('DROPBOX TOKEN Environment Variable not set!');
}
if (intent.name === "SearchIntent" || intent.name === "ShowIntent") {
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")
}
if (alexaUtteranceText) {
dropbox({
resource: 'files/search',
parameters: {
"path": "/Alexa",
"query": alexaUtteranceText,
"start": 0,
"max_results": 15,
"mode": "filename"
}
}, (err, results) => {
if (err) {
return console.log(err);
}
console.log(JSON.stringify(results));
console.log('number of results is', results.matches.length);
if (results.start === 0) searchFunction.speak('I could not find any file with the name ' + alexaUtteranceText + ', lets try again, what do you want to play?', true);
settings.results = results.matches;
settings.currentresult = 0;
settings.previousURL = null;
settings.previousresult = 0;
var tracksettings = [];
var playlist = [];
for (var count = 0; count <= results.matches.length - 1; count++) {
playlist[count] = 'Track ' + (count + 1) + ': ' + results.matches[count].metadata.name
var object = {
"id": count,
"title": results.matches[count].metadata.name,
"path": results.matches[count].metadata.path_display,
"duration": null,
"parts": null,
"size": results.matches[count].metadata.size,
"currentpart": 0,
"isVideo": this.validVideoFormat(results.matches[count].metadata.path_display)
}
tracksettings.push(object)
}
settings.tracksettings = tracksettings;
settings.playlist = playlist;
if (intent.name === "ShowIntent") {
if (this.supportsDisplay()) {
var content = {
"hasDisplaySpeechOutput" : 'Here you have some videos of ' + alexaUtteranceText,
"hasDisplayRepromptText" : 'Just say which video do you want to play or, if you do not know, say "play track 1"',
"simpleCardTitle" : alexaUtteranceText + ' videos',
"simpleCardContent" : 'Listen or watch videos with less click, click, click and more wow',
"bodyTemplateTitle" : '"' + alexaUtteranceText + '" video results. What do you want to play?',
"bodyTemplateContent" : 'Just say what do you want to play or, if you do not know, say play track 1',
"templateToken" : "dropboxPlayerListTemplate",
"askOrTell" : ":ask",
"sessionAttributes": {}
};
renderTemplate.call(this, content, settings);
} else {
this.speak('Here you have some videos of ' + alexaUtteranceText + '. What do you want to play?', 'Welcome to Dropbox Player', 'Listen or watch your favourite videos with less click, click, click and more wow')
}
} else {
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 {
searchFunction.processResult(0, null, 0);
}
});
}
});
}
});
} else {
searchFunction.speak('I could not find any file with the name ' + alexaUtteranceText + ', What do you want to do?', 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 (intent.name === "DemoIntent") {
console.log('Demo intent');
if (this.supportsDisplay()) {
dropbox({
resource: 'files/get_temporary_link',
parameters: {
'path': '/Alexa/demo video dropbox player.mp4'
}
}, (err, result) => {
if (err) {
console.log('There was an error')
console.log(err)
this.speak('There was an error playing the demo video');
} else if (result) {
console.log('Here is the temp link')
console.log(result.link)
var streamURL = result.link
this.playVideo(streamURL, 0, this.createToken(), "Demo sample video", "Just a streaming video demo");
}
});
} else {
this.playAudio("https://audio1.maxi80.com/",0,this.createToken(),"Demo sample audio","Just a demo streaming audio from maxi80 radio")
}
}
} 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);
}
}
}
}
});
} else if (requestType === "Display.ElementSelected") {
console.log('Element Selected:');
console.log(this.event.request.token);
var id = this.event.request.token.split('_')[1];
console.log(settings.tracksettings[id]);
var that = this;
var getTempURL = function(cb) {
dropbox({
resource: 'files/get_temporary_link',
parameters: {
'path': settings.tracksettings[id].path
}
}, (err, result) => {
if (err) {
console.log('There was an error')
console.log(err)
this.speak('There was an error playing the demo video');
} else if (result) {
console.log('Here is the temp link')
console.log(result.link)
var streamURL = result.link
cb(streamURL);
}
});
};
if (this.supportsDisplay()) {
getTempURL( function(streamURL) {
that.playVideo(streamURL, 0, that.createToken(), settings.tracksettings[id].title, settings.tracksettings[id].size);
});
} else {
getTempURL( function(streamURL) {
that.playAudio(streamURL, 0, that.createToken(), settings.tracksettings[id].title, "Just streaming audio")
});
}
} else {
console.log('unknown request...');
console.log(this.event.request);
}
};
alexaplayer.prototype.playAudio = function (mediaURL, offsetInMilliseconds, tokenValue, title, playlistText) {
try {
var a = title.slice(0, -4);
title = a;
} catch (e) {}
var responseText = 'Playing ' + 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: mediaURL,
token: tokenValue,
expectedPreviousToken: null,
offsetInMilliseconds: offsetInMilliseconds
}
}
}
]
}
};
console.log('Play Response is')
console.log(JSON.stringify(response))
this.context.succeed(response);
}
alexaplayer.prototype.playVideo = function (mediaURL, offsetInMilliseconds, tokenValue, title, playlistText) {
try {
var a = title.slice(0, -4);
title = a;
} catch (e) {}
console.log('Play');
var response = {
version: "1.0",
response: {
outputSpeech: {
type: "PlainText",
text: "Playing " + title,
},
card: null,
directives: [
{
type: "VideoApp.Launch",
videoItem:
{
source: mediaURL,
metadata: {
title: title,
subtitle: playlistText
}
}
}
],
reprompt: null
}
};
console.log('Play Response is')
console.log(JSON.stringify(response))
this.context.succeed(response);
};
alexaplayer.prototype.stop = function () {
console.log("Sending stop response");
var stopfunction = this;
settings.lastplayed = this.event;
this.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
} else {
if (!stopfunction.supportsDisplay()) {
var response = {
version: "1.0",
response: {
shouldEndSession: true,
directives: [
{
type: "AudioPlayer.Stop"
}
]
}
};
this.context.succeed(response);
}
}
});
};
alexaplayer.prototype.next = function () {
console.log("Next function, TBC")
var filesettings = [];
var numfunction = this;
dropbox({
resource: 'files/list_folder',
parameters: {
"path": "/Alexa",
"recursive": false,
"include_media_info": false,
"include_deleted": false,
"include_has_explicit_shared_members": false,
"include_mounted_folders": true
}
}, (err, results) => {
if (err) {
console.log(err);
numfunction.speak('Something went wrong reading from Dropbox. The Alexa folder might not be present in the linked Dropbox account');
} else {
console.log(results);
console.log('lenght: ' + results.entries.length);
var playlist=[];
// Save filenames list
for (var count = 0; count <= results.entries.length-1; count++) {
playlist[count] = 'Track ' + (count +1) +': ' + results.entries[count].name
var object = {
"id": count,
"title": results.entries[count].name,
"path": results.entries[count].path_display,
"duration": null,
"parts": null,
"size": results.entries[count].size,
"isVideo": this.validVideoFormat(results.entries[count].path_display)
}
filesettings.push(object)
}
if (number > results.entries.length || number < 1 ){
numfunction.speak('That is not a valid selection')
} else {
var i = 0;
do {
if (filesettings[i].isVideo) {
console.log('Playing ' + filesettings[i].title);
dropbox({
resource: 'files/get_temporary_link',
parameters: {
'path': filesettings[i].path
}
}, (err, result) => {
if (err) {
console.log('There was an error')
console.log(err)
} else if (result) {
console.log('Here is the temp link')
console.log(result.link)
var streamURL = result.link
numfunction.playVideo(streamURL, 0, this.createToken, filesettings[i].name, filesettings[i].size)
}
});
} else {
console.log('File is not a recognized video format, use: m4v,avi or mp4. Playing next');
}
i++;
} while (!filesettings[i].isVideo && i < results.entries.length);
this.speak('Video file not found in the Alexa Dropbox folder');
}
}
});
};
alexaplayer.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);
};
alexaplayer.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);
};
alexaplayer.prototype.speakWithCard = function (responseText, cardTitle, cardText) {
console.log('speaking with card 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);
};
alexaplayer.prototype.numberedTrack = function (number) {
console.log('Numbered track function')
var numfunction = this;
this.loadSettings(function(err, result) {
if (err) {
console.log('There was an error loading settings from dropbox. Starting track 1 in dropbox')
var filesettings = [];
dropbox({
resource: 'files/list_folder',
parameters: {
"path": "/Alexa",
"recursive": false,
"include_media_info": false,
"include_deleted": false,
"include_has_explicit_shared_members": false,
"include_mounted_folders": true
}
}, (err, results) => {
if (err) {
console.log(err);
numfunction.speak('Soemething went wrong reading from Dropbox. The Alexa folder might not be present in the linked Dropbox account');
} else {
console.log(results);
console.log('lenght: ' + results.entries.length);
// Save filenames list
for (var count = 0; count <= results.entries.length-1; count++) {
playlist[count] = 'Track ' + (count +1) +': ' + results[count].name
var object = {
"id": count,
"title": results.entries[count].name,
"path": results.entries[count].path_display,
"duration": null,
"parts": null,
"size": results.entries[count].size,
"isVideo": this.validVideoFormat(results.entries[count].path_display)
}
filesettings.push(object)
}
if (number > results.entries.length || number < 1 ){
numfunction.speak('That is not a valid selection')
} else {
var i = number;
do {
if (filesettings[i].isVideo) {
console.log('Playing ' + filesettings[i].title);
dropbox({
resource: 'files/get_temporary_link',
parameters: {
'path': filesettings[i].path
}
}, (err, result) => {
if (err) {
console.log('There was an error')
console.log(err)
} else if (result) {
console.log('Here is the temp link')
console.log(result.link)
var streamURL = result.link
numfunction.playVideo(streamURL, 0, this.createToken, filesettings[i].name, filesettings[i].size)
}
});
} else {
console.log('File is not a recognized video format, use: m4v,avi or mp4. Playing next');
}
i++;
} while (!filesettings[i].isVideo && i < results.entries.length)
this.speak('Video file not found in the Alexa Dropbox folder');
}
}
});
} else {
var enqueuestatus = settings.enqueue
var currenttoken = settings.currenttoken
var url = settings.currentURL
var results = settings.playlist
var current = settings.currentresult
console.log(JSON.stringify(settings));
if (number > results.length || number < 1 ){
numfunction.speak('That is not a valid selection')
} else {
settings.currentresult = number-1;
settings.tracksettings[settings.currentresult].currentpart = 0
numfunction.processResult(0, null, 0);
}
}
});
};
alexaplayer.prototype.saveSettings = function (callback) {
// add the writing of this file to the data used (we have to estimate the filesize as being 24KB)
var wstream = fs.createWriteStream('/tmp/settings.js');
wstream.write(JSON.stringify(settings));
wstream.end();
wstream.on('finish', function () {
//console.log('seetings file has been written');
const dropboxUploadlastplayed = dropbox({
resource: 'files/upload',
parameters: {
path: '/AlexaSettings/settings.js',
mode: 'overwrite',
mute: true
}
}, (err, result) => {
if (err){
console.log('There was an error')
callback(err, null);
} else if (result){
callback(null, result);
}
});
fs.createReadStream('/tmp/settings.js').pipe(dropboxUploadlastplayed);
});
};
alexaplayer.prototype.loadSettings = function (callback) {
const savefile = fs.createWriteStream('/tmp/settings.js')
dropbox({
resource: 'files/download',
parameters: {
path: '/AlexaSettings/settings.js'
}
}, (err, result) => {
if (err){
console.log('There was an error downloading file from dropbox')
callback(err, null);
} else if (result){
//savefile.end();
}
}).pipe(savefile);
savefile.on('finish', function () {
fs.readFile('/tmp/settings.js', 'utf8', onFileRead);
function onFileRead(err, data) {
if (err) {
console.log('There was an error reading settings file from /tmp')
callback(err, null);
} else {
settings = JSON.parse(data);
callback(null, {});
}
}
})
};
alexaplayer.prototype.help = function(currentresult) {
console.log('Help intent');
var cardtext = '1. Request a particular video: "Alexa, play the latest video from Chicago"\n' +
'2. Request an auto generated playlist of 25 results: - "Alexa play the latest Seattle match"\n' +
'3. Request a particular track from the playlist: "Alexa, play Track 10"\n' +
'4. Skip to the next/previous track:- "Alexa, next/previous"\n' +
'5. Pause:- "Alexa pause" or "Alexa stop"\n' +
'6. Resume playback:- "Alexa resume" ';
var cardTitle = 'Dropbox Player Skill Commands';
if (this.supportsDisplay()) {
this.speakWithCard('Please see the Alexa app for a list of commands that can be used with this skill', cardTitle, cardtext)
} else {
this.speak(cardtext);
}
}
alexaplayer.prototype.processResult = function (partnumber, enqueue, offset) {
console.log("Processing result");
if (enqueue) {
settings.enqueue = true
}
if (!offset) {
offset = 0
}
var results = settings.results || settings.playlist;
var currentresult = settings.currentresult || 0;
console.log(results);
console.log(settings);
console.log(settings.tracksettings[currentresult].path);
var url = settings.tracksettings[currentresult].path;
var foundTitle = settings.tracksettings[currentresult].title;
var processfuntion = this;
dropbox({
resource: 'files/get_temporary_link',
parameters: {
'path': url
}
}, (err, result) => {
if (err){
console.log('There was an error')
console.log(err)
} else if (result){
console.log('Here is the temp link')
console.log(result.link)
var streamURL = result.link
if (!enqueue){
console.log('normal play')
var token = processfuntion.createToken();
settings.currenttoken = token
settings.enqueue = false
settings.currentURL = streamURL;
processfuntion.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
processfuntion.speak('There was an error saving settings to dropbox')
} else {
if (processfuntion.supportsDisplay()) processfuntion.playVideo(streamURL, offset, token, foundTitle, "");
}
});
} else {
console.log('enque play')
var previoustoken = settings.currenttoken
var token = processfuntion.createToken();
settings.currenttoken = token
settings.enqueue = true
settings.previousURL = settings.currentURL
settings.currentURL = streamURL;
processfuntion.saveSettings(function(err, result) {
if (err) {
console.log('There was an error saving settings to dropbox', err)
processfuntion.speak('There was an error saving settings to dropbox')
} else {
processfuntion.enqueue(streamURL, 0, token, previoustoken);
}
});
}
}
});
}
// HELPER FUNCTIONS
alexaplayer.prototype.putObjectToS3 = function(bucket, key, data){
var s3 = new AWS.S3();
var params = {
Bucket : bucket,
Key : key,
Body : data
}
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
alexaplayer.prototype.createToken = function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
alexaplayer.prototype.supportsDisplay = function() {
var hasDisplay = this.event.context && this.event.context.System && this.event.context.System.device &&
this.event.context.System.device.supportedInterfaces && this.event.context.System.device.supportedInterfaces.Display;