forked from alexa-js/alexa-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
429 lines (403 loc) · 12.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
var Promise = require("bluebird");
var AlexaUtterances = require("alexa-utterances");
var SSML = require("./to-ssml");
var alexa = {};
alexa.response = function() {
this.resolved = false;
this.response = {
"version": "1.0",
"sessionAttributes": {},
"response": {
"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": "PlainText",
"text": ""
};
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;
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.session = function(key, val) {
if (typeof val == "undefined") {
return this.response.sessionAttributes[key];
} else {
this.response.sessionAttributes[key] = val;
}
return this;
};
this.clearSession = function(key) {
if (typeof key == "string" && typeof this.response.sessionAttributes[key] != "undefined") {
delete this.response.sessionAttributes[key];
} else {
this.response.sessionAttributes = {};
}
return this;
};
};
alexa.request = function(json) {
this.data = json;
this.slot = function(slotName, defaultValue) {
try {
return this.data.request.intent.slots[slotName].value;
} catch (e) {
console.error("missing intent in request: " + slotName, e);
return defaultValue;
}
};
this.type = function() {
try {
return this.data.request.type;
} catch (e) {
console.error("missing type", e);
return null;
}
};
if (typeof this.data.session == 'undefined') {
this.sessionDetails = {
"new": false,
"sessionId": null,
"userId": null,
"accessToken": null,
"attributes": {},
"application": {
applicationId: null
}
};
} else {
this.sessionDetails = {
"new": this.data.session.new,
"sessionId": this.data.session.sessionId,
"userId": this.data.session.user.userId,
"accessToken": this.data.session.user.accessToken || null,
"attributes": this.data.session.attributes,
"application": this.data.session.application
};
}
this.userId = this.sessionDetails.userId;
this.applicationId = this.sessionDetails.application.applicationId;
this.sessionId = this.sessionDetails.sessionId;
this.sessionAttributes = this.sessionDetails.attributes;
this.isSessionNew = (true === this.sessionDetails.new);
this.session = function(key) {
try {
return this.sessionDetails.attributes[key];
} catch (e) {
console.error("key not found on session attributes: " + key, e);
return;
}
};
};
alexa.apps = {};
alexa.app = function(name, endpoint) {
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 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",
// If some other exception happens
"GENERIC_ERROR": "Sorry, the application encountered an error"
};
// 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*/) {};
this.endpoint = endpoint;
// 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 = null;
}
self.intents[intentName] = {
"name": intentName,
"function": func
};
if (schema) {
self.intents[intentName].schema = schema;
}
};
this.launchFunc = null;
this.launch = function(func) {
self.launchFunc = func;
};
this.sessionEndedFunc = null;
this.sessionEnded = function(func) {
self.sessionEndedFunc = func;
};
this.messageReceivedFunc = null;
this.messageReceived = function(func) {
self.messageReceivedFunc = func;
}
this.request = function(request_json) {
return new Promise(function(resolve, reject) {
var request = new alexa.request(request_json);
var response = new alexa.response();
var postExecuted = false;
// Attach Promise resolve/reject functions to the response object
response.send = function(exception) {
if (typeof self.post == "function" && !postExecuted) {
postExecuted = true;
self.post(request, response, requestType, exception);
}
if (!response.resolved) {
response.resolved = true;
resolve(response.response);
}
};
response.fail = function(msg, exception) {
if (typeof self.post == "function" && !postExecuted) {
postExecuted = true;
self.post(request, response, requestType, exception);
}
if (!response.resolved) {
response.resolved = true;
reject(msg);
}
};
try {
var key;
// Copy all the session attributes from the request into the response so they persist.
// The Alexa API doesn't think session variables should persist for the entire
// duration of the session, but I do.
if (request.sessionAttributes && self.persistentSession) {
for (key in request.sessionAttributes) {
response.session(key, request.sessionAttributes[key]);
}
}
var requestType = request.type();
if (typeof self.pre == "function") {
self.pre(request, response, requestType);
}
if (!response.resolved) {
if ("IntentRequest" === requestType) {
var intent = request_json.request.intent.name;
if (typeof self.intents[intent] != "undefined" && typeof self.intents[intent]["function"] == "function") {
if (false !== self.intents[intent]["function"](request, response)) {
response.send();
}
} else {
throw "NO_INTENT_FOUND";
}
} else if ("LaunchRequest" === requestType) {
if (typeof self.launchFunc == "function") {
if (false !== self.launchFunc(request, response)) {
response.send();
}
} else {
throw "NO_LAUNCH_FUNCTION";
}
} else if ("SessionEndedRequest" === requestType) {
if (typeof self.sessionEndedFunc == "function") {
if (false !== self.sessionEndedFunc(request, response)) {
response.send();
}
}
} else if ("Messaging.MessageReceived" === requestType) {
if (typeof self.messageReceivedFunc == "function") {
if (false !== self.messageReceivedFunc(request, response)) {
response.send();
}
} else {
response.fail("No messageReceived function defined.");
}
} else {
throw "INVALID_REQUEST_TYPE";
}
}
} catch (e) {
if (typeof self.error == "function") {
self.error(e, request, response);
} else if (typeof e == "string" && self.messages[e]) {
response.say(self.messages[e]);
response.send(e);
}
if (!response.resolved) {
response.fail("Unhandled exception" + e.message, 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,
"slots": []
};
if (intent.schema) {
if (intent.schema.slots) {
for (key in intent.schema.slots) {
intentSchema.slots.push({
"name": key,
"type": intent.schema.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.schema && intent.schema.utterances) {
intent.schema.utterances.forEach(function(sample) {
var list = AlexaUtterances(sample,
intent.schema.slots,
self.dictionary,
self.exhaustiveUtterances);
list.forEach(function(utterance) {
out += intent.name + "\t" + (utterance.replace(/\s+/g, " ")).trim() + "\n";
});
});
}
}
return out;
};
// A built-in handler for AWS Lambda
this.handler = function(event, context) {
self.request(event)
.then(function(response) {
context.succeed(response);
})
.catch(function(response) {
context.fail(response);
});
};
// For backwards compatibility
this.lambda = function() {
return self.handler;
};
// A utility method to bootstrap alexa endpoints into express automatically
this.express = function(express, path, enableDebug) {
var endpoint = (path || "/") + (self.endpoint || self.name);
express.post(endpoint, function(req, res) {
self.request(req.body).then(function(response) {
res.json(response);
}, function() {
res.status(500).send("Server Error");
});
});
if (typeof enableDebug != "boolean") {
enableDebug = true;
}
if (enableDebug) {
express.get(endpoint, function(req, res) {
res.render("test", {
"json": self,
"schema": self.schema(),
"utterances": self.utterances()
});
});
}
};
// Add the app to the global list of named apps
if (name) {
alexa.apps[name] = self;
}
return this;
};
module.exports = alexa;