forked from alexa-js/alexa-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
737 lines (679 loc) · 24 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
"use strict";
var Promise = require("bluebird");
var AlexaUtterances = require("alexa-utterances");
var SSML = require("./lib/to-ssml");
var alexa = {};
var defaults = require("lodash.defaults");
var verifier = require("alexa-verifier-middleware");
var bodyParser = require('body-parser');
var normalizeApiPath = require('./lib/normalize-api-path');
alexa.response = function(session) {
var self = this;
this.resolved = false;
this.response = {
"version": "1.0",
"response": {
"directives": [],
"shouldEndSession": true
}
};
this.say = function(str) {
if (typeof this.response.response.outputSpeech == "undefined") {
this.response.response.outputSpeech = {
"type": "SSML",
"ssml": SSML.fromStr(str)
};
} else {
// append str to the current outputSpeech, stripping the out speak tag
this.response.response.outputSpeech.ssml = SSML.fromStr(str, this.response.response.outputSpeech.ssml);
}
return this;
};
this.clear = function( /*str*/ ) {
this.response.response.outputSpeech = {
"type": "SSML",
"ssml": SSML.fromStr("")
};
return this;
};
this.reprompt = function(str) {
if (typeof this.response.response.reprompt == "undefined") {
this.response.response.reprompt = {
"outputSpeech": {
"type": "SSML",
"ssml": SSML.fromStr(str)
}
};
} else {
// append str to the current outputSpeech, stripping the out speak tag
this.response.response.reprompt.outputSpeech.ssml = SSML.fromStr(str, this.response.response.reprompt.outputSpeech.text);
}
return this;
};
this.card = function(oCard) {
if (2 == arguments.length) { // backwards compat
oCard = {
type: "Simple",
title: arguments[0],
content: arguments[1]
};
}
var requiredAttrs = [],
clenseAttrs = [];
switch (oCard.type) {
case 'Simple':
requiredAttrs.push('content');
clenseAttrs.push('content');
break;
case 'Standard':
requiredAttrs.push('text');
clenseAttrs.push('text');
if (('image' in oCard) && (!('smallImageUrl' in oCard['image']) && !('largeImageUrl' in oCard['image']))) {
console.error('If card.image is defined, must specify at least smallImageUrl or largeImageUrl');
return this;
}
break;
case 'AskForPermissionsConsent':
requiredAttrs.push('permissions');
break;
default:
break;
}
var hasAllReq = requiredAttrs.every(function(idx) {
if (!(idx in oCard)) {
console.error('Card object is missing required attr "' + idx + '"');
return false;
}
return true;
});
if (!hasAllReq) {
return this;
}
// remove all SSML to keep the card clean
clenseAttrs.forEach(function(idx) {
oCard[idx] = SSML.cleanse(oCard[idx]);
});
this.response.response.card = oCard;
return this;
};
this.linkAccount = function() {
this.response.response.card = {
"type": "LinkAccount"
};
return this;
};
this.shouldEndSession = function(bool, reprompt) {
this.response.response.shouldEndSession = bool;
if (reprompt) {
this.reprompt(reprompt);
}
return this;
};
this.sessionObject = session;
this.setSessionAttributes = function(attributes) {
this.response.sessionAttributes = attributes;
};
// prepare response object
this.prepare = function() {
this.setSessionAttributes(this.sessionObject.getAttributes());
};
this.audioPlayerPlay = function(playBehavior, audioItem) {
var audioPlayerDirective = {
"type": "AudioPlayer.Play",
"playBehavior": playBehavior,
"audioItem": audioItem
};
this.directive(audioPlayerDirective);
return this;
};
this.audioPlayerPlayStream = function(playBehavior, stream) {
var audioItem = {
"stream": stream
};
return this.audioPlayerPlay(playBehavior, audioItem);
};
this.audioPlayerStop = function() {
var audioPlayerDirective = {
"type": "AudioPlayer.Stop"
};
this.directive(audioPlayerDirective);
return this;
};
this.audioPlayerClearQueue = function(clearBehavior) {
var audioPlayerDirective = {
"type": "AudioPlayer.ClearQueue",
"clearBehavior": clearBehavior || "CLEAR_ALL"
};
this.directive(audioPlayerDirective);
return this;
};
// Read & manipulate response directives
var directives = new alexa.directives(self.response.response.directives);
this.getDirectives = function() {
return directives;
};
this.directive = function(directive) {
this.getDirectives().set(directive);
return this;
};
// legacy code below
// @deprecated
this.session = function(key, val) {
if (typeof val == "undefined") {
return this.sessionObject.get(key);
} else {
this.sessionObject.set(key, val);
}
return this;
};
// @deprecated
this.clearSession = function(key) {
this.sessionObject.clear(key);
return this;
};
};
alexa.directives = function(directives) {
// load the alexa response directives information into details
this.details = directives;
this.set = function(directive) {
this.details.push(directive);
};
this.clear = function() {
this.details.length = 0;
};
};
alexa.request = function(json) {
this.data = json;
this.slots = {};
if (this.data.request && this.data.request.intent && this.data.request.intent.slots && Object.keys(this.data.request.intent.slots).length > 0) {
var slot, slotName;
for (slotName in this.data.request.intent.slots) {
slot = new alexa.slot(this.data.request.intent.slots[slotName]);
this.slots[slotName] = slot;
}
}
this.slot = function(slotName, defaultValue) {
if (this.slots && 'undefined' != typeof this.slots[slotName]) {
return this.slots[slotName].value;
} else {
return defaultValue;
}
};
this.type = function() {
if (!(this.data && this.data.request && this.data.request.type)) {
console.error("missing request type:", this.data);
return;
}
return this.data.request.type;
};
this.isAudioPlayer = function() {
var requestType = this.type();
return (requestType && 0 === requestType.indexOf("AudioPlayer."));
};
this.isPlaybackController = function() {
var requestType = this.type();
return (requestType && 0 === requestType.indexOf("PlaybackController."));
};
if (this.data.request && this.data.request.intent) {
this.confirmationStatus = this.data.request.intent.confirmationStatus;
}
if (this.data.request && this.data.request.type === 'Display.ElementSelected' && this.data.request.token) {
this.selectedElementToken = this.data.request.token;
}
this.isConfirmed = function() {
return 'CONFIRMED' === this.confirmationStatus;
};
this.userId = null;
this.applicationId = null;
this.context = null;
if (this.data.context) {
this.userId = this.data.context.System.user.userId;
this.applicationId = this.data.context.System.application.applicationId;
this.context = this.data.context;
}
var session = new alexa.session(json.session);
this.hasSession = function() {
return session.isAvailable();
};
this.getSession = function() {
return session;
};
this.getDialog = function() {
var dialogState = (typeof this.data.request['dialogState'] !== "undefined") ?
this.data.request['dialogState'] : null;
return new alexa.dialog(dialogState);
};
// legacy code below
// @deprecated
this.sessionDetails = this.getSession().details;
// @deprecated
this.sessionId = this.getSession().sessionId;
// @deprecated
this.sessionAttributes = this.getSession().attributes;
// @deprecated
this.isSessionNew = this.hasSession() ? this.getSession().isNew() : false;
// @deprecated
this.session = function(key) {
return this.getSession().get(key);
};
};
alexa.dialog = function(dialogState) {
this.dialogState = dialogState;
this.isStarted = function() {
return 'STARTED' === this.dialogState;
};
this.isInProgress = function() {
return 'IN_PROGRESS' === this.dialogState;
};
this.isCompleted = function() {
return 'COMPLETED' === this.dialogState;
};
this.handleDialogDelegation = function(request, response) {
var dialogDirective = {
"type": "Dialog.Delegate"
};
response.shouldEndSession(false).directive(dialogDirective).send();
};
};
alexa.intent = function(name, schema, handler) {
this.name = name;
this.handler = handler;
this.dialog = (schema && typeof schema.dialog !== "undefined") ? schema.dialog : {};
this.slots = (schema && typeof schema["slots"] !== "undefined") ? schema["slots"] : null;
this.utterances = (schema && typeof schema["utterances"] !== "undefined") ? schema["utterances"] : null;
this.isDelegatedDialog = function() {
return this.dialog.type === "delegate";
};
};
alexa.slot = function(slot) {
this.name = slot.name;
this.value = slot.value;
this.confirmationStatus = slot.confirmationStatus;
this.isConfirmed = function() {
return 'CONFIRMED' === this.confirmationStatus;
};
};
alexa.session = function(session) {
var isAvailable = (typeof session != "undefined");
this.isAvailable = function() {
return isAvailable;
};
if (isAvailable) {
this.isNew = function() {
return (true === session.new);
};
this.get = function(key) {
// getAttributes deep clones the attributes object, so updates to objects
// will not affect the session until `set` is called explicitly
return this.getAttributes()[key];
};
this.set = function(key, value) {
this.attributes[key] = value;
};
this.clear = function(key) {
if (typeof key == "string") {
if (typeof this.attributes[key] != "undefined") {
delete this.attributes[key];
}
} else {
this.attributes = {};
}
};
// load the alexa session information into details
this.details = session;
// @deprecated
this.details.userId = this.details.user.userId || null;
// @deprecated
this.details.accessToken = this.details.user.accessToken || null;
// persist all the session attributes across requests
// the Alexa API doesn't think session variables should persist for the entire
// duration of the session, but I do
this.attributes = session.attributes || {};
this.sessionId = session.sessionId;
} else {
this.isNew = this.get = this.set = this.clear = function() {
throw "NO_SESSION";
};
this.details = {};
this.attributes = {};
this.sessionId = null;
}
this.getAttributes = function() {
// deep clone attributes so direct updates to objects are not set in the
// session unless `.set` is called explicitly
return JSON.parse(JSON.stringify(this.attributes));
};
};
alexa.apps = {};
alexa.app = function(name) {
if (!(this instanceof alexa.app)) {
throw new Error("Function must be called with the new keyword");
}
var self = this;
this.name = name;
this.messages = {
// when an intent was passed in that the application was not configured to handle
"NO_INTENT_FOUND": "Sorry, the application didn't know what to do with that intent",
// when an AudioPlayer event was passed in that the application was not configured to handle
"NO_AUDIO_PLAYER_EVENT_HANDLER_FOUND": "Sorry, the application didn't know what to do with that AudioPlayer event",
// when the app was used with 'open' or 'launch' but no launch handler was defined
"NO_LAUNCH_FUNCTION": "Try telling the application what to do instead of opening it",
// when a request type was not recognized
"INVALID_REQUEST_TYPE": "Error: not a valid request",
// when a request and response don't contain session object
// https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference#request-body-parameters
"NO_SESSION": "This request doesn't support session attributes",
// if some other exception happens
"GENERIC_ERROR": "Sorry, the application encountered an error",
// User interacted with the display but no element selected handler has been defined.
"NO_DISPLAY_ELEMENT_SELECTED_FUNCTION": "Try telling the application how to handle display events. Make sure displayElementSelected is implemented."
};
// persist session variables from every request into every response
this.persistentSession = true;
// use a minimal set of utterances or the full cartesian product
this.exhaustiveUtterances = false;
// a catch-all error handler do nothing by default
this.error = null;
// pre/post hooks to be run on every request
this.pre = function( /*request, response, type*/ ) {};
this.post = function( /*request, response, type*/ ) {};
// a mapping of keywords to arrays of possible values, for expansion of sample utterances
this.dictionary = {};
this.intents = {};
this.intent = function(intentName, schema, func) {
if (typeof schema === "function") {
func = schema;
schema = {};
}
self.intents[intentName] = new alexa.intent(intentName, schema, func);
};
this.audioPlayerEventHandlers = {};
this.audioPlayer = function(eventName, func) {
self.audioPlayerEventHandlers[eventName] = {
"name": eventName,
"function": func
};
};
this.playbackControllerEventHandlers = {};
this.playbackController = function(eventName, func) {
self.playbackControllerEventHandlers[eventName] = {
"name": eventName,
"function": func
};
};
this.launchFunc = null;
this.launch = function(func) {
self.launchFunc = func;
};
this.displayElementSelectedFunc = null;
this.displayElementSelected = function(func) {
self.displayElementSelectedFunc = func;
};
this.sessionEndedFunc = null;
this.sessionEnded = function(func) {
self.sessionEndedFunc = func;
};
this.request = function(request_json) {
var request = new alexa.request(request_json);
var response = new alexa.response(request.getSession());
var postExecuted = false;
var requestType = request.type();
var promiseChain = Promise.resolve();
// attach Promise resolve/reject functions to the response object
response.send = function(exception) {
response.prepare();
var postPromise = Promise.resolve();
if (typeof self.post == "function" && !postExecuted) {
postExecuted = true;
postPromise = Promise.resolve(self.post(request, response, requestType, exception));
}
return postPromise.then(function() {
if (!response.resolved) {
response.resolved = true;
}
return response.response;
});
};
response.fail = function(msg, exception) {
response.prepare();
var postPromise = Promise.resolve();
if (typeof self.post == "function" && !postExecuted) {
postExecuted = true;
postPromise = Promise.resolve(self.post(request, response, requestType, exception));
}
return postPromise.then(function() {
if (!response.resolved) {
response.resolved = true;
throw msg;
}
// propagate successful response if it's already been resolved
return response.response;
});
};
return promiseChain.then(function () {
// Call to `.pre` can also throw, so we wrap it in a promise here to
// propagate errors to the error handler
var prePromise = Promise.resolve();
if (typeof self.pre == "function") {
prePromise = Promise.resolve(self.pre(request, response, requestType));
}
return prePromise;
}).then(function () {
requestType = request.type();
if (!response.resolved) {
if ("IntentRequest" === requestType) {
var intent = request_json.request.intent.name;
if (typeof self.intents[intent] !== "undefined" && typeof self.intents[intent].handler === "function") {
if (self.intents[intent].isDelegatedDialog() && !request.getDialog().isCompleted()) {
return Promise.resolve(request.getDialog().handleDialogDelegation(request, response));
} else {
return Promise.resolve(self.intents[intent].handler(request, response));
}
} else {
throw "NO_INTENT_FOUND";
}
} else if ("LaunchRequest" === requestType) {
if (typeof self.launchFunc == "function") {
return Promise.resolve(self.launchFunc(request, response));
} else {
throw "NO_LAUNCH_FUNCTION";
}
} else if ("SessionEndedRequest" === requestType) {
if (typeof self.sessionEndedFunc == "function") {
return Promise.resolve(self.sessionEndedFunc(request, response));
}
} else if (request.isAudioPlayer()) {
var event = requestType.slice(12);
var eventHandlerObject = self.audioPlayerEventHandlers[event];
if (typeof eventHandlerObject != "undefined" && typeof eventHandlerObject["function"] == "function") {
return Promise.resolve(eventHandlerObject["function"](request, response));
}
} else if (request.isPlaybackController()) {
var playbackControllerEvent = requestType.slice(19);
var playbackEventHandlerObject = self.playbackControllerEventHandlers[playbackControllerEvent];
if (typeof playbackEventHandlerObject != "undefined" && typeof playbackEventHandlerObject["function"] == "function") {
return Promise.resolve(playbackEventHandlerObject["function"](request, response));
}
} else if ("Display.ElementSelected" === requestType) {
if (typeof self.displayElementSelectedFunc === "function") {
return Promise.resolve(self.displayElementSelectedFunc(request, response));
} else {
throw "NO_DISPLAY_ELEMENT_SELECTED_FUNCTION";
}
} else {
throw "INVALID_REQUEST_TYPE";
}
}
})
.then(function () {
return response.send();
})
.catch(function(e) {
if (typeof self.error == "function") {
// Default behavior of any error handler is to send a response
return Promise.resolve(self.error(e, request, response)).then(function() {
if (!response.resolved) {
response.resolved = true;
return response.send();
}
// propagate successful response if it's already been resolved
return response.response;
});
} else if (typeof e == "string" && self.messages[e]) {
if (!request.isAudioPlayer()) {
response.say(self.messages[e]);
return response.send(e);
} else {
return response.fail(self.messages[e]);
}
}
if (!response.resolved) {
if (e.message) {
return response.fail("Unhandled exception: " + e.message + ".", e);
} else if (typeof e == "string") {
return response.fail("Unhandled exception: " + e + ".", e);
} else {
return response.fail("Unhandled exception.", e);
}
}
throw e;
});
};
// extract the schema and generate a schema JSON object
this.schema = function() {
var schema = {
"intents": []
},
intentName, intent, key;
for (intentName in self.intents) {
intent = self.intents[intentName];
var intentSchema = {
"intent": intent.name
};
if (intent.slots && Object.keys(intent.slots).length > 0) {
intentSchema["slots"] = [];
for (key in intent.slots) {
intentSchema.slots.push({
"name": key,
"type": intent.slots[key]
});
}
}
schema.intents.push(intentSchema);
}
return JSON.stringify(schema, null, 3);
};
// generate a list of sample utterances
this.utterances = function() {
var intentName,
intent,
out = "";
for (intentName in self.intents) {
intent = self.intents[intentName];
if (intent.utterances) {
intent.utterances.forEach(function(sample) {
var list = AlexaUtterances(sample,
intent.slots,
self.dictionary,
self.exhaustiveUtterances);
list.forEach(function(utterance) {
out += intent.name + " " + (utterance.replace(/\s+/g, " ")).trim() + "\n";
});
});
}
}
return out;
};
// a built-in handler for AWS Lambda
this.handler = function(event, context, callback) {
self.request(event)
.then(function(response) {
callback(null, response);
})
.catch(function(response) {
callback(response);
});
};
// for backwards compatibility
this.lambda = function() {
return self.handler;
};
// attach Alexa endpoint to an express router
//
// @param object options.expressApp the express instance to attach to
// @param router options.router router instance to attach to the express app
// @param string options.endpoint the path to attach the router to (e.g., passing 'mine' attaches to '/mine')
// @param bool options.checkCert when true, applies Alexa certificate checking (default true)
// @param bool options.debug when true, sets up the route to handle GET requests (default false)
// @param function options.preRequest function to execute before every POST
// @param function options.postRequest function to execute after every POST
// @throws Error when router or expressApp options are not specified
// @returns this
this.express = function(options) {
if (!options.expressApp && !options.router) {
throw new Error("You must specify an express app or an express router to attach to.");
}
var defaultOptions = { endpoint: "/" + self.name, checkCert: true, debug: false };
options = defaults(options, defaultOptions);
// In ExpressJS, user specifies their paths without the '/' prefix
var deprecated = options.expressApp && options.router;
var endpoint = deprecated ? '/' : normalizeApiPath(options.endpoint);
var target = deprecated ? options.router : (options.expressApp || options.router);
if (deprecated) {
options.expressApp.use(normalizeApiPath(options.endpoint), options.router);
console.warn("Usage deprecated: Both 'expressApp' and 'router' are specified.\nMore details on https://github.com/alexa-js/alexa-app/blob/master/UPGRADING.md");
}
if (options.debug) {
target.get(endpoint, function(req, res) {
if (typeof req.query['schema'] != "undefined") {
res.set('Content-Type', 'text/plain').send(self.schema());
} else if (typeof req.query['utterances'] != "undefined") {
res.set('Content-Type', 'text/plain').send(self.utterances());
} else {
res.render("test", {
"app": self,
"schema": self.schema(),
"utterances": self.utterances()
});
}
});
}
if (options.checkCert) {
target.use(endpoint, verifier);
} else {
target.use(endpoint, bodyParser.json());
}
// exposes POST /<endpoint> route
target.post(endpoint, function(req, res) {
var json = req.body,
response_json;
// preRequest and postRequest may return altered request JSON, or undefined, or a Promise
Promise.resolve(typeof options.preRequest == "function" ? options.preRequest(json, req, res) : json)
.then(function(json_new) {
if (json_new) {
json = json_new;
}
return json;
})
.then(self.request)
.then(function(app_response_json) {
response_json = app_response_json;
return Promise.resolve(typeof options.postRequest == "function" ? options.postRequest(app_response_json, req, res) : app_response_json);
})
.then(function(response_json_new) {
response_json = response_json_new || response_json;
res.json(response_json).send();
})
.catch(function(err) {
console.error(err);
res.status(500).send("Server Error");
});
});
};
// add the app to the global list of named apps
if (name) {
alexa.apps[name] = self;
}
return this;
};
module.exports = alexa;