forked from beckyricha/alexa-gmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2852 lines (2801 loc) · 152 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
/**
*Copyright 2016 Rebecca Onuschak, except as noted below. This code may be implemented, with or without modification, for personal use, provided this copyright remains intact, but no other commercial or noncommercial license or rights are conveyed with this offer. Use of this Alexa skill, when obtained via the Amazon Alexa platform as a published skill, will be licensed in accordance with Amazon standard terms.
*/
/**
* A portion of this code was adapted from Amazon code samples, and this relies on an a modified version of the Alexa.js file provided by Amazon. The copyright statement above is for the overall GMail skill concept and for the coding work done to enable it. This does not alter in any way Amazon license terms for its portions of the code, or any rights that may be claimed by Google for use of its services and trademark names. The following statement was included by Amazon in its files:
Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the
License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
var APP_ID = process.env.appID;
//SETUP REFERENCES - The AlexaSkill prototype and https helper function
var AlexaSkill = require('./AlexaSkill');
var https = require('https');
var MyGmail = function () {
AlexaSkill.call(this, APP_ID);
};
// EXTEND AlexaSkill
MyGmail.prototype = Object.create(AlexaSkill.prototype);
MyGmail.prototype.constructor = MyGmail;
MyGmail.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
//erase google drive files from old sessions (any images from "show me").
var myToken=session.user.accessToken;
var postData = "{'function':'deleteFiles','parameters':['"+myToken+"']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
});
};
//if no intent was stated, then default to the review intent
MyGmail.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
if(!session.user.accessToken){
makeResponse(session,response,2);
} else{
var intent={
"name": "ReviewIntent",
"slots": {
"fromFilter": {
"name": "fromFilter"
},
"subjectFilter": {
"name": "subjectFilter"
},
"readFilter": {
"name": "readFilter",
"value": "new"
},
"dateFilter": {
"name": "dateFilter"
}
}
};
checkpin (intent,session, response);}
};
MyGmail.prototype.eventHandlers.onSessionEnded = function (SessionEndedRequest, session) {
};
//CONNECT INTENTS TO THE FUNCTIONS THAT WILL HANDLE THEM
MyGmail.prototype.intentHandlers = {
"CountIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"ReviewIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"AMAZON.NextIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"AMAZON.PreviousIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"GoToMessageIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"DetailsIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"MarkReadIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"MarkUnReadIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"StarIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"UnStarIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"DeleteIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"RefreshIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"ReplyIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"ReplyAllIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"PrintMessageIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"SetPrinterIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"ListAttachmentsIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"PrintAttachmentsIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"AMAZON.HelpIntent": function (intent, session, response) {
helpTheUser(intent, session, response);
},
"AMAZON.StopIntent": function (intent, session, response) {
makeResponse(session,response,28);
},
"AMAZON.CancelIntent": function (intent, session, response) {
makeResponse(session,response,28);
},
"AMAZON.RepeatIntent": function (intent, session, response) {
makeResponse(session, response,29);
},
"AMAZON.YesIntent": function (intent, session, response) {
questionYesHandler(intent, session, response);
},
"AMAZON.NoIntent": function (intent, session, response) {
questionNoHandler(intent, session, response);
},
"ShowMeIntent": function (intent, session, response) {
checkpin(intent, session,response);
},
"AMAZON.StartOverIntent": function (intent, session, response) {
checkpin(intent, session, response);
},
"HelpWithSlotIntent": function (intent, session, response) {
helpTheUser(intent, session, response);
},
"SetPINIntent": function (intent, session, response) {
checkpin(intent,session,response);
},
"SayPINIntent": function (intent, session, response) {
checkpin(intent,session,response);
},
"ClearPINIntent": function (intent, session, response) {
checkpin(intent,session,response);
},
"AdvancedModeOnIntent": function (intent, session, response) {
session.attributes.advanced=true;
checkpin(intent,session,response);
},
"AdvancedModeOffIntent": function (intent, session, response) {
session.attributes.advanced=false;
checkpin(intent,session,response);
},
"WaitIntent":function (intent, session, response) {
checkpin(intent,session,response);
}
};
//User has asked how many messages match certain criteria (or how many on the current list)
function getCount (intent, session, response) {
//initialize session attributes and some needed variables.
session.attributes.lastIntent="";
var myFilter; //will hold value for label (new,old,all,starred) on messages to search.
var searchString=""; //will hold the rest of the search parameters, if any.
var query="&q=in:inbox"; //holds the query string in gMail API format;
var useExistingList=false;
var myPath = "/gmail/v1/users/me/messages";
//check for filters on the intent:
var readSlot=intent.slots.readFilter.value;
var dateSlot=intent.slots.dateFilter.value;
//if no previous filter was saved in session attributes and no search is requested now, default to new messages:
if(!readSlot&&!session.attributes.readFilter&&!session.attributes.searchString)
{
if(!intent.slots.fromFilter.value&&!intent.slots.subjectFilter.value&&!dateSlot){myFilter=' new';}
else {myFilter="";}
}
//if the user only asked how many messages do I have while already working a list, assume the same list)
//assume they are asking about the same list they are working with:
else {
if(!readSlot&&!intent.slots.subjectFilter.value&&!intent.slots.fromFilter.value&&!dateSlot){
useExistingList=true;
}
}
//if something is in the intent slot, standardize the word choices the user had:
if(readSlot){
if(readSlot.match('read')||readSlot.match('old')){myFilter=' old';}
if(readSlot.match('unread')||readSlot.match('new')){myFilter=' new';}
if(readSlot=='all'||readSlot=='total'){myFilter=' total';}
if(readSlot.match('starred')||readSlot.match('important')){myFilter=' starred';}
}
if(!myFilter){myFilter="";}
//handle the date, recorded by Alexa as P[yY][mM][dD][T[hH][mM][s[.s]S]] where lower case is a number. we will convert it all //to days for ease of searching gmail, and will throw errors for anything lower than that.
if(dateSlot){
searchString = " sent in the last";
var daycounter=0;
var lastItem;
var errFlag;
var testItem;
for (var indexer = 0; indexer < dateSlot.length; indexer++)
{
testItem = dateSlot.substr(indexer,1);
if(isNaN(testItem))
{
switch(testItem)
{
case 'P':
break;
case 'Y':
if(lastItem == 1){searchString=searchString+" year";}
else{searchString=searchString+" "+lastItem+" years";}
daycounter=daycounter+lastItem*365;
break;
case 'M':
if(lastItem == 1){searchString=searchString+" month";}
else{searchString=searchString+" "+lastItem+" months";}
daycounter=daycounter+lastItem*30;
break;
case 'W':
if(lastItem == 1){searchString=searchString+" week";}
else{searchString=searchString+" "+lastItem+" weeks";}
daycounter=daycounter+lastItem*7;
break;
case 'D':
if(lastItem == 1){searchString=searchString+" day";}
else{searchString=searchString+" "+lastItem+" days";}
daycounter=daycounter+lastItem;
break;
case 'H':
errFlag=true;
break;
case 'T':
errFlag=true;
break;
default:
errFlag=true;
}
lastItem=testItem;
} else
{
if(isNaN(lastItem)){lastItem=testItem;}
else{lastItem = parseInt(lastItem.toString()+testItem.toString());}
}
if(errFlag)
{
session.attributes.helpContext=2;
session.attributes.tmpreadFilter="";
session.attributes.tmpsearchString="";
session.attributes.tmpmessageList="";
makeResponse(session,response,1);
}
}
query = query+"%20newer_than:"+daycounter+"d";
}
//get the rest of the search parameters
if(intent.slots.fromFilter.value){
searchString=searchString+" from "+intent.slots.fromFilter.value;
query = query+"%20from:"+intent.slots.fromFilter.value;
}
if(intent.slots.subjectFilter.value){
searchString=searchString+" about "+intent.slots.subjectFilter.value;
query = query +"%20subject:"+intent.slots.subjectFilter.value;
}
//If the filter has changed, get a new message list.
var filterTester="";
var searchTester="";
if(session.attributes.readFilter){filterTester=session.attributes.readFilter;}
if(session.attributes.searchString){searchTester=session.attributes.readFilter;}
if(myFilter==filterTester&&searchString==searchTester){useExistingList=true;}
if(!searchString){searchString="";}
if(!useExistingList){
switch(myFilter){
case ' new':
query=query + "%20is:unread";
break;
case ' old':
query=query +"%20is:read";
break;
case ' starred':
query = query +"%20is:starred";
break;
default:
}
//make the actual call to google API
getGmail(myPath,query,session, function mailResponseCallback(err, mailResponse) {
if (err) {
//error getting messages
if(err=="Error: 401"){
makeResponse(session,response,2);
} else {
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} else
{
if(mailResponse.resultSizeEstimate>0){ //message list returned
session.attributes.tmpreadFilter=myFilter;
session.attributes.tmpsearchString = searchString;
session.attributes.tmpmessageList=mailResponse;
session.attributes.tmpQuery=query;
session.attributes.helpContext=12;
makeResponse(session,response,4);
} else { //no messages found
session.tmpreadFilter="";
session.attributes.tmpsearchString = "";
session.attributes.tmpmessageList="";
session.attributes.tmpQuery="";
if(myFilter==' total'){myFilter='';}
if(session.attributes.messageList){session.attributes.helpContext=2;}
else {session.attributes.helpContext=1;}
makeResponse(session,response,5,myFilter,searchString);
}
}
});
} else //user asked for a count of the same list already being reviewed
{
session.attributes.helpContext=5;
session.attributes.tmpreadFilter="";
session.attributes.tmpsearchString="";
session.attributes.tmpmessageList="";
session.attributes.tmpQuery="";
makeResponse(session,response,6);
}
}
function getSummary (intent, session, response) {
// handles many intents - this finds and reads summary of each message
//initialize variables
var myFilter=""; //will hold value for selection of new,old,starred or all messages.
var searchString=""; //will hold the rest of the search parameters, if any.
var query="&q=in:inbox"; //holds the query string in gMail API format, skil only searches inbox for now
var useExistingList=false; //determines whether a new call to google for a message list is needed.
var myIndex=session.attributes.messageIndex;
if(!myIndex){myIndex=0;}
var name=intent.name;
var myPath, messageID, messageList; //params for gmail http calls
//process AMAZON.NextIntent, AMAZON.PreviousIntent, GoToMessageIntent indexing changes + error handling
if(name=='AMAZON.NextIntent'||name=='AMAZON.PreviousIntent'||name=='GoToMessageIntent'){
useExistingList=true;
if(!session.attributes.messageList){ //if there is no message list but user is asking to move around one
session.attributes.helpContext=4;
makeResponse(session,response,7); //response prompts user to check messages first.
} else {
switch(name){
case 'AMAZON.NextIntent':
++myIndex;
break;
case 'AMAZON.PreviousIntent':
--myIndex;
break;
case 'GoToMessageIntent':
if(!intent.slots.messagenumber.value){
session.attributes.helpContext=6;
makeResponse(session,response,10,'outofbounds')}
else{myIndex=intent.slots.messagenumber.value-1;}
break;
default:
}
}
}
//handle stored info if this was called from getCount function
if(session.attributes.tmpmessageList){
if(name=='AMAZON.YesIntent'){ //user wants to use the new search
session.attributes.readFilter=session.attributes.tmpreadFilter;
session.attributes.searchString=session.attributes.tmpsearchString;
session.attributes.messageList= session.attributes.tmpmessageList;
session.attributes.lastQuery = session.attributes.tmpQuery;
myIndex = 0;
useExistingList=true;
session.attributes.messageIndex=0;
} else { //user said anything but yes after search in getCount
//if user said anything that can't be a new search:
if(name!='ReviewIntent'&&name!='RefreshIntent'){
useExistingList=true;
}
}
session.attributes.tmpreadFilter="";
session.attributes.tmpsearchString="";
session.attributes.tmpmessageList="";
session.attributes.tmpQuery="";
} else {
if(name=='ReviewIntent'){ //all other intents use existing filters and can skip this.
//check for filters on the intent:
var readSlot=intent.slots.readFilter.value;
var dateSlot=intent.slots.dateFilter.value;
//if no previous filter and no search is requested now, default to new messages:
if(!readSlot&&!session.attributes.readFilter&&!session.attributes.searchString) //no previous filter and nothing in "new/old/starred"
{
if(!intent.slots.fromFilter.value&&!intent.slots.subjectFilter.value&&!dateSlot){ //no other search params
myFilter=' new';}
else { //no old search, but there is something searched besides "new/old/starred." Assume this means all
myFilter=" total";}
}
//if something is in the intent slot, standardize the word choices the user had:
if(readSlot){
if(readSlot.match('read')||readSlot.match('old')){myFilter=' old';}
if(readSlot.match('unread')||readSlot.match('new')){myFilter=' new';}
if(readSlot=='all'||readSlot=='total'){myFilter=' total';}
if(readSlot.match('starred')||readSlot.match('important')){myFilter=' starred';}
}
if(!myFilter){myFilter=" total";}
switch(myFilter){
case ' new':
query=query + "%20is:unread";
break;
case ' old':
query=query +"%20is:read";
break;
case ' starred':
query = query +"%20is:starred";
break;
default:
}
//handle the date, recorded by Alexa as P[yY][mM][dD][T[hH][mM][s[.s]S]]
//where lower case is a number. convert it all to days.
if(dateSlot){
searchString = " sent in the last";
var daycounter=0;
var lastItem;
var errFlag;
var testItem;
for (var indexer = 0; indexer < dateSlot.length; indexer++) {
testItem = dateSlot.substr(indexer,1);
if(isNaN(testItem)){
switch(testItem){
case 'P':
break;
case 'Y':
if(lastItem == 1){searchString=searchString+" year";}
else{searchString=searchString+" "+lastItem+" years";}
daycounter=daycounter+lastItem*365;
break;
case 'M':
if(lastItem == 1){searchString=searchString+" month";}
else{searchString=searchString+" "+lastItem+" months";}
daycounter=daycounter+lastItem*30;
break;
case 'W':
if(lastItem == 1){searchString=searchString+" week";}
else{searchString=searchString+" "+lastItem+" weeks";}
daycounter=daycounter+lastItem*7;
break;
case 'D':
if(lastItem == 1){searchString=searchString+" day";}
else{searchString=searchString+" "+lastItem+" days";}
daycounter=daycounter+lastItem;
break;
case 'T':
errFlag=true;
break;
default:
errFlag=true;
}
lastItem=testItem;
} else {
if(isNaN(lastItem)){lastItem=testItem;}
else{lastItem = parseInt(lastItem.toString()+testItem.toString());}
}
if(errFlag) {
if(!session.attributes.messageList){session.attributes.helpContext=1;}
else{session.attributes.helpContext=2;}
makeResponse(session,response,1);
}
}
query = query+"%20newer_than:"+daycounter+"d";
}
//get the rest of the search parameters
if(intent.slots.fromFilter.value){
searchString=searchString+" from "+intent.slots.fromFilter.value;
query = query+"%20from:"+intent.slots.fromFilter.value;
}
if(intent.slots.subjectFilter.value){
searchString=searchString+" about "+intent.slots.subjectFilter.value;
query = query +"%20subject:"+intent.slots.subjectFilter.value;
}
} //end of if statement that started the search for intent filters
} //end of else statement about tmp stored strings
//If there is no existing message list, user asked for a refresh, or the filter has changed, get a new message list.
//set variables to help with undefined comparing to ""
if(session.attributes.messageList){
messageList=session.attributes.messageList;
if(!myFilter&&!searchString){
myFilter=session.attributes.readFilter;
searchString=session.attributes.searchString;
}
}
var filterTester="";
var searchTester="";
if(session.attributes.readFilter){filterTester=session.attributes.readFilter;}
if(session.attributes.searchString){searchTester=session.attributes.readFilter;}
if(myFilter==filterTester&&searchString==searchTester&&messageList){useExistingList=true;}
if(intent.name=='RefreshIntent'){
useExistingList=false;
myFilter=session.attributes.readFilter;
searchString=session.attributes.searchString;
query=session.attributes.lastQuery;
}
if(!searchString){searchString="";}
if(!myFilter){myFilter="";}
if(!useExistingList){
//make the actual call to google API
myPath = "/gmail/v1/users/me/messages";
session.attributes.lastQuery=query;
session.attributes.messageIndex = 0;
session.attributes.attachments="";
session.attributes.currentMessage="";
session.attributes.messageList="";
session.attributes.readFilter = myFilter;
session.attributes.searchString = searchString;
getGmail(myPath,query,session, function mailResponseCallback(err, mailResponse) {
if (err) {
if(err=="Error: 401"){
makeResponse(session,response,2); //user needs to link account
} else { //some other error getting info back from Google
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} else {
//successfully got the new list, start the speech responses and handle zero length.
if(mailResponse.resultSizeEstimate===0){
if(!session.attributes.messageList){session.attributes.helpContext=1;}
else{session.attributes.helpContext=2;}
makeResponse(session,response,5,myFilter,searchString);
} else {
var subject;
var date;
var from,x;
var tmpfrom="";
session.attributes.messageList = mailResponse;
//call gmail again for first message
messageID=mailResponse.messages[0].id;
query="&format=METADATA";
myPath = "/gmail/v1/users/me/messages/"+messageID;
getGmail(myPath,query,session, function mailResponseCallback2(err2, mailResponse2) {
if (err2) {
if(err2=="Error: 401"){
makeResponse(session,response,2); //user need to re-link account
} else {
session.attributes.helpContext=3;
session.attributes.currentMessage="";
makeResponse(session,response,3);
}
} else { //read first message.
if(!mailResponse2){
session.attributes.helpContext=3;
session.attributes.currentMessage="";
makeResponse(session,response,3);
}
for (var headerIndex = 0; headerIndex < mailResponse2.payload.headers.length; headerIndex++) {
switch(mailResponse2.payload.headers[headerIndex].name){
case 'Subject':
subject = makereadable(mailResponse2.payload.headers[headerIndex].value);
break;
case 'From':
from = makereadable(mailResponse2.payload.headers[headerIndex].value).split(" ");
if(from.length==1){
tmpfrom = from[0];
}
else{
for (x in from){
if(from[x].indexOf("@")==-1){tmpfrom=tmpfrom+" "+from[x];}
}
}
from = tmpfrom;
break;
case 'Date':
let tmpdate = new Date(mailResponse2.payload.headers[headerIndex].value);
date = tmpdate.toDateString();
let today= new Date();
if(date==today.toDateString()){date="today";}
today.setDate(today.getDate() - 1);
if(today.toDateString()==date){date='yesterday';}
//remove any leading zero from the day to correct Alexa speech quirk.
if(date.charAt(8)=='0'){date=date.replace("0", "");}
break;
default:
}
}
session.attributes.helpContext=6;
session.attributes.readFilter=myFilter;
session.attributes.searchString=searchString;
session.attributes.currentMessage={"id":messageID,"from":from,"date":date,"subject":subject};
makeResponse(session,response,8);
}
});
}
}
});
}
else {
//just use the existing message list, but get another message;
var problem="";
var listlength=messageList.resultSizeEstimate;
//circle back and error check for valid message index (incremented/decremented above but no err check)
if(myIndex>=listlength&&name==='AMAZON.NextIntent'){problem = 'reachedend';}
if(myIndex<0&&name==='AMAZON.PreviousIntent'){problem = 'reachedfirst';}
if(name==='GoToMessageIntent'){
if(myIndex<0||myIndex>listlength){problem = 'outofbounds';}
}
session.attributes.helpContext=6;
if(problem){makeResponse(session,response,10,problem);}
else{
messageID=messageList.messages[myIndex].id;
myPath = "/gmail/v1/users/me/messages/"+messageID;
query="&format=METADATA";
getGmail(myPath,query,session, function mailResponseCallback3 (err, mailResponse) {
var subject;
var date;
var from,x;
var tmpfrom="";
if (err) {
if(err=="Error: 401"){
makeResponse(session,response,2);
} else {
session.attributes.helpContext=3;
session.attributes.currentMessage="";
session.attributes.messageIndex=myIndex;
makeResponse(session,response,3);
}
} else { //read first message.
if(!mailResponse){
session.attributes.helpContext=3;
session.attributes.currentMessage="";
session.attributes.messageIndex=myIndex;
makeResponse(session,response,3);
} else {
for (var headerIndex = 0; headerIndex < mailResponse.payload.headers.length; headerIndex++) {
switch(mailResponse.payload.headers[headerIndex].name){
case 'Subject':
subject = makereadable(mailResponse.payload.headers[headerIndex].value);
break;
case 'From':
from = makereadable(mailResponse.payload.headers[headerIndex].value).split(" ");
if(from.length==1){
tmpfrom = from[0];
}
else{
tmpfrom="";
for (x in from){
if(from[x].indexOf("@")==-1){tmpfrom=tmpfrom+" "+from[x];}
}
}
from = tmpfrom;
break;
case 'Date':
let tmpdate = new Date(mailResponse.payload.headers[headerIndex].value);
date = tmpdate.toDateString();
let today= new Date();
if(date==today.toDateString()){date="today";}
today.setDate(today.getDate() - 1);
if(today.toDateString()==date){date='yesterday';}
//remove any leading zero from the day to correct Alexa speech quirk.
if(date.charAt(8)=='0'){date=date.replace("0", "");}
break;
default:
}
}
var postData = "{'function':'modifyMsg','parameters':['"+messageID+"','MarkReadIntent']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){});
session.attributes.messageIndex=myIndex;
session.attributes.attachments="";
session.attributes.currentMessage={"id":messageID,"from":from,"date":date,"subject":subject};
session.attributes.helpContext=6;
makeResponse(session,response,9);
}
}
});
}
}
}
function messageDetails(intent, session, response){
var messageID=session.attributes.currentMessage.id;
if(!messageID){
session.attributes.helpContext=4;
makeResponse(session,response,7);
} else {
var postData = "{'function':'getPlainBody','parameters':['"+messageID+"']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) {
session.attributes.helpContext=3; //alert user to error
makeResponse(session,response,3);
} else {
var resp;
try{
resp=JSON.parse(scriptResponse).response.result;
var plainResponse=makereadable(resp);
session.attributes.helpContext=7;
makeResponse(session,response,11,plainResponse);
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
}
});
}
}
function modifyMessage(intent, session, response){
var postData;
var messageID;
if(session.attributes.currentMessage){messageID=session.attributes.currentMessage.id;}
if(!messageID){
session.attributes.helpContext=4;
makeResponse(session,response,7);
}
else{
session.attributes.helpContext=6;
postData = "{'function':'modifyMsg','parameters':['"+messageID+"','"+intent.name+"']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) {
session.attributes.helpContext=3;
makeResponse(session,response,3);
} else {
var resp;
try{
resp=JSON.parse(scriptResponse).response.result;
if(resp=='OK'){
session.attributes.helpContext=6;
makeResponse(session,response,12,intent.name);
} else {
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
}
});
}
}
function replyMessage(intent, session, response){
var postData;
var replyslot;
if(!session.attributes.currentMessage){
session.attributes.helpContext=4;
makeResponse(session,response,7);
}
else{
var messageID=session.attributes.currentMessage.id;
if(intent.name!='AMAZON.YesIntent'){
replyslot = intent.slots.replymessage.value;
if (!replyslot) {
session.attributes.helpContext=8;
makeResponse(session,response,13);
} else {
session.attributes.helpContext=9;
session.attributes.lastIntent=intent;
var FnName;
if(session.attributes.lastIntent.name=='ReplyIntent'){FnName = 'sendReply';}
if(session.attributes.lastIntent.name=='ReplyAllIntent'){FnName = 'sendReplyAll';}
session.attributes.postData = "{'function':'"+FnName+"','parameters':['"+messageID+"','"+replyslot+"']}";
makeResponse(session,response,14,replyslot);
}
} else {
postData = session.attributes.postData;
session.attributes.postData = "";
session.attributes.lastIntent="";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) {
session.attributes.helpContext=3;
makeResponse(session,response,3);
} else {
var resp;
try{
resp=JSON.parse(scriptResponse).response.result;
if(resp=='OK'){
session.attributes.helpContext=6;
makeResponse(session,response,15);
} else {
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
}
});
}
}
}
function setPrinter(intent, session, response){
var printSlot = intent.slots.printernumber.value;
var mytoken=session.user.accessToken;
if(!printSlot){
session.attributes.helpContext=10;
makeResponse(session,response,16);
} else {
var printerIndex = printSlot-1;
if(!session.attributes.printers){
var postData= "{'function':'getPrinterList','parameters':['"+mytoken+"']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) {
session.attributes.helpContext=3;
makeResponse(session,response,3);
} else {
var printers;
try{
printers=JSON.parse(scriptResponse).response.result;
if(printers.length === 0) {
session.attributes.helpContext=11;
makeResponse(session,response,17);
}
if(printers.length>1){
session.attributes.printers=printers;
if(0<=printerIndex&&printerIndex<printers.length){
session.attributes.selectedPrinter=printSlot;
if(session.attributes.messageList){session.attributes.helpContext=6;}
else {session.attributes.helpContext=4;}
makeResponse(session,response,18,printerIndex);
} else {
session.attributes.helpContext=10;
makeResponse(session,response,19);
}
}
if(printers.length == 1) {
session.attributes.selectedPrinter=1;
session.attributes.printers=printers;
if(session.attributes.messageList){session.attributes.helpContext=6;}
else {session.attributes.helpContext=4;}
makeResponse(session,response,18,0);
}
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
}
});
} else {
var printLen = session.attributes.printers.length;
if(printLen>1){
if(0<=printerIndex&&printerIndex<printLen){
session.attributes.selectedPrinter=printSlot;
if(session.attributes.messageList){session.attributes.helpContext=6;}
else {session.attributes.helpContext=4;}
makeResponse(session,response,18,printerIndex);
} else {
session.attributes.helpContext=10;
makeResponse(session,response,19);
}
} else {
session.attributes.selectedPrinter=1;
if(session.attributes.messageList){session.attributes.helpContext=6;}
else {session.attributes.helpContext=4;}
makeResponse(session,response,18,0);
}
}
}
}
function printStuff(intent, session, response){
//First, bounce with error if user said print while nothing exists to print;
if(!session.attributes.currentMessage){
session.attributes.helpContext=4;
makeResponse(session,response,7);
} else {
//set up variables
var messageID=session.attributes.currentMessage.id;
var mytoken=session.user.accessToken;
var postData,printerID,attachNum,resp,pages;
var selectedPrinter=session.attributes.selectedPrinter;
var printers=session.attributes.printers;
if(!printers){ //printers have not been retrieved from Cloud Print Service
//call Google apps scriupt to get printer list
postData= "{'function':'getPrinterList','parameters':['"+mytoken+"']}";
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) { //error handling
session.attributes.helpContext=3;
makeResponse(session,response,3);
} else {
try {
printers=JSON.parse(scriptResponse).response.result;
if(printers.length === 0) { //message to user no online printers found;
session.attributes.helpContext=11;
makeResponse(session,response,17);
}
if(printers.length>1){ //message to user to choose printer to use
session.attributes.printers=printers;
session.attributes.helpContext=10;
makeResponse(session,response,19);
}
if(printers.length == 1) { //if only one printer, select it without user input
selectedPrinter=1; //id = index +1. matches spoken input, not array.
session.attributes.selectedPrinter=selectedPrinter;
printerID=printers[selectedPrinter-1][0];
session.attributes.printers=printers;
//set up for 2 apps script calls - postData used now to get page count; session data sets up what to send after later user confirmation
switch(intent.name){
case 'PrintMessageIntent': //user asked to print message body
postData="{'function':'print','parameters':['"+mytoken+"','__google__docs','"+messageID+"','']}";
session.attributes.printdata="{'function':'print','parameters':['"+mytoken+"','"+printerID+"','"+messageID+"','']}";
break;
case 'PrintAttachmentsIntent': //user asked to print an attachment
if(!session.attributes.attachments){ //attachments have not been checked for the message (program doesn't check now because user may think there is a different current message; places decision in user control)
session.attributes.helpContext=6;
makeResponse(session,response,22);
} else {
if(session.attributes.attachments[0]=="no attachments"){ //message has no attachments
session.attributes.helpContext=6;
makeResponse(session,response,23);
} else {
if(!intent.slots.AttachNum.value){ //user asked for an attachment but Alexa did not record which
session.attributes.helpContext=6;
makeResponse(session,response,24);
} else { //Alexa understood the requested attachment number
attachNum=intent.slots.AttachNum.value-1;
if(attachNum>=0&&attachNum<session.attributes.attachments.length){ //everything looks OK to print
postData="{'function':'print','parameters':['"+mytoken+"','__google__docs','"+messageID+"',"+attachNum+"]}";
session.attributes.printdata="{'function':'print','parameters':['"+mytoken+"','"+printerID+"','"+messageID+"',"+attachNum+"]}";
} else { //Alexa recorded a requested attachment number that does not exist
session.attributes.helpContext=6;
makeResponse(session,response,24);
}
}
}
}
//Yes Intent can't get here as we are inside the case where no printers found.
} //end of switch
//call apps script to print to Google drive, get returned page count and delete resulting file from Drive
runScripts (postData, session, function scriptCallback(err,scriptResponse){
if (err) {
session.attributes.helpContext=3;
makeResponse(session,response,3);
} else {
try{
resp=JSON.parse(scriptResponse).response.result;
if(resp.length==2){
pages=resp[1];
//ask for user to confirm print job, with speech based on intent to print message or attachment
switch(intent.name){
case 'PrintMessageIntent':
session.attributes.helpContext=13;
makeResponse(session,response,20,pages);
break;
case 'PrintAttachmentsIntent':
session.attributes.helpContext=13;
makeResponse(session,response,21,attachNum,pages);
}
} else {
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
}
});
} //end of if (printer length=1)
} catch(e){
session.attributes.helpContext=3;
makeResponse(session,response,3);
}
} //end of else for outer http call
}); //end of outer call to runscripts to get printer list
} else { //The printer list was already fetched from cloud print
if(!selectedPrinter){ //no printer is selected
if(printers.length === 0) { //no priners are online
session.attributes.helpContext=11;
makeResponse(session,response,17);
}
if(printers.length>1){ //user needs to choose a printer because there are more than one
session.attributes.helpContext=10;
makeResponse(session,response,19);
}
if(printers.length == 1) { //only one exxists, use it.
selectedPrinter=1; //id = index +1. matches spoken input, not array.
session.attributes.selectedPrinter=selectedPrinter;