-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
621 lines (547 loc) · 20.1 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
'use strict';
var https = require('https');
var User = require(__dirname + '/tools/CanvasUser');
var storage = require(__dirname + '/storage');
var express = require("express");
var ERRORS = require("./customerror");
var Promise = require("bluebird");
Promise.config({
cancellation: true,
longStackTraces: true
});
const alexia = require('alexia');
const app = alexia.createApp('CanvasGradie');
app.setShouldEndSessionByDefault(true);
function isValidObject(obj) {
if ((typeof(obj) !== 'undefined') && (obj !== null)) {
return Object.keys(obj).length;
} else
return false;
}
function checkLinked() {
}
function getAmazon(token, session) {
var amz_account = session.amz_account || {};
if (process.env.NODE_CLAYTON === "true") {
console.log("------------HI Clayton-------------");
amz_account = require("./accounts").amz_account;
console.log(amz_account)
console.log("-----------------------------------");
}
if (isValidObject(amz_account)) {
console.log("using session")
return Promise.resolve(amz_account);
} else {
if (token) {
return storage.getAmazonAccount(token).then(amz_account => {
session.amz_account = {}
session.amz_account = amz_account;
return amz_account;
})
} else {
return Promise.reject(new ERRORS.NotLinkedError("Not linked"));
}
}
}
function checkCanvas(user) {
var valid = user.hasValidToken();
if (!valid) {
throw new ERRORS.InvalidCanvasTokenError("Not linked");
} else {
return user;
}
}
function wrapSSML(ssml) {
return "<speak>" + ssml + "</speak>";
}
function handleNoMatch(user, slots, data, done) {
var stringResult = 'I could not tell what course you wanted. I suggest you login to canvas skill <break time=".1ms"/>dot <break time=".1ms"/>tk <break time="1ms"/>so you can add more custom nicknames' +
'<break time="5ms"/> Would you like me to list your current courses? ';
var courselist = "";
var cnt = 1;
var listResult = "";
user.courses.forEach((course, index) => {
courselist += cnt + '. ' + (course.meta.title || course.nickname || course.name) + '\n';
listResult += cnt + '<break time="1ms"/>' + (course.meta.title || course.nickname || course.name) + '<break time="2ms"/>\n';
cnt++;
})
done({
text: "<speak>" + stringResult + "</speak>",
ssml: true,
attrs: {
action: "MatchCourse",
origSlots: slots,
from: data.request.intent.name,
courselist: courselist,
listResult: listResult,
courseCount: user.courses.length
},
end: false
});
}
function linkAccount(done) {
done({
text: "Unable to gather grades, please link your account in the Alexa app.",
card: {
type: "LinkAccount"
},
attrs: {
saved: "asdf"
},
end: true
})
}
function linkCanvas(done) {
done({
text: wrapSSML('Unable to gather your grades without gradebook access, please add a Canvas Token. Visit ' +
'canvas skill <break time=".1ms"/>dot <break time=".1ms"/>tk <break time="1ms"/> to add a token.'),
ssml: true,
card: {
title: 'Update Canvas Account',
content: 'This skill cannot access your canvas acount without a valid access token.\n To add a token, ' +
'please visit www.CanvasSkill.tk. While there you can also add custom nicknames for your classes ' +
'and view your settings.'
},
end: true
});
}
function getUserfromIntent(slots, attrs, data, done) {
var accessToken = data.session.user.accessToken || 0;
// if (accessToken) {
return getAmazon(accessToken, data.session.user).then(account => {
return storage.getUser(account).then(u => {
if (u === false) {}
var user = new User(u);
console.log("Got user from intent")
return checkCanvas(user);
});
}).catch(ERRORS.NotLinkedError, function(err) {
linkAccount(done);
return Promise.reject(new ERRORS.HandledError(err.message, err));
}).catch(ERRORS.InvalidCanvasTokenError, function(err) {
console.log(err)
linkCanvas(done);
return Promise.reject(new ERRORS.HandledError(err.message, err));
}).catch(ERRORS.Request.StatusCodeError, function(err) {
return Promise.reject(new ERRORS.PresentableError("Unable to verifiy amazon account.", err));
});
}
app.onStart((slots, attrs, data, done) => {
console.log("how well inside")
return getUserfromIntent(slots, attrs, data, done).then(user => {
done({
text: 'Welcome to My gradebook, you can ask about your grades, or say help to get more instructions',
end: false
});
}).catch(ERRORS.PresentableError, function(err) {
done({
text: err.message,
end: true
});
}).catch(ERRORS.HandledError, function(err) {
//Handled error
console.log("I dont have to worry");
}).catch(function(err) {
done({
text: "Unexpected error",
end: true
});
});
});
var exit = function(slots, attrs, data, done) {
done({
text: 'My-Gradebook closed. Goodbye.',
end: true
});
};
app.intent('stop', 'read original request data async', exit);
app.intent('cancel', 'read original request data async', exit);
app.onEnd(exit);
app.defaultActionFail((slots, attrs, data, done) => {
done({
text: 'Your command is invalid, you can ask about your grades, upcoming assignments, how you are doing, or say help to get more instructions',
end: true
});
});
var getHowWellIntent = app.intent('GetHowWellIntent', 'read original request data async', (slots, attrs, data, done) => {
console.log("how well inside")
return getUserfromIntent(slots, attrs, data, done).then(user => {
var letters = {
'a': 0,
'b': 0,
'c': 0,
'd': 0,
'f': 0,
};
//Populate letters with the amount of letter grades in gradebook
return user.getCourses().then(courses => {
courses.forEach(course => {
var grade = course.getGrade();
console.log(grade + "\t " + course.name)
if (grade !== null) {
if (grade >= 90) {
letters.a++
} else if (grade >= 80) {
letters.b++
} else if (grade >= 70) {
letters.c++
} else if (grade >= 60) {
letters.d++
} else {
letters.f++
}
}
});
var output = "You are doing ";
var howWell = "good"
if ((letters.f + letters.d + letters.c + letters.b) == 0 && letters.a > 0) {
howWell = "fantastic";
} else if ((letters.f + letters.d + letters.c) == 0 && (letters.a + letters.b > 0)) {
howWell = "great";
} else if ((letters.f + letters.d) == 0 && (letters.a + letters.b + letters.c > 0)) {
howWell = "good";
} else if ((letters.f) == 0 && (letters.a + letters.b + letters.c + letters.d > 0)) {
howWell = "well";
} else {
howWell = "okay";
}
output += howWell;
var str = " with ";
Object.keys(letters).forEach(function(key, index) {
if (letters[key] == 0)
delete letters[key];
})
Object.keys(letters).forEach(function(key, index) {
var numOfGradeLetter = letters[key];
if (numOfGradeLetter > 0) {
var addS = numOfGradeLetter > 1 ? "'s " : " ";
var and = "";
if (index == Object.keys(letters).length - 1 && index != 0)
and = "and ";
str += and + numOfGradeLetter + key + addS + '<break time="5ms"/>'
console.log(numOfGradeLetter + key + addS)
}
});
output += str;
//TODO post issue for createOutputSpeechObject() on Alexia
console.log(output)
if (Object.keys(letters).length == 0) {
done({
text: "You don't seem to have any grades yet.. I'm sure you will do great though.",
ssml: false,
end: true
});
} else {
done({
text: wrapSSML(output),
ssml: true,
end: true
});
}
});
}).catch(ERRORS.PresentableError, function(err) {
done({
text: err.message,
end: true
});
}).catch(ERRORS.HandledError, function(err) {
//Handled error
console.log("I dont have to worry");
}).catch(function(err) {
console.log(err)
done({
text: "Sorry, there was an unexpected server error, please try again later",
end: true
});
});
});
var getUpcommingEventsIntent = app.intent('GetUpcommingEventsIntent', 'read original request data async', (slots, attrs, data, done) => {
return getUserfromIntent(slots, attrs, data, done).then(user => {
return user.getUpcommingEvents();
}).then(events => {
console.log("events")
if (events) {
var event = {};
var upcomming = "You have " + events.length + " upcoming events<break time='2ms'/>";
console.log(upcomming)
return events.forEach(function(event) {
upcomming += event.title + "<break time='4ms'/>";
});
done({
text: wrapSSML(upcomming),
ssml: true,
end: true
});
} else {
var upcomming = "You have no upcoming events<break time='2ms'/>";
done({
text: wrapSSML(upcomming),
ssml: true,
end: true
});
}
}).catch(ERRORS.PresentableError, function(err) {
done({
text: err.message,
end: true
});
}).catch(ERRORS.HandledError, function(err) {
//Handled error
console.log("I dont have to worry");
}).catch(function(err) {
done({
text: "Sorry, there was an unexpected server error, please try again later",
end: true
});
});
});
function doGetLastAssignmentsIntent(slots, attrs, data, done) {
var course = slots.ClassName || "";
var coursenumberOfAssignments = slots.numberOfAssignments || 3
var accessToken = data.session.user.accessToken || 0;
function doGetLastGraded(courseOrUser, coursenumberOfAssignments, done) {
var stringResult = "Your last " + coursenumberOfAssignments + " graded assignments ";
if (courseOrUser instanceof User) {
stringResult += "overall";
} else {
stringResult += "in " + (courseOrUser.meta.title || courseOrUser.nickname || courseOrUser.name);
}
stringResult += " are\n";
return courseOrUser.getLastGraded(coursenumberOfAssignments).then(assignmentArr => {
assignmentArr.forEach(assignment => {
var strGrade = "";
var grade = assignment.getGrade()[0];
if (typeof grade !== 'undefined' && grade !== null) {
strGrade = grade + " percent."
} else {
strGrade = "not listed."
}
stringResult += (assignment.name) + " is " + strGrade + " <break time='2ms'/>\n";
});
done({
text: wrapSSML(stringResult),
ssml: true,
end: true
});
return;
});
}
return getUserfromIntent(slots, attrs, data, done).then(user => {
console.log(user)
var choice = slots.number || 0;
if (attrs.previousIntent === "GetNumberIntent") {
return user.getCourses().then(courses => {
return doGetLastGraded(courses[choice - 1], coursenumberOfAssignments, done);
});
} else {
if (course === "" || typeof course === 'undefined') {
done({
text: "Please provide a course name",
end: true
});
return;
} else {
return user.findCourse(course).then(y => {
if (typeof y !== 'undefined') {
if (!Array.isArray(y)) {
return doGetLastGraded(y, coursenumberOfAssignments, done);
} else {
//Todo theres hope here for the user to find what they want, just out of time
handleNoMatch(user, slots, data, done);
}
} else {
handleNoMatch(user, slots, data, done);
}
});
}
}
}).catch(ERRORS.PresentableError, function(err) {
done({
text: err.message,
end: true
});
}).catch(ERRORS.HandledError, function(err) {
//Handled error
console.log("I dont have to worry");
}).catch(function(err) {
done({
text: "Sorry, there was an unexpected server error, please try again later",
end: true
});
});
}
var getLastAssignmentsIntent = app.intent('GetLastAssignmentsIntent', 'read original request data async', doGetLastAssignmentsIntent);
function doGetGradeIntent(slots, attrs, data, done) {
var course = slots.ClassName || "";
var accessToken = data.session.user.accessToken || 0;
function doGetGrade(course, done) {
// console.log(course)
var strGrade = "";
var grade = course.getGrade();
if (typeof grade !== 'undefined' && grade !== null) {
strGrade = grade + " percent."
} else {
strGrade = "not listed."
}
var stringResult = "Your current grade in " + (course.meta.title || course.nickname) + " is " + strGrade;
console.log(stringResult);
done({
text: stringResult,
end: true
});
return;
}
return getUserfromIntent(slots, attrs, data, done).then(user => {
console.log(user)
var choice = slots.number || 0;
if (attrs.previousIntent === "GetNumberIntent") {
return user.getCourses().then(courses => {
return doGetGrade(courses[choice - 1], done);
});
} else {
if (course === "" || typeof course === 'undefined') {
return user.getCourses().then(courses => {
var stringResult = "Your current grades are ";
courses.forEach(course => {
var strGrade = "";
var grade = course.getGrade();
if (grade !== 'undefined' && grade !== null) {
strGrade = grade + " percent."
} else {
strGrade = "not listed."
}
stringResult += (course.meta.title || course.nickname || course.name) + '<break time="2ms"/>' + strGrade + '<break time="2ms"/>';
});
done({
text: wrapSSML(stringResult),
ssml: true,
end: true
});
});
} else {
return user.findCourse(course).then(y => {
if (typeof y !== 'undefined') {
if (!Array.isArray(y)) {
return doGetGrade(y, done);
} else {
//Todo theres hope here for the user to find what they want, just out of time
handleNoMatch(user, slots, data, done);
}
} else {
handleNoMatch(user, slots, data, done);
}
});
}
}
}).catch(ERRORS.PresentableError, function(err) {
done({
text: err.message,
end: true
});
}).catch(ERRORS.HandledError, function(err) {
//Handled error
console.log("I dont have to worry");
}).catch(function(err) {
done({
text: "Sorry, there was an unexpected server error, please try again later",
end: true
});
});
}
var getGradeIntent = app.intent('GetGradeIntent', 'read original request data async', doGetGradeIntent);
//Allow main intents starting access
const YesIntent = app.builtInIntent('yes', 'read original request data async', (slots, attrs, data, done) => {
console.log("yes start")
if (attrs.action === "MatchCourse") {
done({
text: wrapSSML("Choose a number. <break time='2ms'/>" + attrs.listResult),
ssml: true,
card: {
title: 'Current Courses',
content: attrs.courselist
},
end: false
});
} else {
done({
text: "Okay",
end: true
})
}
});
var handlers = {
"GetGradeIntent": doGetGradeIntent,
"GetLastAssignmentsIntent": doGetLastAssignmentsIntent
}
var NoIntent = app.intent('no', 'read original request data async', (slots, attrs, data, done) => {
// // Clear calendar for date `attrs.date` here
if (attrs.from === "GetGradeIntent") {
done({
text: wrapSSML("Okay."),
ssml: true,
card: {
title: 'Current Courses',
content: attrs.courselist
},
end: true
});
} else {
done({
text: "Okay, Goodbye",
end: true
})
}
});
var GetNumberIntent = app.intent('GetNumberIntent', 'read original request data async', (slots, attrs, data, done) => {
var choice = slots.number || -1;
if (choice >= 1 && choice <= attrs.courseCount + 1) {
console.log("eval true");
//Manually set beacuse were going to forward the intent
attrs.previousIntent = "GetNumberIntent";
attrs.origSlots.number = choice;
handlers[attrs.from](attrs.origSlots, attrs, data, done);
} else {
done({
text: choice + " is not a valid choice, say a number between one and " + attrs.courseCount + ". I have sent a card with valid choices.",
attrs: attrs,
end: false
});
}
});
var HelpIntent = app.intent('help', 'read original request data async', (slots, attrs, data, done) => {
done({
text: wrapSSML('You can ask about your grades <break time="2ms"/> what your current grade in a class is <break time="2ms"/> about your upcoming events ' +
'<break time="2ms"/> and your recent graded assignments for a class. For more help visit canvas skill <break time=".1ms"/>dot <break time=".1ms"/>tk <break time="1ms"/>.'),
ssml: true,
attrs: attrs,
end: false
});
});
app.action({
from: '*',
to: [getHowWellIntent, getLastAssignmentsIntent, getGradeIntent, getUpcommingEventsIntent]
});
app.action({
from: [getGradeIntent, getLastAssignmentsIntent],
to: ["AMAZON.YesIntent", "AMAZON.NoIntent"]
});
app.action({
from: "AMAZON.YesIntent",
to: ["GetNumberIntent"]
});
//Allow looping over determining the correct course
app.action({
from: 'GetNumberIntent',
to: "GetNumberIntent"
})
app.action({
from: '*',
to: ["AMAZON.StopIntent", "AMAZON.CancelIntent", HelpIntent]
})
// exports.handler = (event, context, callback) => {
// app.handle(event, data => {
// callback(null, data);
// });
// };
// Testing over HTTPS
module.exports = app;