This repository has been archived by the owner on Aug 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
936 lines (787 loc) · 19.9 KB
/
script.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
(() => {
const TextPartType = {
NORMAL: "normal",
BLANK: "blank",
IMAGE: "image"
};
const QuestionType = {
// Angular fill-in-blanks
BLANKS: "fib",
// Angular multiple response question
RESPONSES: "mrq",
// Angular multiple choice question
// Angular true or false
CHOICES: "mcq-tof"
};
class TextPart {
constructor(
type,
text
) {
Object.assign(
this,
{
type,
text
}
);
}
}
class NormalText extends TextPart {
constructor(text) {
super(
TextPartType.NORMAL,
text
);
}
}
class AnswerBlank extends TextPart {
constructor(blankNumber) {
super(
TextPartType.BLANK,
blankNumber
);
}
}
class ImageSource extends TextPart {
constructor(source) {
super(
TextPartType.IMAGE,
source
);
}
}
class Scan {
constructor(
extractorMode,
questionRows,
saveButton
) {
Object.assign(
this,
{
extractorMode,
questionRows,
saveButton
}
);
}
}
class Question {
constructor(
textParts,
actualMarks,
maxMarks,
input,
questionRow,
marksHint
) {
Object.assign(
this,
{
textParts,
actualMarks,
maxMarks,
input,
questionRow,
marksHint
}
);
}
export() {
return {
textParts: this.textParts,
actualMarks: this.actualMarks,
maxMarks: this.maxMarks,
input: this.input.export()
};
}
}
class Input {
constructor(
type,
entries
) {
Object.assign(
this,
{
type,
entries
}
);
}
export() {
return {
type: this.type,
entries: this.entries.map((entry) => entry.export())
};
}
}
class BlanksInput extends Input {
constructor(
textParts,
entries
) {
super(
QuestionType.BLANKS,
entries
);
Object.assign(
this,
{ textParts }
);
}
export() {
return {
...super.export(),
textParts: this.textParts
};
}
}
class ResponsesInput extends Input {
constructor(entries) {
super(
QuestionType.RESPONSES,
entries
);
}
}
class ChoicesInput extends Input {
constructor(entries) {
super(
QuestionType.CHOICES,
entries
);
}
}
class Entry {
constructor(control) {
Object.assign(
this,
{ control }
);
}
export() {
return {};
}
}
class BlanksEntry extends Entry {
constructor(
text,
control
) {
super(control);
Object.assign(
this,
{ text }
);
}
export() {
return {
...super.export(),
text: this.text
};
}
}
class CheckedEntry extends Entry {
constructor(
textParts,
checked,
control
) {
super(control);
Object.assign(
this,
{
textParts,
checked
}
);
}
export() {
return {
...super.export(),
textParts: this.textParts,
checked: this.checked
};
}
}
class ResponsesEntry extends CheckedEntry {}
class ChoicesEntry extends CheckedEntry {}
function l(content, group = false) {
let consoleFunction = (!group) ? console.log : console.group;
consoleFunction(
// Skip instanceof check for type object + class String from new String()s
(typeof content !== "string")
? content
: `>>> ${content}`
);
}
function w(content) {
console.warn(
(typeof content !== "string")
? content
: `[!] ${content}!`
);
}
function e(content) {
console.error(
(typeof content !== "string")
? content
: `ERR ${content}!`
);
}
function d(content) {
console.debug(
(typeof content !== "string")
? content
: `*** ${content}`
);
}
function extractTextParts(node, parentNode = null) {
let whitelistedNodeTypes = [
Node.ELEMENT_NODE,
Node.TEXT_NODE
];
let children = [...node.childNodes].filter(
(child) => whitelistedNodeTypes.includes(child.nodeType)
);
let textParts = [];
if (children.length === 0) {
// Base case
let textPart = extractTextPart(node, parentNode);
if (textPart === null) return [];
textParts.push(textPart);
} else {
// Recurse
children.forEach((child) => {
textParts = [...textParts, ...extractTextParts(child, node)];
});
}
return textParts;
}
function extractTextPart(node, parentNode) {
let text = node.textContent;
if (
parentNode !== null
&& parentNode.matches("em.question-blank")
) {
let regex = /^(?<blankNumber>\d+)(?:\. [\s\S]*)?$/u;
let result = regex.exec(text);
if (result === null) {
e("Unrecognised blank format in answer blank");
return null;
}
return new AnswerBlank(
result.groups.blankNumber
);
}
if (
node.nodeType === Node.ELEMENT_NODE
&& node.matches("img")
) return new ImageSource(node.src);
return new NormalText(text);
}
function compareTextParts(textParts1, textParts2) {
if (textParts1.length !== textParts2.length) return false;
return textParts1.every((textPart1, index) => {
let textPart2 = textParts2[index];
return textPart1.type === textPart2.type
&& textPart1.text === textPart2.text;
});
}
function triggerUpdate(
element,
type = "change"
) {
element.dispatchEvent(
new Event(type)
);
}
function onScan() {
let extractorMode;
let saveButton;
let quizHolder = document.querySelector("quiz-question-results");
if (quizHolder !== null) {
// Results quiz holder
l("📈 Using extractor mode");
extractorMode = true;
saveButton = null;
} else {
quizHolder = document.querySelector("quiz-question-all");
if (quizHolder === null) {
e("No quiz holder found in page");
return null;
}
// Ongoing quiz holder
l("🪄 Using importer mode");
extractorMode = false;
let buttons = quizHolder.querySelectorAll("div.buttons > button");
saveButton = [...buttons].find((button) => button.textContent === "Save For Later") ?? null;
if (saveButton === null) w("No save button found among buttons");
}
let questionRows = quizHolder.querySelectorAll("div.question-view");
if (questionRows.length === 0) {
e("No question rows found in quiz holder");
return null;
}
return new Scan(
extractorMode,
questionRows,
saveButton
);
}
function onProcess(questionRows, extractorMode) {
let successCount = 0;
let questionCount = 0;
let questions = [];
for (let questionRow of questionRows) {
questionCount++;
l(`⚙️ Processing page's Q${questionCount}...`, true);
let headerQuestion = questionRow.querySelector("div.question-header > *");
if (headerQuestion === null) {
e("No header question found in question row");
console.groupEnd();
continue;
}
let textParts = extractTextParts(headerQuestion);
if (textParts.length === 0) {
e("No text parts extracted from header question");
console.groupEnd();
continue;
}
let actualMarks = null;
let maxMarks = null;
if (extractorMode) {
let marksReport = questionRow.querySelector("div.mark-obtained > span");
if (marksReport !== null) {
let regex = /^You scored (?<actualMarks>\d+(?:\.\d+)?) \/ (?<maxMarks>\d+(?:\.\d+)?) marks?$/u;
let result = regex.exec(marksReport.textContent);
if (result === null) w("Unrecognised marks format in marks report");
else {
let resultGroups = result.groups;
actualMarks = parseFloat(resultGroups.actualMarks);
maxMarks = parseFloat(resultGroups.maxMarks);
}
}
}
let input = tryProcessBlanks(questionRow, extractorMode)
?? tryProcessResponses(questionRow, extractorMode)
?? tryProcessChoices(questionRow, extractorMode);
if (input === null) {
e("⚠️ This type of question isn't supported");
console.groupEnd();
continue;
}
let marksHint = null;
if (!extractorMode) {
marksHint = questionRow.querySelector(
"div.question-header > small:nth-child(2)"
);
if (marksHint === null) {
e("No marks hint found in question row");
console.groupEnd();
continue;
}
}
let question = new Question(
textParts,
actualMarks,
maxMarks,
input,
questionRow,
marksHint
);
d(question);
questions.push(question);
successCount++;
console.groupEnd();
}
if (questions.length === 0) {
e("No questions extracted from question rows");
return null;
}
l(`📦 Processed ${successCount}/${questionCount} questions`);
d(questions);
return questions;
}
function tryProcessBlanks(questionRow, extractorMode) {
// Check if is this question type
let blanksHolder = questionRow.querySelector("question-view-fib");
if (blanksHolder === null) return null;
let blanksQuestion = blanksHolder.querySelector("span.question");
if (blanksQuestion === null) {
e("No blanks question found in blanks holder");
return null;
}
let textParts = extractTextParts(blanksQuestion);
if (textParts.length === 0) {
e("No text parts extracted from blanks question");
return null;
}
let answerBlanks = textParts.filter((textPart) => textPart.type === TextPartType.BLANK);
let entryHolders = blanksHolder.querySelectorAll("div.input");
if (entryHolders.length === 0) {
e("No entry holders found in blanks holder");
return null;
}
let answerBlankCount = answerBlanks.length;
let entryHolderCount = entryHolders.length;
if (answerBlankCount !== entryHolderCount) {
w(`Number of answer blanks (${answerBlankCount}) doesn't match number of entry holders (${entryHolderCount})`);
}
let successCount = 0;
let entries = [];
for (let entryHolder of entryHolders) {
let text;
let input;
if (extractorMode) {
let textarea = entryHolder.querySelector("textarea.answer-fib");
if (textarea === null) {
e("No textarea found in entry holder");
continue;
}
text = textarea.value;
input = null;
} else {
text = null;
input = entryHolder.querySelector("input.form-control");
if (input === null) {
e("No input found in entry holder");
continue;
}
}
entries.push(
new BlanksEntry(text, input)
);
successCount++;
}
if (entries.length === 0) {
e("No entries extracted from entry holders");
return null;
}
l(`(Processed ${successCount}/${entryHolders.length} entries)`);
return new BlanksInput(textParts, entries);
}
function tryProcessResponses(questionRow, extractorMode) {
let responsesHolder = questionRow.querySelector("question-view-mrq");
if (responsesHolder === null) return null;
let entryHolders = responsesHolder.querySelectorAll("div.option-content");
if (entryHolders.length === 0) {
e("No entry holders found in responses holder");
return null;
}
let successCount = 0;
let entries = [];
for (let entryHolder of entryHolders) {
let textHolder = entryHolder.querySelector("div.text");
if (textHolder === null) {
e("No text holder found in entry holder");
continue;
}
let textParts = extractTextParts(textHolder);
if (textParts.length === 0) {
e("No text parts extracted from text holder");
continue;
}
let checkbox = entryHolder.querySelector("input[type=checkbox]");
if (checkbox === null) {
e("No checkbox found in entry holder");
continue;
}
let checked = extractorMode
? checkbox.checked
: null;
entries.push(
new ResponsesEntry(
textParts,
checked,
checkbox
)
);
successCount++;
}
if (entries.length === 0) {
e("No entries extracted from entry holders");
return null;
}
l(`(Processed ${successCount}/${entryHolders.length} entries)`);
return new ResponsesInput(entries);
}
function tryProcessChoices(questionRow, extractorMode) {
let choicesHolder = questionRow.querySelector("question-view-mcq")
?? questionRow.querySelector("question-view-tof");
if (choicesHolder === null) return null;
let entryHolders = choicesHolder.querySelectorAll("div.option-content");
if (entryHolders.length === 0) {
e("No entry holders found in choices holder");
return null;
}
let successCount = 0;
let entries = [];
let soleButton = null;
for (let entryHolder of entryHolders) {
let textHolder = entryHolder.querySelector("div.text");
if (textHolder === null) {
e("No text holder found in entry holder");
continue;
}
let textParts = extractTextParts(textHolder);
if (textParts.length === 0) {
e("No text parts extracted from text holder");
continue;
}
let button = entryHolder.querySelector("input[type=radio]");
if (button === null) {
e("No button found in entry holder");
continue;
}
let checked;
if (extractorMode) {
checked = button.checked;
if (checked) {
if (soleButton !== null) {
e("Multiple checked buttons found in entry holders");
return null;
}
soleButton = button;
}
} else checked = null;
entries.push(
new ChoicesEntry(
textParts,
checked,
button
)
);
successCount++;
}
if (entries.length === 0) {
e("No entries extracted from entry holders");
return null;
}
l(`(Processed ${successCount}/${entryHolders.length} entries)`);
return new ChoicesInput(entries);
}
function onImport(_pageQuestions, storedData) {
// Clone for importOne() to progressively remove overwritten questions
let pageQuestions = [..._pageQuestions];
let successCount = 0;
let questionCount = 0;
for (let storedQuestion of storedData) {
questionCount++;
l(`🔮 Importing stored question #${questionCount}...`, true);
try {
let success = importOne(storedQuestion, pageQuestions);
if (success) successCount++;
} catch (error) {
e("⛔ Your stored answer is in a different format. You may be running a newer version of the script on outdated data - try re-extracting your answers");
e(error);
}
console.groupEnd();
}
l(`☁️ Imported ${successCount}/${questionCount} questions`);
}
function importOne(storedQuestion, pageQuestions) {
let success = false;
for (let i = 0; i < pageQuestions.length; i++) {
let pageQuestion = pageQuestions[i];
let headerQuestionsMatch = compareTextParts(
storedQuestion.textParts,
pageQuestion.textParts
);
if (!headerQuestionsMatch) continue;
let storedInput = storedQuestion.input;
let pageInput = pageQuestion.input;
if (storedInput.type !== pageInput.type) continue;
switch (storedInput.type) {
case QuestionType.BLANKS:
success = tryImportBlanks(
storedInput,
pageInput
);
break;
case QuestionType.RESPONSES:
success = tryImportResponses(
storedInput,
pageInput
);
break;
case QuestionType.CHOICES:
success = tryImportChoices(
storedInput,
pageInput
);
break;
default:
e("Stored question type not supported");
return false;
}
if (success) {
// Remove for efficiency
pageQuestions.splice(i, 1);
let actualMarks = storedQuestion.actualMarks;
let maxMarks = storedQuestion.maxMarks;
if (
actualMarks !== null
&& maxMarks !== null
) {
let isWarning = actualMarks < maxMarks;
let rgb = (isWarning)
? "255 170 0" // Orange
: "85 255 170"; // Greenish blue
let rowStyle = pageQuestion.questionRow.style;
rowStyle["background-color"] = `rgb(${rgb} / 10%)`;
rowStyle["box-shadow"] = `0px 0px 25px 25px rgb(${rgb} / 10%)`;
rowStyle["border-radius"] = "50px";
let newDiv = document.createElement("div");
newDiv.setAttribute("tag-custom", "");
newDiv.textContent = `☁️ Imported Marks: ${actualMarks}/${maxMarks}`;
let divStyle = newDiv.style;
divStyle.display = "inline-block";
divStyle["line-height"] = "1";
divStyle.padding = "5px";
divStyle["font-size"] = "15px";
divStyle["font-weight"] = "bold";
divStyle["background-color"] = `rgb(${rgb} / 40%)`;
divStyle["border-radius"] = "5px";
let oldSmall = pageQuestion.marksHint;
let potentialExistingDiv = oldSmall.nextSibling;
if (
potentialExistingDiv?.nodeType === Node.ELEMENT_NODE
&& potentialExistingDiv.hasAttribute("tag-custom")
) potentialExistingDiv.remove();
oldSmall.style.display = "none";
let potentialNextSibling = oldSmall.nextSibling;
// Inserts at the end if potentialNextSibling is null (if oldSmall is already last node)
oldSmall.parentNode.insertBefore(newDiv, potentialNextSibling);
}
return true;
}
}
e("⚠️ Your stored answer doesn't match any of this quiz's processed questions");
return false;
}
function tryImportBlanks(storedInput, pageInput) {
let inputQuestionsMatch = compareTextParts(
storedInput.textParts,
pageInput.textParts
);
if (!inputQuestionsMatch) return false;
let storedEntries = storedInput.entries;
let pageEntries = pageInput.entries;
if (storedEntries.length !== pageEntries.length) return false;
for (let i = 0; i < storedEntries.length; i++) {
let storedEntry = storedEntries[i];
let pageEntry = pageEntries[i];
let control = pageEntry.control;
control.value = storedEntry.text;
triggerUpdate(control, "input");
}
return true;
}
function tryImportResponses(storedInput, pageInput) {
let storedEntries = storedInput.entries;
let pageEntries = [...pageInput.entries];
if (storedEntries.length !== pageEntries.length) return false;
let orderedCheckboxes = [];
// Check if all entries have a match.
// Eg header question is likely identical for different sets of entries
outerLoop:
for (let storedEntry of storedEntries) {
for (let i = 0; i < pageEntries.length; i++) {
let pageEntry = pageEntries[i];
if (compareTextParts(
storedEntry.textParts,
pageEntry.textParts
)) {
orderedCheckboxes.push(pageEntry.control);
// Remove for efficiency, end loop as array mutated
pageEntries.splice(i, 1);
continue outerLoop;
}
}
// No page entries matched the stored entry
return false;
}
// Safe to start overwriting
for (let i = 0; i < storedEntries.length; i++) {
let storedEntry = storedEntries[i];
let checkbox = orderedCheckboxes[i];
checkbox.checked = storedEntry.checked;
triggerUpdate(checkbox);
}
return true;
}
function tryImportChoices(storedInput, pageInput) {
let storedEntries = storedInput.entries;
let pageEntries = [...pageInput.entries];
let buttonToCheck = null;
outerLoop:
for (let storedEntry of storedEntries) {
for (let i = 0; i < pageEntries.length; i++) {
let pageEntry = pageEntries[i];
if (compareTextParts(
storedEntry.textParts,
pageEntry.textParts
)) {
if (storedEntry.checked) buttonToCheck = pageEntry.control;
pageEntries.splice(i, 1);
continue outerLoop;
}
}
return false;
}
if (buttonToCheck === null) {
e("No button to check in stored entries");
return true;
}
buttonToCheck.checked = true;
triggerUpdate(buttonToCheck);
return true;
}
function onStore(questions) {
let data = questions.map((question) => question.export());
d(data);
localStorage.setItem(
"LumiTransfer",
JSON.stringify(data)
);
}
function onRetrieve() {
let rawData = localStorage.getItem("LumiTransfer");
if (rawData === null) {
e("⛔ Did not find any stored answers to import. Run this script on your quiz results (not an ongoing attempt) to extract those answers first");
return null;
}
let data;
try {
data = JSON.parse(rawData);
} catch (syntaxError) {
e("Stored data unreadable");
e(syntaxError);
return null;
}
l("✨ Stored answers retrieved");
d(data);
return data;
}
function onProperSave(saveButton) {
if (saveButton === null) return;
saveButton.click();
}
let scan = onScan();
if (scan === null) return;
let questions = onProcess(scan.questionRows, scan.extractorMode);
if (questions === null) return;
if (scan.extractorMode) {
onStore(questions);
l("✅ Your answers have been extracted & stored. Run this script again on an ongoing quiz attempt to import them");
} else {
let storedData = onRetrieve();
if (storedData === null) return;
onImport(questions, storedData);
onProperSave(scan.saveButton);
l("✅ Your answers have been retrieved & imported. Matching questions have been overwritten");
}
})();