-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
1377 lines (1229 loc) · 49.2 KB
/
server.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
"use strict";
const express = require("express"),
app = express(),
bodyParser = require("body-parser"),
compression = require("compression"),
fs = require("fs"),
util = require("util"),
sqlite = require("sqlite3").verbose(),
handleError = require("./custom_modules/handleError.js"),
getUnfinishedQuestion = require("./custom_modules/getUnfinishedQuestion.js"),
shuffle = require("./custom_modules/shuffle.js"),
questionMatchesSettings = require("./custom_modules/questionMatchesSettings.js"),
nodemailer = require("nodemailer"),
transporter = nodemailer.createTransport(JSON.parse(fs.readFileSync("emailCredentials.json", "utf8")));
app.set('trust proxy', true);
const templateConvert = require("./public_html/globalResources/templateConvert.js"),
presetTemplates = require("./public_html/globalResources/presetTemplates.js"),
replaceExpressions = require("./public_html/globalResources/replaceExpressions.js"),
searchLinks = require("./public_html/globalResources/searchLinks.js"),
playerNames = JSON.parse(fs.readFileSync("playerNames.json", "utf8"));
app.use(compression());
app.use(bodyParser.json({"limit":"1mb"}));
app.use(bodyParser.urlencoded({"extended": true}));
app.use(express.static("./public_html"));
let server;
function deepFreeze(object) {
// Retrieve the property names defined on object
const propNames = Reflect.ownKeys(object);
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name];
if ((value && typeof value === "object") || typeof value === "function") {
deepFreeze(value);
}
}
return Object.freeze(object);
}
let referenceQuestionArray;
let canonicalAllCards = JSON.parse(fs.readFileSync("allCards.json", "utf8"));
deepFreeze(canonicalAllCards);
const sendEmail = function(recipientEmail, subject, message) {
transporter.sendMail({
from: "[email protected]",
to: recipientEmail,
subject: subject,
text: message,
}, function(err) {
if (err) {
handleError(err);
}
});
}
const sendEmailToOwners = function(subject, message, res) {
const allAdmins = JSON.parse(fs.readFileSync("admins.json", "utf8"));
for (let i in allAdmins) {
if (allAdmins[i].roles.owner) {
transporter.sendMail({
"from": "[email protected]",
"to": allAdmins[i].emailAddress,
"subject": subject,
"text": message
}, function(err) {
if (err) {
handleError(err);
if (res) {
res.send("email error")
}
} else {
if (res) {
res.send("success")
}
}
});
}
}
}
let promisifiedAll,
promisifiedGet,
promisifiedRun,
dbAll,
dbGet,
dbRun;
const db = new sqlite.Database("questionDatabase.db", async function(err) {
if (err) {
handleError(err);
} else {
console.log("Database created");
promisifiedAll = util.promisify(db.all),
promisifiedGet = util.promisify(db.get),
promisifiedRun = util.promisify(db.run),
dbAll = async function(arg1, arg2) {
const result = await promisifiedAll.call(db, arg1, arg2);
return result;
},
dbGet = async function(arg1, arg2) {
const result = await promisifiedGet.call(db, arg1, arg2);
return result;
},
dbRun = async function(arg1, arg2) {
const result = await promisifiedRun.call(db, arg1, arg2);
return result;
};
try {
referenceQuestionArray = JSON.parse(fs.readFileSync("referenceQuestionArray.json", "utf8"));
deepFreeze(referenceQuestionArray);
} catch {
console.log("Generating reference question array")
await updateReferenceObjects();
}
//Check for a reference question array that's out of aync with the database.
const allData = await dbAll(`SELECT * FROM questions`);
const referenceArrayNums = referenceQuestionArray.map(question => question.id);
const databaseNums = allData.filter(question => question.status === "finished").map(question => question.id);
let problemString = "";
if (referenceArrayNums.filter(num => !databaseNums.includes(num)).length > 0) {
problemString += `Database doesn't include questions ${referenceArrayNums.filter(num => !databaseNums.includes(num))}. `;
}
if (databaseNums.filter(num => !referenceArrayNums.includes(num)).length > 0) {
problemString += `Reference array doesn't include questions ${databaseNums.filter(num => !referenceArrayNums.includes(num))}`;
}
if (problemString !== "") {
handleError(new Error(`Reference array mismatch: ${problemString}`));
}
server = app.listen(8080, function () {
console.log("Listening on port 8080");
});
};
});
const validateAdmin = function(password) {
const allAdmins = JSON.parse(fs.readFileSync("admins.json", "utf8"));
let currentAdmin;
for (let i in allAdmins) {
if (password === allAdmins[i].password) {
currentAdmin = allAdmins[i];
break;
}
}
if (!currentAdmin) {
return "Incorrect password.";
} else if (!Object.values(currentAdmin.roles).includes(true)) {
return "Your account is disabled. Please contact the site owner if you think this is in error.";
} else {
return JSON.parse(JSON.stringify(currentAdmin));
}
}
//Format a question to be sent to the browser and send it.
const sendQuestion = function(question, res, allCards) {
const questionToSend = JSON.parse(JSON.stringify(question));
questionToSend.oracle = [];
let chosenCards = [];
if (questionToSend.cardLists.length > 0) {
//Randomly pick cards for the question.
let chosenCards;
for (let i = 0 ; i < 100000 ; i++) {
chosenCards = [];
for (let j = 0 ; j < questionToSend.cardLists.length ; j++) {
chosenCards.push(questionToSend.cardLists[j][Math.floor(Math.random()*questionToSend.cardLists[j].length)]);
}
if (Array.from(new Set(chosenCards)).length === chosenCards.length) {
break;
}
}
if (Array.from(new Set(chosenCards)).length !== chosenCards.length) {
res.json({"error":"There are no questions that fit your parameters. Please change your settings and try again.\n\Have a question that would fit those parameters? Submit it!"});
return;
}
for (let i = 0 ; i < chosenCards.length ; i++) {
questionToSend.oracle.push(allCards[chosenCards[i]]);
}
}
//Don't send the cardLists since they're not needed.
delete questionToSend.cardLists;
const allRules = JSON.parse(fs.readFileSync("allRules.json"));
const allNeededRuleNumbers = (questionToSend.question + questionToSend.answer).match(/(?<=\[)(\d{3}(\.\d{1,3}([a-z])?)?)(?=\])/g) || [];
const allNeededRules = Object.values(allRules).filter(function(rule) {
return allNeededRuleNumbers.includes(rule.ruleNumber);
});
questionToSend.citedRules = {};
for (let rule of allNeededRules) {
questionToSend.citedRules[rule.ruleNumber] = rule;
}
res.json(questionToSend);
}
const convertAllTemplates = function(question, allCards) {
const convertedQuestion = JSON.parse(JSON.stringify(question))
convertedQuestion.cardLists = [];
for (let i = 0 ; i < convertedQuestion.cardGenerators.length ; i++) {
if (typeof convertedQuestion.cardGenerators[i][0] === "object") {
convertedQuestion.cardLists[i] = templateConvert(convertedQuestion.cardGenerators[i], allCards, presetTemplates);
} else {
convertedQuestion.cardLists[i] = convertedQuestion.cardGenerators[i]
}
}
delete convertedQuestion.cardGenerators;
return convertedQuestion;
};
//Update the reference question database and card object that are stored in memory.
const updateReferenceObjects = async function() {
canonicalAllCards = JSON.parse(fs.readFileSync("allCards.json", "utf8"));
deepFreeze(canonicalAllCards);
const finishedQuestions = await dbAll(`SELECT json FROM questions WHERE status = "finished"`);
finishedQuestions.forEach(function(currentValue, index){
finishedQuestions[index] = JSON.parse(currentValue.json);
});
for (let i = 0 ; i < finishedQuestions.length ; i++) {
//Expand templates.
finishedQuestions[i] = convertAllTemplates(finishedQuestions[i], canonicalAllCards);
//Check for a template that generated 0 cards.
let emptyTemplate = false;
for (let j = 0 ; j < finishedQuestions[i].cardLists.length ; j++) {
if (finishedQuestions[i].cardLists[j].length === 0) {
emptyTemplate = true;
}
}
if (emptyTemplate) {
sendEmailToOwners("RulesGuru template error", `Question ${finishedQuestions[i].id} generates an empty template.\n\nhttps://rulesguru.net/question-editor/?${finishedQuestions[i].id}`);
finishedQuestions.splice(i, 1);
i--;
}
}
referenceQuestionArray = finishedQuestions;
deepFreeze(referenceQuestionArray);
console.log("Reference question array generation complete");
saveReferenceQuestionArrayToDisk();
updateIndexQuestionCount();
}
setInterval(updateReferenceObjects, 86400000, false);
const updateIndexQuestionCount = function() {
let html = fs.readFileSync("public_html/index.html", "utf8");
html = html.replace(/(?<=\<span id=\"questionCount\"\>)\d+(?=\<\/span\>)/, referenceQuestionArray.length);
html = html.replace(/(?<=\<span id=\"questionCountMobile\"\>)\d+(?=\<\/span\>)/, referenceQuestionArray.length);
fs.writeFileSync("public_html/index.html", html);
}
let saveReferenceQuestionArrayToDiskRunning = false;
let saveReferenceQuestionArrayToDiskPending = false;
const saveReferenceQuestionArrayToDisk = async function() {
if (saveReferenceQuestionArrayToDiskRunning) {
saveReferenceQuestionArrayToDiskPending = true;
return;
}
saveReferenceQuestionArrayToDiskRunning = true;
saveReferenceQuestionArrayToDiskPending = false;
await Promise.resolve();//Cut off synchroous execution so the stringify doesn't block the outer function.
fs.writeFile("referenceQuestionArray.json", JSON.stringify(referenceQuestionArray), function() {
saveReferenceQuestionArrayToDiskRunning = false;
if (saveReferenceQuestionArrayToDiskPending) {
saveReferenceQuestionArrayToDisk();
}
});
}
//Returns a random map of player names and genders for each possible player tag.
const getPlayerNamesMap = function() {
const playerNamesMap = {};
const genderOrder = ["female", "male", "neutral"];
shuffle(genderOrder);
let genderIndex = 0;
const iterationOrder = ["AP", "NAP1", "NAP2", "NAP3", "NAP"];
for (let i in iterationOrder) {
const correctGenderPlayerNames = playerNames[iterationOrder[i]].filter(function(element) {
return element.gender === genderOrder[genderIndex];
})
playerNamesMap[iterationOrder[i]] = correctGenderPlayerNames[Math.floor(Math.random() * correctGenderPlayerNames.length)];
genderIndex++;
if (genderIndex > 2) {
genderIndex = 0;
}
}
shuffle(genderOrder);
let correctGenderPlayerNames = playerNames.AP.filter(function(element) {
return element.gender === genderOrder[0];
})
playerNamesMap.APa = correctGenderPlayerNames[Math.floor(Math.random() * correctGenderPlayerNames.length)];
correctGenderPlayerNames = playerNames.AP.filter(function(element) {
return element.gender === genderOrder[1];
})
playerNamesMap.APb = correctGenderPlayerNames[Math.floor(Math.random() * correctGenderPlayerNames.length)];
shuffle(genderOrder);
correctGenderPlayerNames = playerNames.NAP.filter(function(element) {
return element.gender === genderOrder[0];
})
playerNamesMap.NAPa = correctGenderPlayerNames[Math.floor(Math.random() * correctGenderPlayerNames.length)];
correctGenderPlayerNames = playerNames.NAP.filter(function(element) {
return element.gender === genderOrder[1];
})
playerNamesMap.NAPb = correctGenderPlayerNames[Math.floor(Math.random() * correctGenderPlayerNames.length)];
return playerNamesMap;
}
//Format a question to be sent to the browser and send it.
const sendAPIQuestions = function(questions, res, allCards) {
const allQuestionsToSend = {
"status": 200,
"questions": []
};
outerQuestionLoop: for (let question of questions) {
const questionToSend = JSON.parse(JSON.stringify(question));
let cardExpressions = Array.from((questionToSend.question + " " + questionToSend.answer).matchAll(/\[(card \d+(?::other side)?)(?::(?:colors|mana cost|mana value|supertypes|types|subtypes|power|toughness|loyalty))?(?::simple)?\]/g));
cardExpressions = cardExpressions.map(result => result[1]);//Use just the capture group.
cardExpressions = cardExpressions.filter(function(item, pos, self) {//Remove duplicates while preserving order of first instance.
return self.indexOf(item) == pos;
});
let chosenCardNames = [];
questionToSend.includedCards = [];
if (questionToSend.cardLists.length > 0) {
//Randomly pick cards for the question.
for (let i = 0 ; i < 10000 ; i++) {
const chosenCardNamesToTest = [];
for (let j = 0 ; j < questionToSend.cardLists.length ; j++) {
chosenCardNamesToTest.push(questionToSend.cardLists[j][Math.floor(Math.random()*questionToSend.cardLists[j].length)]);
}
if (Array.from(new Set(chosenCardNamesToTest)).length === chosenCardNamesToTest.length) {
chosenCardNames = chosenCardNamesToTest;
break;
}
}
//Check for a question with no valid card selection. If this occurs, we don't send that question.
if (chosenCardNames.length === 0) {
continue outerQuestionLoop;
}
for (let i = 0 ; i < cardExpressions.length ; i++) {
const cardNum = Number(cardExpressions[i].match(/(?<=card )\d+/));
const isOtherSide = /card \d+:other side/.test(cardExpressions[i]);
let matchedCard = allCards[chosenCardNames[cardNum - 1]];
if (isOtherSide) {
if (matchedCard.side === "a") {
matchedCard = allCards[matchedCard.names[1]];
} else {
matchedCard = allCards[matchedCard.names[0]];
}
}
questionToSend.includedCards.push(matchedCard);
}
}
//Don't send the cardLists since they're not needed.
delete questionToSend.cardLists;
//Handle formatting.
const allRules = JSON.parse(fs.readFileSync("allRules.json"));
const playerNamesMap = getPlayerNamesMap();
const chosenCards = chosenCardNames.map(cardName => allCards[cardName]);//We need to provide the cards to replaceExpressions in card generator order, not in text order like they are in includedCards.
const questionResult = replaceExpressions(questionToSend.question, playerNamesMap, chosenCards, allCards, allRules);
const answerResult = replaceExpressions(questionToSend.answer, playerNamesMap, chosenCards, allCards, allRules);
questionToSend.questionSimple = questionResult.plaintextNoCitations;
questionToSend.questionHTML = questionResult.html;
questionToSend.answerSimple = answerResult.plaintextNoCitations;
questionToSend.answerSimpleCited = answerResult.plaintext;
questionToSend.answerHTML = answerResult.html;
//Add citedRules
const allNeededRuleNumbers = (questionToSend.question + questionToSend.answer).match(/(?<=\[)(\d{3}(\.\d{1,3}([a-z])?)?)(?=\])/g) || [];
const allNeededRules = Object.values(allRules).filter(function(rule) {
return allNeededRuleNumbers.includes(rule.ruleNumber);
});
questionToSend.citedRules = {};
for (let rule of allNeededRules) {
questionToSend.citedRules[rule.ruleNumber] = rule;
}
//Add a link to the question on RG
const searchLinkMappings = JSON.parse(fs.readFileSync("public_html/globalResources/searchLinkMappings.js", "utf8").slice(27));
questionToSend.url = "https://rulesguru.net/?" + questionToSend.id + "RG" + searchLinks.convertSettingsToSearchLink({
"level": ["0", "1", "2", "3", "Corner Case"],
"complexity": ["Simple", "Intermediate", "Complicated"],
"legality": "All of Magic",
"expansions": [],
"playableOnly": false,
"tags": [],
"tagsConjunc": "OR",
"rules": [],
"rulesConjunc": "OR",
"cards": questionToSend.includedCards.map(card => card.name),
"cardsConjunc": "AND",
}, searchLinkMappings) + "GG";
//Remove old raw properties.
delete questionToSend.question;
delete questionToSend.answer;
//Add this question to the array of all questions to send to the client.
allQuestionsToSend.questions.push(questionToSend);
}
res.json(allQuestionsToSend);
}
/*List and description of request endpoints:
Question Editor:
/submitAdminQuestion: Requests from the admin page to submit a new question.
/updateQuestion: Requests from the admin page to update an existing question without changing its status.
/changeQuestionStatus: Requests from the admin page to change the status (and update) a question.
/getUnfinishedQuestion: Requests from the admin page to get a random unfinished question.
/getSpecificAdminQuestion: Requests from the admin page to get a question by its ID.
/getQuestionsList: Requests from the admin page to get a list of all question IDs that match parameters.
/validateLogin: Validates passwords.
/getTagData: Returns an object that lists tag names and counts.
/getAdminData: Admin data
/updateAdminData: update admin data
/updateAndForceStatus: Handle the owner-only options to force a question into a particular status.
General:
/submitContactForm: Contact form.
/getQuestionCount: Requests from the main page for the number of finished questions. Also requests from the editor for unfinished questions.
/submitQuestion: Requests from the submit page to submit an unfinished question.
/logSearchLinkData: Logs followed searchLinks.
API:
/api/questions
Development:
/mostPlayedStandard: Mirror since the origin API is private.
/mostPlayedPioneer: Mirror since the origin API is private.
/mostPlayedModern: Mirror since the origin API is private.
*/
let recentIPs = [];
app.get("/api/questions", function(req, res) {
let requestSettings;
try {
requestSettings = JSON.parse(decodeURIComponent(req.query.json));
} catch (error) {
res.json({"status": 400, "error":"json parameter is not valid JSON."});
return;
}
//When a request is received, update recentIPs to include only ones from within the last 2 seconds.
recentIPs = recentIPs.filter(ip => performance.now() - ip.date < 2000);
if (recentIPs.filter(ip => ip.ip).length > 0 && !requestSettings.avoidRateLimiting) {//If you find this and use it to get around my rate limiting, go ahead, you deserve it. But I'll be fixing this eventally.
res.json({"status": 429, "error":"Please don't send more than one request every 2 seconds."});
recentIPs.push({"ip": req.ip, "date": performance.now()});
return;
} else {
recentIPs.push({"ip": req.ip, "date": performance.now()});
}
let apiLog = JSON.parse(fs.readFileSync("logs/apiLog.json", "utf8"));
apiLog.push({"date": Date.now(), "request": req.query, "ip": req.ip});
fs.writeFileSync("logs/apiLog.json", JSON.stringify(apiLog));
const allCards = canonicalAllCards;
let questionArray = referenceQuestionArray.slice(0);// Must be a copy because referenceQuestionArray is immutable and this needs to be shuffled. Each question in the copy will still be immutable, which is desirable.
try {
let defaults;
if (requestSettings.id === undefined) {
defaults = {
"count": 1,
"level": ["0", "1", "2"],
"complexity": ["Simple", "Intermediate"],
"legality": "Modern",
"expansions": [],
"playableOnly": false,
"tags": ["Unsupported answers"],
"tagsConjunc": "NOT",
"rules": [],
"rulesConjunc": "OR",
"cards": [],
"cardsConjunc": "OR",
"previousId": undefined,
"id": undefined,
};
} else {
defaults = {
"count": 1,
"level": ["0", "1", "2", "3", "Corner Case"],
"complexity": ["Simple", "Intermediate", "Complicated"],
"legality": "All of Magic",
"expansions": [],
"playableOnly": false,
"tags": [],
"tagsConjunc": "OR",
"rules": [],
"rulesConjunc": "OR",
"cards": [],
"cardsConjunc": "OR",
"previousId": undefined,
"id": undefined,
};
}
for (let prop in defaults) {
if (!requestSettings.hasOwnProperty(prop)) {
requestSettings[prop] = defaults[prop];
}
}
} catch (error) {
handleError(error);
res.json({"status": 400, "error":"Incorrectly formatted query string."});
return;
}
try {
if (requestSettings.id !== undefined) {
if (typeof requestSettings.id !== "number" || requestSettings.id < 1) {
res.json({"status": 400, "error":"Invalid ID provided."});
return;
}
let questionToReturn;
for (let i = 0 ; i < questionArray.length ; i++) {
if (questionArray[i].id === requestSettings.id) {
questionToReturn = questionArray[i];
break;
}
}
if (!questionToReturn) {
res.json({"status": 404, "error":"A question with that ID does not exist."});
return;
}
const result = questionMatchesSettings(questionToReturn, requestSettings, allCards);
if (!result) {
res.json({"status": 400, "error":`Question ${requestSettings.id} cannot match the chosen settings.`});
return;
}
sendAPIQuestions([result], res, allCards);
} else {
let locationToStartSearch;
if (requestSettings.previousId !== undefined) {
if (typeof requestSettings.previousId !== "number" || !Number.isInteger(requestSettings.previousId) || requestSettings.previousId < 1) {
res.json({"status": 400, "error":`${requestSettings.previousId} is not a valid previous ID.`});
return;
}
questionArray.sort((a, b) => a.id - b.id);
for (let i = 0 ; i < questionArray.length ; i++) {
if (questionArray[i].id > requestSettings.previousId) {
locationToStartSearch = i;
break;
}
}
if (locationToStartSearch === undefined) {
locationToStartSearch = 0;
}
} else {
locationToStartSearch = 0;
shuffle(questionArray);
}
const questionsToReturn = [];
let currentSearchLocation = locationToStartSearch;
let loopCounter = 0;
while (true) {
loopCounter++;
if (loopCounter > 9999) {
handleError(new Error(`While loop not terminating.`))
break;
}
const result = questionMatchesSettings(questionArray[currentSearchLocation], requestSettings, allCards);
if (result) {
questionsToReturn.push(result);
}
if (questionsToReturn.length === requestSettings.count) {
sendAPIQuestions(questionsToReturn, res, allCards);
break;
}
currentSearchLocation++;
if (currentSearchLocation === questionArray.length) {
currentSearchLocation = 0;
}
if (currentSearchLocation === locationToStartSearch) {
res.json({"status": 404, "error":`There are ${requestSettings.count === 1 ? "no" : "not enough"} questions that fit your settings.`});
break;
}
}
}
} catch (error) {
console.log(error)
res.json({"status": 400, "error":"Incorrectly formatted json."});
}
});
app.post("/submitContactForm", function(req, res) {
if (req.body.message !== undefined) {
const message = req.body.message;
const num = message.match(/^Message about question #(\d+):/)[1];
sendEmailToOwners(num ? `RulesGuru contact form submission about question ${num}` : "RulesGuru contact form submission", message, res);
transporter.sendMail({
"from": "[email protected]",
"to": "[email protected]",
"subject": "RulesGuru contact form submission",
"text": message,
"replyTo": req.body.returnEmail
}, function(err) {
if (err) {
handleError(err);
if (res) {
res.send("email error")
}
} else {
if (res) {
res.send("success")
}
}
});
} else {
res.send("req.body.message was undefined.");
}
});
let lastTimeReferenceArrayMismatchWarningSent = 0;
app.get("/getQuestionCount", async function(req, res) {
const allData = await dbAll(`SELECT * FROM questions`);
//Check for a reference question array that's out of aync with the database.
const referenceArrayNums = referenceQuestionArray.map(question => question.id);
const databaseNums = allData.filter(question => question.status === "finished").map(question => question.id);
let problemString = "";
if (referenceArrayNums.filter(num => !databaseNums.includes(num)).length > 0) {
problemString += `Database doesn't include questions ${referenceArrayNums.filter(num => !databaseNums.includes(num))}. `;
}
if (databaseNums.filter(num => !referenceArrayNums.includes(num)).length > 0) {
problemString += `Reference array doesn't include questions ${databaseNums.filter(num => !referenceArrayNums.includes(num))}`;
}
if (problemString !== "") {
if (performance.now() - lastTimeReferenceArrayMismatchWarningSent > 60000) {
handleError(new Error(`Reference array mismatch: ${problemString}`));
lastTimeReferenceArrayMismatchWarningSent = performance.now();
}
}
allData.forEach(function(question) {
question.verification = JSON.parse(question.verification);
});
res.json({
"finished": referenceQuestionArray.length,
"pending": allData.filter(question => question.status === "pending").length,
"awaitingVerificationGrammar": allData.filter(question => question.status === "awaiting verification" && question.verification.grammarGuru === null).length,
"awaitingVerificationTemplates": allData.filter(question => question.status === "awaiting verification" && question.verification.templateGuru === null).length,
"awaitingVerificationRules": allData.filter(question => question.status === "awaiting verification" && question.verification.rulesGuru === null).length,
});
let countLog = JSON.parse(fs.readFileSync("logs/questionCountLog.json", "utf8"));
countLog.push(Date.now());
fs.writeFileSync("logs/questionCountLog.json", JSON.stringify(countLog));
});
app.post("/submitAdminQuestion", async function(req, res) {
const date = Date();
const validateAdminResult = validateAdmin(req.body.password);
let currentAdmin;
if (typeof validateAdminResult === "string") {
res.json({
"error": true,
"message": validateAdminResult
});
} else {
currentAdmin = validateAdminResult;
const addQuestionResult = await addQuestion(req.body.questionObj, true, currentAdmin.id);
if (!addQuestionResult.error) {
//Update the reference question array
if (addQuestionResult.newStatus === "finished") {
let newQuestion = req.body.questionObj;
const allCards = canonicalAllCards;
newQuestion = convertAllTemplates(newQuestion, allCards);
//Check for a template that generated 0 cards.
let emptyTemplate = false;
for (let j = 0 ; j < newQuestion.cardLists.length ; j++) {
if (newQuestion.cardLists[j].length === 0) {
emptyTemplate = true;
}
}
if (emptyTemplate) {
sendEmailToOwners("RulesGuru template error", `Question ${newQuestion.id} generates an empty template.\n\nhttps://rulesguru.net/question-editor/?${newQuestion.id}`);
} else {
//We have to copy the array and discard the old one since it was immutable.
referenceQuestionArray = referenceQuestionArray.slice(0);
referenceQuestionArray.push(newQuestion);
deepFreeze(referenceQuestionArray);
}
saveReferenceQuestionArrayToDisk();
updateIndexQuestionCount();
}
res.json({
"error": false,
"message": `Question #${addQuestionResult.newId} submitted successfully.`,
"id": addQuestionResult.newId,
"status": addQuestionResult.newStatus,
"verification": addQuestionResult.newVerification
});
if (currentAdmin.sendSelfEditLogEmails) {
sendEmail(currentAdmin.emailAddress, "You submitted a RulesGuru question", `You submitted question #${addQuestionResult.newId}.\n\nhttps://rulesguru.net/question-editor/?${addQuestionResult.newId}\n\nTime: ${date}\n\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
}
if (!currentAdmin.roles.owner) {
sendEmailToOwners(`RulesGuru admin submission (${currentAdmin.name})`, `${currentAdmin.name} has submitted question #${addQuestionResult.newId}.\n\nhttps://rulesguru.net/question-editor/?${addQuestionResult.newId}\n\nTime: ${date}\n\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
}
} else {
res.json({
"error": true,
"message": `Your question encountered an error being submitted. (${addQuestionResult.error}) Please report this to the site owner.`
});
}
}
});
app.post("/updateQuestion", async function(req, res) {
const validateAdminResult = validateAdmin(req.body.password);
let currentAdmin;
if (typeof validateAdminResult === "string") {
res.send(validateAdminResult);
} else {
currentAdmin = validateAdminResult;
let error = false;
if (!(Number.isInteger(req.body.questionObj.id) && req.body.questionObj.id > 0)) {
res.send("That question doesn't exist.");
return;
}
const date = Date();
const oldQuestion = await dbGet(`SELECT * FROM questions WHERE id = ${req.body.questionObj.id}`);
if (oldQuestion) {
await dbRun(`UPDATE questions SET json = '${JSON.stringify(req.body.questionObj).replace(/'/g,"''")}' WHERE id = ${req.body.questionObj.id}`);
res.json({
"message": `Question #${req.body.questionObj.id} updated successfully.`
});
//Update the reference question array
if (oldQuestion.status === "finished") {
//We have to copy the array and discard the old one since it was immutable.
referenceQuestionArray = referenceQuestionArray.slice(0);
for (let i in referenceQuestionArray) {
if (referenceQuestionArray[i].id === req.body.questionObj.id) {
let newQuestion = req.body.questionObj;
const allCards = canonicalAllCards;
newQuestion = convertAllTemplates(newQuestion, allCards);
//Check for a template that generated 0 cards.
let emptyTemplate = false;
for (let j = 0 ; j < newQuestion.cardLists.length ; j++) {
if (newQuestion.cardLists[j].length === 0) {
emptyTemplate = true;
}
}
if (emptyTemplate) {
sendEmailToOwners("RulesGuru template error", `Question ${newQuestion.id} generates an empty template.\n\nhttps://rulesguru.net/question-editor/?${newQuestion.id}`);
}
referenceQuestionArray[i] = newQuestion;
}
}
deepFreeze(referenceQuestionArray);
}
//Send emails about the change.
if (currentAdmin.sendSelfEditLogEmails) {
sendEmail(currentAdmin.emailAddress, `Your RulesGuru admin update`, `You've updated question #${req.body.questionObj.id} (${oldQuestion.status}).\n\nhttps://rulesguru.net/question-editor/?${req.body.questionObj.id}\n\nTime: ${date}\n\n\nOld question:\n\n${JSON.stringify(JSON.parse(oldQuestion.json), null, 2)}\n\n\nNew question:\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
}
if (!currentAdmin.roles.owner) {
sendEmailToOwners(`RulesGuru admin update (${currentAdmin.name})`, `${currentAdmin.name} has updated question #${req.body.questionObj.id} (${oldQuestion.status}).\n\nhttps://rulesguru.net/question-editor/?${req.body.questionObj.id}\n\nTime: ${date}\n\n\nOld question:\n\n${JSON.stringify(JSON.parse(oldQuestion.json), null, 2)}\n\n\nNew question:\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
}
} else {
res.json({"message": "That question doesn't exist."});
}
}
});
app.post("/changeQuestionStatus", async function(req, res) {
const validateAdminResult = validateAdmin(req.body.password);
let currentAdmin;
if (typeof validateAdminResult === "string") {
res.json({
"error": true,
"message": validateAdminResult
});
return;
} else {
currentAdmin = validateAdminResult;
if (!(Number.isInteger(req.body.questionObj.id) && req.body.questionObj.id > 0)) {
res.json({
"error": true,
"message": "That question doesn't exist."
});
return;
}
//Update the question.
const statusChange = req.body.statusChange;
delete req.body.questionObj.approve;
let date = Date(),
verificationObject,
newStatus,
action = "",
action2 = "";
const oldQuestion = await dbGet(`SELECT * FROM questions WHERE id = ${req.body.questionObj.id}`);
if (!oldQuestion) {
res.json({
"error": true,
"message": "That question doesn't exist."
});
return;
}
if (statusChange === "increase") {
if (oldQuestion.status === "pending") {
verificationObject = {
"editor": currentAdmin.id,
"grammarGuru": currentAdmin.roles.grammarGuru ? currentAdmin.id : null,
"templateGuru": currentAdmin.roles.templateGuru ? currentAdmin.id : null,
"rulesGuru": currentAdmin.roles.rulesGuru ? currentAdmin.id : null
};
if (verificationObject.grammarGuru !== null && verificationObject.templateGuru !== null && verificationObject.rulesGuru !== null) {
newStatus = "finished";
action = "approved and verified";
action2 = "approval and verification";
} else {
newStatus = "awaiting verification";
action = "approved";
action2 = "approval";
}
} else if (oldQuestion.status === "awaiting verification") {
verificationObject = JSON.parse(oldQuestion.verification);
for (let i of ["grammarGuru", "templateGuru", "rulesGuru"]) {
if (currentAdmin.roles[i]) {
verificationObject[i] = currentAdmin.id;
}
}
if (verificationObject.grammarGuru !== null && verificationObject.templateGuru !== null && verificationObject.rulesGuru!== null) {
newStatus = "finished";
action = "verified";
action2 = "verification";
} else {
newStatus = "awaiting verification";
action = "verified";
action2 = "verification";
}
}
} else if (statusChange === "decrease") {
if (oldQuestion.status === "awaiting verification") {
if (currentAdmin.id === JSON.parse(oldQuestion.verification).editor) {
newStatus = "pending";
action = "unapproved";
action2 = "unapproval";
verificationObject = {
"editor": null,
"grammarGuru": null,
"templateGuru": null,
"rulesGuru": null
};
} else {
newStatus = "awaiting verification";
action = "unverified";
action2 = "unverification";
verificationObject = JSON.parse(oldQuestion.verification);
for (let i of ["grammarGuru", "templateGuru", "rulesGuru"]) {
if (currentAdmin.roles[i]) {
verificationObject[i] = null;
}
}
}
}
}
if (!newStatus) {
res.json({
"error": true,
"message": "You do not have permission to perform this action."
});
return;
}
await dbRun(`UPDATE questions SET json = '${JSON.stringify(req.body.questionObj).replace(/'/g,"''")}', status = '${newStatus}', verification = '${JSON.stringify(verificationObject).replace(/'/g,"''")}' WHERE id = ${req.body.questionObj.id}`);
res.json({
"error": false,
"message": `Question #${req.body.questionObj.id} ${action} successfully.`,
"newStatus": newStatus,
"newVerification": verificationObject
});
//Update the reference question array
if (newStatus === "finished") {
let newQuestion = req.body.questionObj;
const allCards = canonicalAllCards;
newQuestion = convertAllTemplates(newQuestion, allCards);
//Check for a template that generated 0 cards.
let emptyTemplate = false;
for (let j = 0 ; j < newQuestion.cardLists.length ; j++) {
if (newQuestion.cardLists[j].length === 0) {
emptyTemplate = true;
}
}
if (emptyTemplate) {
sendEmailToOwners("RulesGuru template error", `Question ${newQuestion.id} generates an empty template.\n\nhttps://rulesguru.net/question-editor/?${newQuestion.id}`);
} else {
//We have to copy the array and discard the old one since it was immutable.
referenceQuestionArray = referenceQuestionArray.slice(0);
referenceQuestionArray.push(newQuestion);
deepFreeze(referenceQuestionArray);
}
saveReferenceQuestionArrayToDisk();
} else if (statusChange === "decrease") {
//We have to copy the array and discard the old one since it was immutable.
referenceQuestionArray = referenceQuestionArray.slice(0);
for (let i in referenceQuestionArray) {
if (referenceQuestionArray[i].id === req.body.questionObj.id) {
referenceQuestionArray.splice(i, 1);
}
}
deepFreeze(referenceQuestionArray);
saveReferenceQuestionArrayToDisk();
}
//Send emails about the change.
if (currentAdmin.sendSelfEditLogEmails) {
sendEmail(currentAdmin.emailAddress, `Your RulesGuru admin ${action2}`, `You've ${action} question #${req.body.questionObj.id} (${newStatus}).\n\nhttps://rulesguru.net/question-editor/?${req.body.questionObj.id}\n\nTime: ${date}\n\n\nOld question:\n\n${JSON.stringify(JSON.parse(oldQuestion.json), null, 2)}\n\n\nNew question:\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
}
sendEmailToOwners(`RulesGuru admin ${action2} (${currentAdmin.name})`, `${currentAdmin.name} has ${action} question #${req.body.questionObj.id}(${newStatus}).\n\nhttps://rulesguru.net/question-editor/?${req.body.questionObj.id}\n\nTime: ${date}\n\n\nOld question:\n\n${JSON.stringify(JSON.parse(oldQuestion.json), null, 2)}\n\n\nNew question:\n\n${JSON.stringify(req.body.questionObj, null, 2)}`);
if (typeof req.body.changes === "string") {
const allAdmins = JSON.parse(fs.readFileSync("admins.json", "utf8"));
sendEmailToOwners("RulesGuru admin verification with changes", `${currentAdmin.name} has verified question #${req.body.questionObj.id} (originally approved by ${allAdmins[verificationObject.editor] ? allAdmins[verificationObject.editor].name : `an unknown admin with ID ${verificationObject.editor}`}) with the following changes:\n\n${req.body.changes}`);
if (allAdmins[verificationObject.editor]) {
sendEmail(allAdmins[verificationObject.editor].emailAddress, `RulesGuru question verification feedback`, `Your question https://rulesguru.net/question-editor/?${req.body.questionObj.id} has been verified with the following feedback:\n\n${req.body.changes}`);
}
}
let recentlyDistributedQuestionIds = JSON.parse(fs.readFileSync("recentlyDistributedQuestionIds.json", "utf8"));
if (recentlyDistributedQuestionIds.includes(req.body.questionObj.id)) {
const index = recentlyDistributedQuestionIds.indexOf(req.body.questionObj.id);
recentlyDistributedQuestionIds.splice(index, 1);
}
fs.writeFileSync("recentlyDistributedQuestionIds.json", JSON.stringify(recentlyDistributedQuestionIds));
updateIndexQuestionCount();
}
});
let addQuestionRunning = false;
const addQuestion = async function(question, isAdmin, adminId) {
if (addQuestionRunning) {
await new Promise(r => setTimeout(r, 50)); //sleep for 50 milliseconds
return await addQuestion(question, isAdmin, adminId);
} else {