-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1783 lines (1582 loc) · 102 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
#!/usr/bin/env node
const prompts = require('prompts'),
validator = require('validator'),
ora = require('ora'),
chalk = require('chalk'),
fs = require('fs'),
path = require('path'),
puppeteer = require('puppeteer'),
format = require('string-format'),
links = require('./templates/links'),
pLimit = require('p-limit'),
netLimit = pLimit(1),
archiver = require('archiver'),
os = require('os'),
terminalLink = require('terminal-link');
// set DEBUG to true to see console.info('[ainfo] ') messages in the terminal
// Note, that you can also debug by putting pupateer in non-headless mode and opening the console in the browser while it runs
const DEBUG = true;
let crypto, browser;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is required but is disabled!');
process.exit(0);
}
// load settings
let sessionData = require('./settings.js'),
arr_objs_classes = [];
let dateObjRN = new Date(), monthRN = dateObjRN.getMonth() + 1, dayRN = dateObjRN.getDate(),
hourRN = dateObjRN.getHours(), minuteRN = dateObjRN.getMinutes(),
yearRN = dateObjRN.getFullYear(),
dateStrRN = yearRN + "/" + monthRN + "/" + dayRN + "/" + (hourRN <= 12 ? hourRN + "AM" : hourRN - 12 + "PM") + "/" + minuteRN;
/*
_ _ _ _ _ _ _ _ _ ____ _ _ __ __ __
_ __ _ _| |__ | (_) ___ ___| |_ __ _| |_(_) ___ __ _____ (_) __| | _ __ ___ __ _(_)_ __ / / _\ |_ _ __(_)_ __ __ _| _|_ | __ _ _ __ __ _ __\ \
| '_ \| | | | '_ \| | |/ __| / __| __/ _` | __| |/ __| \ \ / / _ \| |/ _` | | '_ ` _ \ / _` | | '_ \ | |\ \| __| '__| | '_ \ / _` | | | | / _` | '__/ _` / __| |
| |_) | |_| | |_) | | | (__ \__ \ || (_| | |_| | (__ \ V / (_) | | (_| | | | | | | | (_| | | | | | | |_\ \ |_| | | | | | | (_| | | | | | (_| | | | (_| \__ \ |
| .__/ \__,_|_.__/|_|_|\___| |___/\__\__,_|\__|_|\___| \_/ \___/|_|\__,_| |_| |_| |_|\__,_|_|_| |_| | |\__/\__|_| |_|_| |_|\__, | | | | \__,_|_| \__, |___/ |
|_| \_\ |___/|__|__| |___/ /_/
*/
(async () => {
await startPuppeteer();
if (savedCredsExist()) {
await loadCredentialsPrompts();
await testCredentials()
} else {
await setCredentialsPrompts();
await testCredentials();
await promptSavePwdOptions();
await continueConfirmation().catch((quit) => doneSetupExit);
}
if (savedSectionsIDExist()) {
await loadSavedSectionIDs();
} else {
await parseSectionIDs();
}
await promptAssignmentOptions();
await assembleClassQueues();
await promptSaveDataOptions();
await parseWriteEachClassObj();
await stopPuppeteer();
printCompletionMessage();
/*
_ _ ______ _ _____ ______ _____ _____
| | | | ____| | | __ \| ____| __ \ / ____|
| |__| | |__ | | | |__) | |__ | |__) | (___
| __ | __| | | | ___/| __| | _ / \___ \
| | | | |____| |____| | | |____| | \ \ ____) |
|_| |_|______|______|_| |______|_| \_\_____/
*/
async function startPuppeteer() {
browser = await puppeteer.launch({
headless: false //remove for production
});
}
/* <!--- CodeHS Credentials Functions ---> */
function savedCredsExist() {
try {
return fs.existsSync(path.join(__dirname, 'secrets', 'creds.json')) ? require('./secrets/creds.json').method != null && require('./secrets/creds.json').email : false;
} catch (err) {
return false;
}
}
async function loadCredentialsPrompts() {
let resizedIV = Buffer.allocUnsafe(16),
iv = crypto
.createHash("sha256")
.update('doc says this could be null... it can\'t')
.digest();
iv.copy(resizedIV);
let credJSON = require('./secrets/creds.json');
let {method} = credJSON;
sessionData.email = credJSON.email;
if (method === 'none') {
sessionData.password = credJSON.password || ' '
} else if (method === 'pwd' || method === 'pin') {
function cValidator(val) {
if (method === 'pwd') {
return validator.isAlphanumeric(val + '');
} else if (method === 'pin') {
return validator.matches(val + '', /\b\d{4}\b/);
} else {
return false;
}
}
const response = await prompts({
type: 'password',
name: 'pwd',
message: `Enter your ${method === 'pwd' ? 'password' : 'pin'}`,
validate: val => cValidator(val) ? true : `That could not be your ${method === 'pwd' ? 'password' : 'pin'}`
});
let {pwd} = response;
let key = crypto.createHash('md5').update(pwd + '').digest();
let decrypted, decryptCipher;
try {
decryptCipher = crypto.createDecipheriv('aes-128-cbc', key, resizedIV);
decrypted = decryptCipher.update(Buffer.from(credJSON.password, 'hex'));
decrypted = Buffer.concat([decrypted, decryptCipher.final()]);
} catch (incorrect) {
console.log(`${chalk.red(`Your ${method === 'pwd' ? 'password' : 'pin'} was incorrect... exiting...`)}`);
process.exit();
}
sessionData.password = decrypted.toString();
} else {
console.info('Unknown save method, quitting...');
process.exit();
}
}
async function testCredentials() {
return new Promise(async (resolve5, reject4) => {
const spinner = ora({text: `${chalk.bold('Testing credentials...')}`}).start();
const page = await browser.newPage();
await loginCodeHS(page).then(async suc => {
if (!fs.existsSync(path.join(__dirname, 'secrets', 'teacher.json'))) {
await writeFileAsync(path.join(__dirname, 'secrets', 'teacher.json'), JSON.stringify({teacherID: suc}));
}
spinner.succeed(`${chalk.bold('Login credentials valid')}`);
}).catch(err => {
spinner.fail(`${chalk.red('Login credentials invalid...')}`);
codeHSCredInvalidExit();
});
resolve5(1);
})
}
function codeHSCredInvalidExit() {
console.info('Perhaps you changed your credentials on codehs.com?');
process.exit();
}
async function setCredentialsPrompts() {
sessionData = await prompts([
{
type: 'text',
name: 'email',
message: 'What is your CodeHS email?',
validate: value => validator.isEmail(value + '') ? true : 'Enter a valid email'
},
{
type: 'password',
name: 'password',
message: 'What is your CodeHS password?',
validate: value => value.length > 0
}
], {onCancel: onPromptsCancel}
);
}
async function promptSavePwdOptions() {
let resizedIV = Buffer.allocUnsafe(16),
iv = crypto
.createHash("sha256")
.update('doc says this could be null... it can\'t')
.digest();
iv.copy(resizedIV);
let saveData = await prompts([
{
type: 'confirm',
name: 'save',
message: 'Save credentials?'
},
{
type: prev => prev ? 'select' : null,
name: 'method',
message: 'Security level:',
choices: [
{
title: 'Pin', description: '4 Digits Code', value: 'pin',
},
{
title: 'Password', description: 'Alphanumerical (1+)', value: 'pwd',
},
{
title: 'None', description: 'No Security', value: 'none',
},
{
title: 'Cancel', description: 'Nvm, Don\'t Save!', value: 'cancel'
}
],
hint: '- up/down to navigate. return to submit',
initial: 0
},
{
type: prev => prev === 'pin' ? 'password' : null,
name: 'pin',
message: 'Enter a 4-digit pin',
validate: val => validator.matches(val + '', /\b\d{4}\b/)
},
{
type: prev => prev === 'pwd' ? 'password' : null,
name: 'pwd',
message: 'Enter a password',
validate: val => validator.isAlphanumeric(val + '')
}
], {onCancel: onPromptsCancel});
let {save} = saveData;
if (save) {
let {method} = saveData;
let {email} = sessionData;
let {password} = sessionData;
if (method === 'none') {
// no security or hash, move on !
} else if (method === 'pin') {
let {pin} = saveData;
let key = crypto.createHash('md5').update(pin + '').digest();
await prompts({
type: 'password',
name: 'tmp_confirm',
message: 'Confirm your pin',
validate: val => val === pin ? true : 'That\'s not your pin!'
}, {onCancel: onPromptsCancel});
let cryptoKey = crypto.createCipheriv('aes-128-cbc', key, resizedIV);
password = cryptoKey.update(password, 'utf8', 'hex');
password += cryptoKey.final('hex');
} else if (method === 'pwd') {
let {pwd} = saveData;
let key = crypto.createHash('md5').update(pwd + '').digest();
await prompts({
type: 'password',
name: 'tmp_confirm',
message: 'Confirm your password',
validate: val => val === pwd ? true : 'That\'s not your password!'
}, {onCancel: onPromptsCancel});
let cryptoKey = crypto.createCipheriv('aes-128-cbc', key, resizedIV);
password = cryptoKey.update(password, 'utf8', 'hex');
password += cryptoKey.final('hex');
} else {
// cancel
process.exit();
}
//finally, write finalized email/password to file
await writeFileAsync(path.join(__dirname, 'secrets', 'creds.json'), JSON.stringify({
method: method,
email: email,
password: password
}))
}
}
async function continueConfirmation() {
return new Promise(async (resolve, reject) => {
const response = await prompts({
type: 'confirm',
name: 'tmp_confirm',
message: 'Continue to generating class assignments data?'
});
let {tmp_confirm} = response;
if (tmp_confirm) {
resolve(1);
} else {
reject(0);
}
})
}
/* <!--- Assignments Table Cache Functions ---> */
function savedSectionsIDExist() {
try {
return fs.existsSync(path.join(__dirname, 'secrets', 'sections.json'));
} catch (err) {
return false;
}
}
async function loadSavedSectionIDs() {
sessionData.sections = require('./secrets/sections.json');
}
async function parseSectionIDs() {
const spinner = ora({text: `${chalk.bold('Parsing section IDs...')}`}).start();
const pg = await browser.newPage();
let teacherID;
if (fs.existsSync(path.join(__dirname, 'secrets', 'teacher.json')) && require('./secrets/teacher.json') && require('./secrets/teacher.json').teacherID) {
teacherID = require('./secrets/teacher.json').teacherID;
} else {
// just in case the login step was somehow skipped??
// or corrupted data ig
const response = await prompts({
type: 'number',
name: 'teacherID',
message: 'Enter your teacherID (found in url after logging in)'
});
teacherID = response.teacherID;
}
await pg.goto(format(links.teachersPage, teacherID), {waitUntil: 'networkidle2'});
// make this part optional (could be manual) b/c not everyone has same naming formats
let sections = await pg.evaluate(() => {
let sectionList = document.getElementsByClassName('js-sections-menu dropdown-menu sections-dropdown')[0].children;
let courses = {};
let sections = {};
let classesObj = {};
for (let i = 1; i < sectionList.length; i++) {
let listItem = sectionList[i];
let sectionLink = listItem.getElementsByClassName('compact teacher-section-link')[0];
let sectionName = sectionLink.getElementsByClassName('left')[0].innerHTML;
let sectionPeriod = sectionName.substring(1, sectionName.indexOf(' '));
let sectionHrefSplit = sectionLink.href.toString().split('/');
let sectionId = sectionHrefSplit[sectionHrefSplit.length - 1];
let hrefQuestion = sectionId.indexOf('?');
if (hrefQuestion != -1) sectionId = sectionId.substring(0, hrefQuestion);
let sectionInfo = document.getElementsByClassName('class-list-item wrap class_' + sectionId)[0];
let courseId = sectionInfo.getAttribute('data-teacher-course-id').toString();
let coursesDropdown = document.getElementsByClassName('js-courses-menu dropdown-menu sections-dropdown')[0];
let courseName;
for (let c = 1; c < coursesDropdown.children.length; c++) {
if (coursesDropdown.children[c].getAttribute('href').toString().indexOf(courseId) != -1) {
courseName = coursesDropdown.children[c].getElementsByClassName('left my-course-option-title')[0].innerHTML;
break;
}
}
if (!courses[courseName]) {
courses[courseName] = {'id': courseId, 'classes': {}};
}
courses[courseName]['classes'][sectionPeriod + ''] = sectionId;
}
return courses;
});
// console.info(sections);
await writeFileAsync(path.join(__dirname, 'secrets', 'sections.json'), JSON.stringify(sections));
sessionData.sections = sections;
await pg.close();
spinner.succeed(`${chalk.bold('Section IDs saved in ./secrets/sections.json')}`);
}
/* <!--- CodeHS Parse Configuration Functions ---> */
async function promptAssignmentOptions() {
return new Promise(async (resolve, reject) => {
const response = await prompts([
{
type: 'text',
name: 'assignment_name',
message: 'Enter the name of the assignment',
inital: 'untitled',
validate: val => val.length > 0 ? true : 'Name cannot be blank!'
},
{
type: 'list',
name: 'arr_assignments',
message: `Enter exercise names (separated by ${chalk.bold(',')})`,
initial: '',
separator: ',',
validate: val => val.toString().length > 0 ? true : 'Enter at least one exercise!'
},
{
type: 'date',
name: 'date_dueDate',
message: 'When is this assignment due?',
initial: new Date(yearRN, monthRN - 1, dayRN, 23, 59),
mask: 'YYYY-MM-DD HH:mm'
},
{
type: 'multiselect',
name: 'arr_classes',
message: 'Pick which classes to grade',
choices: buildOptions(),
min: 1,
hint: '- Space to select. Return to submit',
instructions: false
}
]
);
sessionData['date_dueDate'] = response['date_dueDate'];
sessionData['arr_assignments'] = response['arr_assignments'];
sessionData['arr_classes'] = response['arr_classes'];
sessionData['assignment_name'] = response['assignment_name'];
resolve('i');
function buildOptions() {
let options = [];
let {sections} = sessionData;
for (let key in sections) {
if (sections.hasOwnProperty(key)) {
options.push({
title: `All ${key} Classes`, value: `${key}|0`
})
}
}
//run for-loop again to preserve ordering
for (let key in sections) {
if (sections.hasOwnProperty(key)) {
//'...' deconstructs the mapped array into the options array
options.push(...Object.keys(sections[key].classes).map(pNum => {
return {
title: `P${pNum} ${key}`, value: `${key}|${pNum}`
}
}));
}
}
return options;
}
});
}
async function assembleClassQueues() {
return new Promise((resolve, reject) => {
const spinner = ora({text: `${chalk.bold('Assembling parsing queue')}`}).start();
let {arr_classes} = sessionData;
let {sections} = sessionData;
let arr_completed = [];
arr_classes.forEach(obj => {
let teacherName = obj.split('|')[0];
let classIdentifier = obj.split('|')[1];
if (classIdentifier === '0') {
arr_completed.push(teacherName);
for (let classNum in sections[teacherName].classes) {
if (!sections[teacherName].classes.hasOwnProperty(classNum)) continue;
let obj_todo = {
teacherName: teacherName,
url: format(links.homePage, sections[teacherName].id, sections[teacherName].classes[classNum]),
classNum: classNum,
sectionId: sections[teacherName].id,
classId: sections[teacherName].classes[classNum],
students: []
};
arr_objs_classes.push(obj_todo);
}
} else {
if (!arr_completed.includes(teacherName)) {
let obj_todo = {
teacherName: teacherName,
url: format(links.homePage, sections[teacherName].id, sections[teacherName].classes[classIdentifier]),
classNum: classIdentifier,
sectionId: sections[teacherName].id,
classId: sections[teacherName].classes[classIdentifier],
students: []
};
arr_objs_classes.push(obj_todo);
}
}
});
spinner.succeed(`${chalk.bold('Parse queue assembled')}`);
resolve(1);
})
}
/* <!--- File Writing Configuration Functions ---> */
async function promptSaveDataOptions() {
const response = await prompts({
type: 'multiselect',
name: 'chosenOptions',
message: 'Download what?',
choices: [
{title: 'Student\'s score', value: 'score', selected: true},
{title: 'Student\'s code', value: 'code', selected: true},
{title: 'Student\'s coding history', value: 'history', selected: false}
],
min: 1,
hint: '- Space to select. Return to submit',
instructions: false
});
sessionData['downloadOptions'] = response.chosenOptions;
}
async function parseWriteEachClassObj() {
await Promise.all(arr_objs_classes.map((obj) => {
return netLimit(() => combinedSteps(obj))
}));
}
async function combinedSteps(classObj) {
return new Promise(async (a, b) => {
const spinner = ora({text: `${chalk.bold(`[${classObj.teacherName + '_P' + classObj.classNum}] Preparing...`)}`}).start();
await parseClassPages(classObj, arr_objs_classes, browser, spinner);
spinner.text = `${chalk.bold(`[${classObj.teacherName + '_P' + classObj.classNum}] Writing files...`)}`;
await writeClass(classObj);
spinner.succeed(chalk.bold(path.join(sessionData.outDirectory, '----temp----', classObj.teacherName + '_P' + classObj.classNum).replace('----temp----', '~')));
a(Date.now());
})
}
async function parseClassPages(obj, arr_objs_classes, browser, spinner) {
return new Promise(async (resolve, reject) => {
// TOP OF FUNCTION
let {date_dueDate, arr_assignments, downloadOptions} = sessionData;
const page = await browser.newPage();
const headlessUserAgent = await page.evaluate(() => navigator.userAgent);
const chromeUserAgent = headlessUserAgent.replace('HeadlessChrome', 'Chrome');
await page.setUserAgent(chromeUserAgent);
await page.setExtraHTTPHeaders({
'accept-language': 'en-US,en;q=0.8'
});
let cached_modulePath = path.join(__dirname, 'cached', obj.sectionId + '', obj.classId + '');
let url_sectionAllModule = format('https://codehs.com/lms/assignments/{0}/section/{1}/progress/module/0', obj.sectionId, obj.classId);
async function pathExists(path) {
return new Promise((resolve1, reject1) => {
fs.access(path, fs.F_OK, (err) =>{
if (err){
reject1(false);
}
resolve1(true);
});
});
}
let boolean_useCache = true;
let boolean_buildCache = false;
let {rebuildCache: forceCache} = sessionData;
if (typeof forceCache !== "boolean") {
errorExit('settings.js \'rebuildCache\' invalid, not a boolean');
}
await pathExists(path.join(cached_modulePath, 'index.html')).then(success => {
//use cache
if (forceCache) {
boolean_useCache = false;
boolean_buildCache = true;
} else {
url_sectionAllModule = `file:${path.join(cached_modulePath, 'index.html')}`;
}
}).catch(err => {
boolean_useCache = false;
boolean_buildCache = true;
});
let pageGoOptions = {
waitUntil: 'networkidle2',
timeout: 0
};
console.info('boolean use cache', boolean_useCache);
console.info('boolean build cache', boolean_buildCache);
if(!boolean_useCache && boolean_buildCache){
spinner.text = chalk.bold(`[${obj.teacherName + '_P' + obj.classNum}] Preparing... (First run may take up to 5 minutes)`);
}else{
spinner.text = chalk.bold(`[${obj.teacherName + '_P' + obj.classNum}] Preparing... (Loading all assignments and IDs from cache)`);
}
await page.goto(url_sectionAllModule, pageGoOptions).catch(errObj => {
if (errObj.name !== 'TimeoutError') {
console.info(os.EOL + chalk.bold.red('Unknown error: ', errObj));
console.info(chalk.bold.yellow('Please open an issue in this ' + terminalLink('repo', 'https://github.com/e-zhang09/CodeHS-HWCrawler')));
process.exit();
}
});
await page.waitForSelector('#activity-progress-table', {visible: true, timeout: 0});
if (boolean_buildCache) {
if (forceCache) {
spinner.text = chalk.bold(`[${obj.teacherName + '_P' + obj.classNum}] Rebuilding Cache... (May take up to 5 minutes)`);
}
let bodyHTML = await page.evaluate(() => document.body.innerHTML);
await writeFileAsync(path.join(cached_modulePath, 'index.html'), bodyHTML);
}
// duplicate assignments
let arr_assignmentsCopy = arr_assignments.slice();
page.on('console', consoleObj => {
// if DEBUG is true, it will print console messages containing '[ainfo]'
if (DEBUG && consoleObj.text().includes('[ainfo]')) {
console.log(consoleObj.text().replace('[ainfo]', ''))
}
if (consoleObj.text().includes('[awarning]')) {
console.log(chalk.yellow.bold(consoleObj.text().replace('[awarning]', '')))
}
if (consoleObj.text().includes('[aerror]')) {
console.log(chalk.red.bold(consoleObj.text().replace('[aerror]', '')));
process.exit();
}
});
let [arr_assignmentIDs, arr_obj_students] = await page.evaluate(async (arr_assignmentsCopy) => {
function sleep(ms) {
return new Promise(resolution => setTimeout(resolution, ms));
}
// console.info('[ainfo] arr_assignmentsCopy', JSON.stringify(arr_assignmentsCopy, null, 4));
let originalLength = arr_assignmentsCopy.length;
let arr_IDs = [];
let children_possibleNodes = document.getElementsByClassName('activity-item');
for (let i = 0; i < children_possibleNodes.length; i++) {
if (children_possibleNodes[i].getAttribute('data-original-title')) {
let str = children_possibleNodes[i].getAttribute('data-original-title').toLowerCase();
str = str.slice(0, str.lastIndexOf(":")); //remove the status that follows the problem name
for (let j = 0; j < arr_assignmentsCopy.length; j++) {
if (str.toLowerCase().trim() === arr_assignmentsCopy[j].toLowerCase()) {
//assignments are already trimmed from prompts
//got one assignment
arr_IDs.push({
name: arr_assignmentsCopy[j],
url: children_possibleNodes[i].children[0].href
});
//remove 'assignment' name from to-search list
arr_assignmentsCopy.splice(j, 1);
break;
}
}
if (arr_assignmentsCopy.length === 0) {
//got all assignments needed
break;
}
}
}
// console.info('[ainfo] arr_assignmentsCopy', JSON.stringify(arr_assignmentsCopy, null, 4));
if (arr_assignmentsCopy.length === originalLength) {
console.log('[aerror]', 'None of these assignments were found: ' + JSON.stringify(arr_assignmentsCopy))
} else if (arr_assignmentsCopy.length !== 0) {
console.log('[aerror]', 'The following assignments were not found: ' + JSON.stringify(arr_assignmentsCopy));
}
let arr_obj_students = [];
let table = document.getElementById('activity-progress-table').children[0].getElementsByClassName('student-row');
console.info('numStudents', table.length);
for (let i = 0; i < table.length; i++) {
let student_firstName = table[i].getAttribute('data-first-name').toString();
let student_lastName = table[i].getAttribute('data-last-name').toString();
let obj_student = {
firstName: student_firstName,
lastName: student_lastName,
assignments: {}
};
let candidate_assignments = table[i].getElementsByClassName('progress-circle');
// console.info('num student-link candidates', candidate_assignments.length);
for (let j = 0; j < candidate_assignments.length; j++) {
let refStr = candidate_assignments[j].href;
let refStrComponents = refStr.split('/');
if (refStr && refStrComponents.length >= 4) {
refStrComponents.slice().some(str => {
if (str.toString().trim().length >= 3) {
if (!str.match(/[a-zA-Z:]/g)) {
//to parse it even if from cache
obj_student.id = str;
// console.info('got student id', str);
return '0';
}
}
});
break;
}
}
arr_obj_students.push(obj_student);
}
return [arr_IDs, arr_obj_students];
}, arr_assignmentsCopy);
let rosterPage;
if (boolean_useCache) {
rosterPage = await browser.newPage();
await rosterPage.goto('https://codehs.com');
} else {
rosterPage = page;
}
spinner.text = chalk.bold(`[${obj.teacherName + '_P' + obj.classNum}] Downloading Student Emails...`);
let obj_studentEmail = await rosterPage.evaluate(async (TEMPLATE_ROSTER_URL, obj) => {
//add String.format utility
if (!String.format) {
String.format = function (format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
let obj_studentEmail = {};
//get student emails
//TODO: Could cache but not necessary because response loads fast
function fetchStudentEmails() {
return new Promise((resolve1, reject1) => {
let emailRequest = new XMLHttpRequest();
emailRequest.onload = function () {
resolve1(this.responseXML);
};
emailRequest.open("GET", String.format(TEMPLATE_ROSTER_URL, obj.classId));
emailRequest.responseType = "document";
emailRequest.send();
});
}
let rosterDocument = await fetchStudentEmails();
let tmp_table = rosterDocument.getElementById('classset-progress');
let rosterTable = tmp_table.getElementsByTagName('table')[0];
let rosterRows = rosterTable.getElementsByTagName('tr');
for (let i = 0; i < rosterRows.length; i++) {
let row = rosterRows[i];
if (row.getElementsByTagName('a').length === 0) {
continue;
}
let studentName = row.getElementsByTagName('a')[0].innerText.trim();
let studentEmail = 'none';
let tds = row.getElementsByTagName('td');
for (let j = 0; j < tds.length; j++) {
if (tds[j].innerText.includes('@student')) {
studentEmail = tds[j].innerText;
}
}
obj_studentEmail[studentName] = studentEmail;
}
return obj_studentEmail;
}, links.rosterPage, obj);
if (boolean_useCache) rosterPage.close();
let problemIdMap = {};
for (let i = 0; i < arr_assignmentIDs.length; i++) {
let name = arr_assignmentIDs[i].name;
let temp_split = arr_assignmentIDs[i].url.substr(8).split('/');
arr_assignmentIDs[i] = temp_split[6];
problemIdMap[arr_assignmentIDs[i]] = name;
}
//console.info('[ainfo] arr_assignmentIDs = ' + JSON.stringify(arr_assignmentIDs));
console.info('\n[ainfo] problemIdMap = ' + JSON.stringify(problemIdMap, null, 4) + "\n");
//need to move to codehs.com for cors
if (boolean_useCache) await page.goto('https://www.codehs.com');
//update spinner
spinner.text = chalk.bold(`[${obj.teacherName + '_P' + obj.classNum}] Calculating Student Grades...`);
//attach bottleneckJS to limit network calls
await pathExists(path.join(__dirname, 'node_modules', 'bottleneck', 'es5.js')).then(async suc => {
await page.addScriptTag({path: path.join(__dirname, 'node_modules', 'bottleneck', 'es5.js')});
}).catch(async err => {
await pathExists(path.join(__dirname, '..', '..', 'node_modules', 'bottleneck', 'es5.js')).then(async suc => {
await page.addScriptTag({path: path.join(__dirname, '..', '..', 'node_modules', 'bottleneck', 'es5.js')});
}).catch(err => {
console.info(chalk.bold.red('Could not find the \'bottleneck\' module'));
process.exit();
})
});
//calculate student grades
obj.students = await page.evaluate(
async (arr_assignmentIDs, obj, TEMPLATE_STUDENT_URL, date_dueDate, arr_obj_students, downloadCode, obj_studentEmail) => {
//import bottleneck from script tag
let Bottleneck = window.Bottleneck;
const limiter = new Bottleneck({
maxConcurrent: 10,
minTime: 200
});
function getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
return '';
}
//add String.format utility
if (!String.format) {
String.format = function (format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// limits to one student for testing
// arr_obj_students = arr_obj_students.splice(arr_obj_students.length - 1); // Delete this for prod
// limits to first student
//arr_obj_students = [arr_obj_students[0]]; // Delete this for prod
// Limits to a particular student
// for (let i = 0; i < arr_obj_students.length; i++) {
// if (arr_obj_students[i].firstName === "Iker") {
// arr_obj_students = [arr_obj_students[i]];
// break;
// }
// }
// fetch date from students' page
await Promise.all(arr_obj_students.map(async (studentObject) => {
await limiter.schedule(() => {
const allTasks = arr_assignmentIDs.map(async (key) => {
return new Promise((res, rej) => {
let xhr = new XMLHttpRequest();
xhr.onload = async function () {
let document = this.responseXML;
let contextDescription = " [Context] problemId " + key + " for " + studentObject.firstName + " " + studentObject.lastName;
//console.info('[ainfo] doc: ' + new XMLSerializer().serializeToString(document));
//get problem name
//console.info("[ainfo] executing " + contextDescription);
if (document === undefined || document === null) {
console.error("[aerror] student problem page is not valid" + contextDescription);
} else if (document.title === undefined) {
console.error("[aerror] student problem page has no title: " + document.title + contextDescription);
}
let problemName = document.title.split('|')[0].trim();
//console.info('[ainfo] problemName = ' + problemName + contextDescription);
let startedText;
let firstTryTime;
let firstTryDate;
let date_startDate;
let originalStartedText = startedText;
let selectionField;
let dataStudentAssignmentId;
let dataId;
let dataCodeUserId;
let dataItemId;
try {
let startedTimeElement = document.querySelector("#started-time");
let startMsg = startedTimeElement.querySelector('.msg-content');
let startP = startMsg.querySelector("p");
startedText = startP.innerText;
//console.info('[ainfo] startP startedText = ' + startedText);
selectionField = document.getElementById("assignment-submission-select");
let resetElement = document.getElementsByClassName("js-assignment-reset")[0];
dataStudentAssignmentId = resetElement.getAttribute("data-student_assignment_id");
dataId = resetElement.getAttribute("data-uid");
dataCodeUserId = resetElement.getAttribute("data-uid");
dataItemId = resetElement.getAttribute("data-item_id");
//console.info("[ainfo] dataStudentAssignmentId = " + dataStudentAssignmentId);
//console.info("[ainfo] dataId = " + dataId + " dataCodeUserId = " + dataCodeUserId + " dataStudentAssignmentId = " + dataStudentAssignmentId + " dataItemId = " + dataItemId);
} catch (err) {
//console.info('[ainfo] not a Karel Problem: ' + err.message);
if (typeof document.querySelector !== "function") {
console.error("[aerror] document.querySelector is not a function!" + contextDescription);
}
let parent = document.querySelector('#teacher-revision-banner');
if (!parent) {
console.error("[aerror] teacher-revision-banner does not exist!" + contextDescription);
}
let children = parent.querySelectorAll('span');
if (!children) {
console.error("[aerror] teacher-revision-banner has no span children!" + contextDescription);
} else if (children.length < 2) {
console.error("[aerror] teacher-revision-banner does not have at least 2 children!" + contextDescription);
}
let span = children[1];
dataId = span.getAttribute('data-id');
if (dataId === undefined || dataId === null) {
console.error("[aerror] span does not have a 'data-id' attribute!" + contextDescription);
}
dataCodeUserId = span.getAttribute('data-code-user-id');
if (dataCodeUserId === undefined || dataCodeUserId === null) {
console.error("[aerror] span does not have a 'data-code-user-id' attribute!" + contextDescription);
}
dataStudentAssignmentId = span.getAttribute('data-student-assignment-id');
if (dataStudentAssignmentId === undefined || dataStudentAssignmentId === null) {
console.error("[aerror] span does not have a 'data-student-assignment-id' attribute!" + contextDescription);
}
dataItemId = span.getAttribute('data-item-id');
if (dataItemId === undefined || dataItemId === null) {
console.error("[aerror] span does not have a 'data-item-id' attribute!" + contextDescription);
}
//console.info("[ainfo] dataId = " + dataId + " dataCodeUserId = " + dataCodeUserId + " dataStudentAssignmentId = " + dataStudentAssignmentId + " dataItemId = " + dataItemId);
let tabDocs = {};
// assumes docs is an object where the value associated with each key is an html document
// will find the first element with the given id, if it is in one of the docs
// returns the element with the given id or null if none exists.
function getElementByIdInDocs(id, docs) {
for (let key in docs) {
let elem = docs[key].getElementById(id);
if (elem) {
//console.info("[ainfo] found element with id " + id + " in docs[" + key + "]");
return elem;
}
}
return null;
}
//console.info('[ainfo] getting tabs' + contextDescription);
try {
await getTabsAsync().then(tabs => {
function htmlToElement(html) {
if (typeof(html) !== "string") {
console.error("[aerror] html is not a string! - " + html + contextDescription);
}
let doc = document.implementation.createHTMLDocument("Help Tab");
let div = document.createElement('div');
html = html.trim(); // Never return a text node of whitespace as the result
div.innerHTML = html;
doc.body.appendChild(div);
return doc;
}
//console.info('[ainfo] tabs = ' + tabs);
if (tabs === undefined || tabs === null) {
console.error("[aerror] tabs xhr request returned " + tabs + contextDescription);
}
let tabKeys = Object.keys(tabs);
for (let i = 0; i < tabKeys.length; i++) {
tabDocs[tabKeys[i]] = htmlToElement(tabs[tabKeys[i]].text);
}
let startedTimeElement = getElementByIdInDocs("started-time", tabDocs);
if (startedTimeElement === undefined || startedTimeElement === null) {
//console.info("[ainfo] tabDocs does not have an element with id 'started-time'" + contextDescription);
} else if (startedTimeElement.innerText === undefined) {
//console.info("[ainfo] startedTimeElement.innerText is undefined" + contextDescription);
} else {
startedText = startedTimeElement.innerText;
}
//console.info('[ainfo] (1) startedText = ' + startedText);
}).catch(err => {
console.error("[aerror] err from .catch" + err.message + contextDescription);
});
} catch (err) {
console.error("[aerror] catch err from outer try" + err.message + contextDescription);
}