-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
693 lines (618 loc) · 23.5 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
'use strict';
const Alexa = require('alexa-sdk');
const awsSDK = require('aws-sdk');
const request = require('request');
// Tables
const itemsTableName = 'Items';
const timeStampTableName = 'TimeStamp';
const activeListTableName = 'ActiveList';
const historyTableName = 'HistoryOfItems';
const eventsTableName = 'Events';
const userInfoTableName = 'UsersInfo';
const instructions = `Welcome to Stuffer.
The following features are available: storing item. finding item.
listing and retrieving items for an event.
To store an item say, add an item.
To find an item say, find an item.
To list items for an event say, add event, name, and, add items. item one, item two, item three, end of list.
To retrieve items for an event say, list items.
For any event, only five items can be added.
Start now by adding an item.
To hear this again, ask stuff locator to help.`;
const helpMessage = `Having trouble there? The skill provides the following features - "find item feature", "store item feature", "create event feature" and "list event feature". So which feature do you want help in?`;
const findIntentMessage = `To find an item, try saying, "find an item"`;
const storeIntentMessage = `To store an item, try saying, "add an item"`;
const createEventMessage = `To create an event, try saying, "create event Party and add the following items cap, balloon, cake end of list"`;
const listEventMessage = `To list an event try saying, "list an event"`;
const documentClient = new awsSDK.DynamoDB.DocumentClient();
let activeListFetchedStatus = false;
//this activeList is filled up at the beginning of the program
let activeList = [];
// handles all Intents
const handlers = {
'FindItemIntent': function () {
let emitCopy = this.emit;
const { userId } = this.event.session.user;
const { slots } = this.event.request.intent;
if(!activeListFetchedStatus) {
fetchActiveListAndCache(userId);
fetchExistingTimeStamp(userId);
}
//name of the item
if (!slots.Item.value) {
const slotToElicit = 'Item';
const speechOutput = 'What item is to be found?';
const repromptSpeech = 'Please specify the item';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
} else if (slots.Item.confirmationStatus !== 'CONFIRMED') {
if (slots.Item.confirmationStatus !== 'DENIED') {
// slot status: unconfirmed
const slotToConfirm = 'Item';
const speechOutput = `The name of the item is ${slots.Item.value}, correct?`;
const repromptSpeech = speechOutput;
return this.emit(':confirmSlot', slotToConfirm, speechOutput, repromptSpeech);
}
const slotToElicit = 'Item';
const speechOutput = 'What item is to be found?';
const repromptSpeech = 'Please specify the item';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
}
const itemName = slots.Item.value;
let searchFlag = false;
let itemLocation = '';
if(!activeList.length) {
if(!searchFlag) {
console.log('Attempting to read data in Items table');
let params = {
TableName: itemsTableName,
Key:{
"itemName-userId": slots.Item.value + "-" + userId
}
};
documentClient.get(params, function(err, data) {
if (err) {
console.error("Unable to find item. Error JSON:", JSON.stringify(err, null, 2));
emitCopy(':tell', 'cannot connect to the server');
} else {
console.log("Found item:", JSON.stringify(data, null, 2));
if(data.Item) {
searchFlag = true;
itemLocation = data.Item.locationName;
emitCopy(":tell", `${data.Item.itemName} exists at ${data.Item.locationName}`);
//deleting found item form itemsTable. Updation in historyTable Takes place below
let params = {
TableName: itemsTableName,
Key:{
"itemName-userId": slots.Item.value + "-" + userId
}
};
documentClient.delete(params, function (err, data) {
if (err) {
console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log(`Deleted Item`, JSON.stringify(data, null, 2));
updateHistoryOfItem(userId, itemName, itemLocation);
}
})
} else {
const getParams = {
TableName: historyTableName,
Key: {
"itemName-userId": `${itemName}-${userId}`
}
};
documentClient.get(getParams, function (err, data) {
if(err) {
console.log('error, nothing found');
emitCopy(':tell', 'cannot connect to the server');
} else {
if(data.Item) {
emitCopy(":tell", `History tells me that the item might exist at ${data.Item.historyArray.join(". ")}`)
} else {
emitCopy(":tell", "Item not found")
}
}
})
}
}
});
}
}
//search in activeList with itemName
for (let activeMember of activeList) {
if(searchFlag)
break;
if(activeMember.itemName === itemName) {
emitCopy(":tell", `${itemName} exists at ${activeMember.locationName}`);
searchFlag = true;
itemLocation = activeMember.locationName;
const index = activeList.indexOf(activeMember);
activeList.splice(index, 1);
storeActiveList(userId);
updateHistoryOfItem(userId, itemName, itemLocation);
break;
}
if(activeMember === activeList[activeList.length-1]) {
// search in Items table using ItemName
if(!searchFlag) {
console.log('Attempting to read data in Items table');
let params = {
TableName: itemsTableName,
Key:{
"itemName-userId": slots.Item.value + "-" + userId
}
};
documentClient.get(params, function(err, data) {
if (err) {
console.error("Unable to find item. Error JSON:", JSON.stringify(err, null, 2));
emitCopy(':tell', 'cannot connect to the server');
} else {
console.log("Found item:", JSON.stringify(data, null, 2));
if(data.Item) {
searchFlag = true;
itemLocation = data.Item.locationName;
emitCopy(":tell", `${data.Item.itemName} exists at ${data.Item.locationName}`);
//deleting found item form itemsTable. Updation in historyTable Takes place below
let params = {
TableName: itemsTableName,
Key:{
"itemName-userId": slots.Item.value + "-" + userId
}
};
documentClient.delete(params, function (err, data) {
if (err) {
console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log(`Deleted Item`, JSON.stringify(data, null, 2));
updateHistoryOfItem(userId, itemName, itemLocation);
}
})
} else {
const getParams = {
TableName: historyTableName,
Key: {
"itemName-userId": `${itemName}-${userId}`
}
};
documentClient.get(getParams, function (err, data) {
if(err) {
console.log('error, nothing found');
emitCopy(':tell', 'cannot connect to the server');
} else {
if(data.Item) {
emitCopy(":tell", `History tells me that the item might exist at ${data.Item.historyArray.join(". ")}`)
} else {
emitCopy(":tell", "Item not found")
}
}
})
}
}
});
}
}
}
},
"HelpMessageIntent": function () {
const { slots } = this.event.request.intent;
let speechOutput, reprompt;
if(slots.MessageType.value.toLowerCase() === "find item feature") {
speechOutput = findIntentMessage;
reprompt = speechOutput;
} else if(slots.MessageType.value.toLowerCase() === "store item feature") {
speechOutput = storeIntentMessage;
reprompt = speechOutput;
} else if(slots.MessageType.value.toLowerCase() === "list event feature") {
speechOutput = listEventMessage;
reprompt = speechOutput;
} else {
speechOutput = createEventMessage;
reprompt = speechOutput;
}
this.emit(':ask', speechOutput, reprompt);
},
'StoreItemIntent': function () {
const { userId } = this.event.session.user;
const { slots } = this.event.request.intent;
if(!activeListFetchedStatus) {
fetchActiveListAndCache(userId);
fetchExistingTimeStamp(userId);
}
console.log('asas', slots);
// name of the item
if (!slots.Item.value) {
const slotToElicit = 'Item';
const speechOutput = 'What is the item to be stored?';
const repromptSpeech = 'Please specify the item';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
} else if (slots.Item.confirmationStatus !== 'CONFIRMED') {
if (slots.Item.confirmationStatus !== 'DENIED') {
// slot status: unconfirmed
const slotToConfirm = 'Item';
const speechOutput = `The item is ${slots.Item.value}, correct?`;
const repromptSpeech = speechOutput;
return this.emit(':confirmSlot', slotToConfirm, speechOutput, repromptSpeech);
}
const slotToElicit = 'Item';
const speechOutput = 'What item is to be stored?';
const repromptSpeech = 'Please specify the item';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
}
//name of the place where the item is to be stored
if (!slots.Place.value) {
const slotToElicit = 'Place';
const speechOutput = 'Where is the item stored?';
const repromptSpeech = 'Please specify the location';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
} else if (slots.Place.confirmationStatus !== 'CONFIRMED') {
if (slots.Place.confirmationStatus !== 'DENIED') {
// slot status: unconfirmed
const slotToConfirm = 'Place';
const speechOutput = `The item location is ${slots.Place.value}, correct?`;
const repromptSpeech = speechOutput;
return this.emit(':confirmSlot', slotToConfirm, speechOutput, repromptSpeech);
}
// slot status: denied -> reprompt for slot data
const slotToElicit = 'Place';
const speechOutput = 'Where can the item be found?';
const repromptSpeech = 'Please specify the location';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
}
activeList.push({
itemName: slots.Item.value,
locationName: slots.Place.value
});
storeActiveList(userId);
this.emit(":tell", `item successfully stored`)
},
'StoreEventItemIntent': function () {
let emitCopy = this.emit;
const { userId } = this.event.session.user;
let event_name = this.event.request.intent.slots.Event.value;
let itemName = this.event.request.intent.slots.Item.value;
let itemTwo = this.event.request.intent.slots.Itemtwo.value;
let itemThree = this.event.request.intent.slots.Itemthree.value;
let itemFour = this.event.request.intent.slots.Itemfour.value;
let itemFive = this.event.request.intent.slots.Itemfive.value;
let params = {
TableName: eventsTableName,
Item:{
"userId-eventName": userId + "-"+ event_name,
"eventName":event_name,
"itemName": itemName,
"itemTwoName": itemTwo,
"itemThreeName": itemThree,
"itemFourName": itemFour,
"itemFiveName": itemFive
}
};
documentClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
emitCopy(':tell', 'cannot connect to the server');
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
emitCopy(':tell', "event created");
}
});
},
'FindEventItemIntent': function () {
let emitCopy = this.emit;
const { userId } = this.event.session.user;
const { slots } = this.event.request.intent;
//name of the item
if (!slots.Event.value) {
const slotToElicit = 'Event';
const speechOutput = 'What is the event name?';
const repromptSpeech = 'Please specify the event';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
} else if (slots.Event.confirmationStatus !== 'CONFIRMED') {
if (slots.Event.confirmationStatus !== 'DENIED') {
// slot status: unconfirmed
const slotToConfirm = 'Event';
const speechOutput = `The event is ${slots.Event.value}, correct?`;
const repromptSpeech = speechOutput;
return this.emit(':confirmSlot', slotToConfirm, speechOutput, repromptSpeech);
}
const slotToElicit = 'Event';
const speechOutput = 'What is the event name?';
const repromptSpeech = 'Please specify the event';
return this.emit(':elicitSlot', slotToElicit, speechOutput, repromptSpeech);
}
console.log('Attempting to read data in Events table');
let params = {
TableName: eventsTableName,
Key:{
"userId-eventName": userId+ "-"+slots.Event.value
}
};
documentClient.get(params, function(err, data) {
if (err) {
console.error("Unable to find item. Error JSON:", JSON.stringify(err, null, 2));
emitCopy(':tell', 'cannot connect to the server');
} else {
console.log("Found item:", JSON.stringify(data, null, 2));
if(data.Item) {
if(data.Item.itemName) {
if(data.Item.itemTwoName) {
if(data.Item.itemThreeName) {
if(data.Item.itemFourName) {
if(data.Item.itemFiveName) {
emitCopy(":tell", `For ${data.Item.eventName} you require. ${data.Item.itemName}.
${data.Item.itemTwoName}. ${data.Item.itemThreeName}. ${data.Item.itemFourName}.
${data.Item.itemFiveName}.`);
}
emitCopy(":tell", `For ${data.Item.eventName} you require. ${data.Item.itemName}.
${data.Item.itemTwoName}. ${data.Item.itemThreeName}. ${data.Item.itemFourName}.`);
}
emitCopy(":tell", `For ${data.Item.eventName} you require. ${data.Item.itemName}.
${data.Item.itemTwoName}. ${data.Item.itemThreeName}.`);
}
emitCopy(":tell", `For ${data.Item.eventName} you require. ${data.Item.itemName}.
${data.Item.itemTwoName}.`);
}
emitCopy(":tell", `For ${data.Item.eventName}. you require ${data.Item.itemName}.`);
}
emitCopy(":tell", `For ${data.Item.eventName}. you do not require anything.`);
} else {
emitCopy(":tell", "no such event exists");
}
}
});
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', 'Goodbye!');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', 'Goodbye!');
},
'AMAZON.HelpIntent': function () {
const speechOutput = helpMessage;
const reprompt = helpMessage;
this.emit(':ask', speechOutput, reprompt);
},
'LaunchRequest': function () {
let emitCopy = this.emit;
const { userId } = this.event.session.user;
const accessToken = this.event.session.user.accessToken;
console.log(this);
// checkUserInfo(userId, accessToken, emitCopy);
storeUserInfo (userId, accessToken, emitCopy)
},
'Unhandled': function() {
this.emit(':ask', 'Sorry I didnt understand that. Ask stuff locator to help for assistance.');
}
};
//function to update history
function updateHistoryOfItem(userId, itemName, itemLocation) {
let historyArrayOfItem = [];
const readParams = {
TableName: historyTableName,
Key: {
"itemName-userId": `${itemName}-${userId}`
}
};
documentClient.get(readParams, function (err, data) {
if (err) {
console.log('error, the history array of the item couldn\'t be fetched');
} else {
if(data.Item) {
historyArrayOfItem = data.Item.historyArray;
if(!historyArrayOfItem.includes(itemLocation)) {
historyArrayOfItem.push(itemLocation);
if(historyArrayOfItem.length > 5) {
historyArrayOfItem.shift();
}
}
} else {
historyArrayOfItem.push(itemLocation);
}
const writeParams = {
TableName: historyTableName,
Item: {
"itemName-userId": `${itemName}-${userId}`,
"historyArray": historyArrayOfItem
}
};
documentClient.put(writeParams, function (err, data) {
if(err) {
console.log('error, the history array of the item couldn\'t be updated');
} else {
console.log('this history of the Item has been updated', data);
}
})
}
})
}
//function to fetch activeList at the beginning of the start of Alexa
function fetchActiveListAndCache(userId) {
const params = {
TableName: activeListTableName,
Key: {
"userId": userId
}
};
documentClient.get(params, function (err, data) {
if(err) {
console.log("oops! activeList couldn't be fetched", err);
} else {
console.log('activeList has been cached');
activeListFetchedStatus = true;
if(data.Item) activeList = data.Item.activeList;
}
})
}
//stores the activeList back into the ActiveList table after the program comes to a halt
function storeActiveList(userId) {
const params = {
TableName: activeListTableName,
Item: {
"userId": userId,
"activeList": activeList
}
};
documentClient.put(params, function (err, data) {
if(err) {
console.log("activeList couldn't be stored");
} else {
console.log("activeList has been stored", data);
}
})
}
//moves all old items to masterDB
function localALtoDBAL(userId, transferList) {
transferList.forEach(function (item) {
const params = {
TableName: itemsTableName,
Item:{
"itemName-userId": item.itemName + "-" + userId,
"userId": userId,
"itemName": item.itemName,
"locationName": item.locationName
}
};
documentClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item to the database:", JSON.stringify(data, null, 2));
}
});
})
}
//gets old timestamp and then updates DB if needed
function fetchExistingTimeStamp(userId) {
const timeStampParams = {
TableName: timeStampTableName,
Key: {
"userId": userId
}
};
documentClient.get(timeStampParams, function (err, data) {
if (err) {
console.error("Time stamp not working", JSON.stringify(err, null, 2));
checkRenew(false, userId);
} else {
console.log("Time Stamp found:", JSON.stringify(data, null, 2));
checkRenew(data, userId);
}
});
}
//updates db after checking time
function checkRenew(data, userId) {
const date = new Date();
const currentTimeStamp = date.getTime();
if(!data.Item) {
let params = {
TableName: timeStampTableName,
Item:{
"userId": userId,
"timestamp": currentTimeStamp
}
};
documentClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
} else {
if(currentTimeStamp - data.Item.timestamp >= 259200000) {
let params = {
TableName: timeStampTableName,
Item:{
"userId": userId,
"timestamp": currentTimeStamp
}
};
documentClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
// transfers local Active list items to larger ActiveList existing in DB. i.e. Items Table after every 3 days
// empties the local ActiveList afterwards.
localALtoDBAL(userId, activeList)
activeList = []
}
});
}
}
}
//checks if users info uis present in the userInfoTable, if not, makes an entry
/*
function checkUserInfo(userId, accessToken, emitCopy) {
const searchParams = {
TableName: userInfoTableName,
Key: {
"userId": userId
}
};
documentClient.get(searchParams, function (err, data) {
if(err) {
console.error ("Unable to find item. Error JSON:", JSON.stringify (err, null, 2));
storeUserInfo (userId, accessToken, emitCopy)
}
});
}
*/
// stores the info after exchanging the ouath accessToken
function storeUserInfo(userId, accessToken, emitCopy) {
if (!accessToken) {
emitCopy(':tellWithLinkAccountCard', `Welcome to Stuffer, please login, for a better experience`);
return;
}
let profileURL = 'https://api.amazon.com/user/profile?access_token=';
profileURL += accessToken;
request(profileURL, function(error, response, body) {
if (response.statusCode === 200) {
const profile = JSON.parse(body);
const searchParams = {
TableName: userInfoTableName,
Item: {
"userId": userId,
"name": profile.name,
"email": profile.email
}
};
documentClient.put(searchParams, function (err, data) {
if(err) {
console.error("Unable to store UserInfo. Error JSON:", JSON.stringify(err, null, 2));
} else {
welcomeNewUser(userId, emitCopy, profile.name.split(' ')[0])
}
});
} else {
emitCopy(':tell', "There was problem with the authentication. Please try again.");
}
});
}
// if every thing works well, welcomes the new User
function welcomeNewUser(userId, emitCopy, name) {
const searchParams = {
TableName: timeStampTableName,
Key: {
"userId": userId
}
};
documentClient.get(searchParams, function (err, data) {
if(err) {
console.error("Unable to find item. Error JSON:", JSON.stringify(err, null, 2));
emitCopy(':tell', 'cannot connect to the server');
} else {
if(data.Item) {
emitCopy(":ask", `Hey ${name}, how do you want me to help you?`)
} else {
emitCopy(':ask', instructions);
}
}
});
}
exports.myHandler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
const APP_ID = "amzn1.ask.skill.4e32f60b-02f6-45b2-9d88-0bf895ea52c7";
alexa.appId = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};