forked from thewindsofwinter/JHMC-scripts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
368 lines (315 loc) · 11.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const AirtablePlus = require("airtable-plus");
const humanizeDuration = require("humanize-duration");
const tests = require("./tests");
const { match } = require("path-to-regexp");
const http = require("http").createServer(app);
const fs = require("fs");
const websocket = require("./socket.js");
const { apiKey, baseID, sampleTestId } = require("./secrets.js");
// baseID, apiKey, and tableName can alternatively be set by environment variables
const testsTable = new AirtablePlus({ tableName: "Tests", apiKey, baseID }),
studentsTable = new AirtablePlus({ tableName: "Students", apiKey, baseID }),
schoolsTable = new AirtablePlus({ tableName: "Schools", apiKey, baseID }),
competitionsTable = new AirtablePlus({
tableName: "Competitions",
apiKey,
baseID,
}),
eventsTable = new AirtablePlus({ tableName: "Events", apiKey, baseID }),
extraneousRedirectsTable = new AirtablePlus({
tableName: "Redirects",
apiKey,
baseID,
}),
alertsTable = new AirtablePlus({ tableName: "Alerts", apiKey, baseID });
// error function that returns the rendered error page
const error = (res, text) => {
console.log("ERROR!");
res.status(500).render("pages/error.ejs", {
errorText:
text ||
"There was an unexpected error. Please contact your proctor, who will inform the JHMC team.",
});
};
app.set("view engine", "ejs");
app.use(function (req, res, next) {
/* // Try new solution
if (req.hostname != 'localhost' && req.get('X-Forwarded-Proto') == 'http') {
res.redirect(`https://${req.host}${req.url}`);
return;
}
next(); */
// Redirect HTTP to HTTPS
if (req.headers["x-forwarded-proto"] === "https") return next();
if (req.protocol === "https") return next();
if (req.hostname === "localhost") return next();
res.redirect(301, `https://${req.hostname}${req.url}`);
});
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.render("pages/home.ejs");
});
app.get("/homeworking", (req, res) => {
res.render("pages/newhome[working].ejs");
});
app.get("/partners", (req, res) => {
res.render("pages/partners.ejs");
});
app.get("/contest-rules", (req, res) => {
res.render("pages/contest-rules.ejs");
});
app.get("/past-tests", (req, res) => {
res.render("pages/past-tests.ejs");
});
app.get("/about", (req, res) => {
res.render("pages/about.ejs");
});
// any actual test
app.get("/test/:recordId", async (req, res) => {
const recordId = req.params.recordId;
if (recordId == "sample") {
res.redirect("/test/" + sampleTestId);
return;
}
try {
let record = await testsTable.find(recordId);
let testBegun = false;
if (record.fields["Start Time"] || record.fields["Submission Time"]) {
testBegun = true;
}
console.log(record);
let studentsPromise = record.fields.Students.map((studentId) =>
studentsTable.find(studentId)
),
schoolPromise = schoolsTable.find(record.fields.School[0]),
competitionPromise = competitionsTable.find(record.fields.Competition[0]);
// let [competition, school, ...students] = await Promise.all([competitionPromise, schoolPromise, ...studentsPromise]);
let [competition, ...students] = await Promise.all([
competitionPromise,
...studentsPromise,
]);
let questions = await tests.getOrderedQuestions(
record,
competition.fields.Code
);
let available = tests.validateTime(competition, record, false),
currentQuestion = record.fields["Current Question Index"];
console.log(available);
if (!testBegun && currentQuestion && currentQuestion != 0) {
currentQuestion = 0;
testsTable.update(record.id, { "Current Question Index": 0 });
}
if (record.id == sampleTestId) {
await testsTable.update(record.id, { "Current Question Index": 0 });
currentQuestion = 0;
testBegun = false;
}
let name = students.map((s) => s.fields.Name).join(", "),
competitionName = competition.fields["Friendly Name"];
let competitionType = competition.fields["Test Type"];
let liveAlerts = await websocket.getAlerts(alertsTable);
let alertsObject = await websocket.getAlertObject(liveAlerts),
alertsHtml = alertsObject.html;
res.render("pages/tests", {
name,
primary: name,
competition: competitionName,
secondary: competitionName + " Test",
division: competition.fields.Division,
durationText: humanizeDuration(competition.fields["Max Duration"] * 1000),
duration: competition.fields["Max Duration"] * 1000,
competitionId: competition.id,
competitionCode: competition.fields.Code,
recordId,
beginButtonText: testBegun ? "Resume Test" : "Begin Test",
numberOfQuestions: questions.length,
currentQuestion,
available,
competitionType,
individualQuestions:
competitionType == "One Question" ||
competitionType == "Spaced Questions",
questionTemplate: fs.readFileSync("views/partials/question.ejs", "utf8"),
alertsHtml,
});
} catch (e) {
console.log(e);
error(res, "Error fetching: " + e);
}
});
//endpoints for current tests to start; I built this part before websockets were implemented
//now, to do this, i would just use websockets
app.post("/test/endpoint/:recordId", async (req, res) => {
const recordId = req.params.recordId;
let record = await testsTable.find(recordId),
competition = await competitionsTable.find(record.fields.Competition[0]),
competitionType = competition.fields["Test Type"],
individualQuestions =
competitionType == "One Question" ||
competitionType == "Spaced Questions";
const questionsPromise = tests.getOrderedQuestions(
record,
req.body.competitionCode
);
if (tests.validateTime(competition, record, true) !== "true") {
res.send("TIMEOUT");
return;
}
if (req.body.action == "begin") {
try {
let questions = await questionsPromise;
let numberQuestionsCompleted =
record.fields["Current Question Index"] || 0;
if (record.id === sampleTestId) {
const time = Date.now();
testsTable.update(recordId, { "Start Time": time });
record.fields["Start Time"] = time; // Could reaquire record, but that would take a lot of time — this is easier & faster
} else if (
record.fields["Start Time"] &&
numberQuestionsCompleted === questions.length
) {
res.send("FINISHED");
return;
} else if (!record.fields["Start Time"]) {
// if test has not been started
const time = Date.now();
const startTimePromise = testsTable.update(recordId, {
"Start Time": time,
});
record.fields["Start Time"] = time; // Could reaquire record, but that would take a lot of time — this is easier & faster
const currentQuestionIndexPromise = testsTable.update(recordId, {
"Current Question Index": 0,
});
}
// let [other] = await Promise.all([startTimePromise, currentQuestionIndexPromise]);
if (individualQuestions) {
res.status(200).json({
questions: [questions[numberQuestionsCompleted]],
closingTime: tests.getEndTime(competition, record).toString(),
});
} else {
res.status(200).json({
questions,
closingTime: tests.getEndTime(competition, record).toString(),
});
}
} catch (e) {
console.log(e);
res.error("Something went wrong " + e.toString());
}
} else if (req.body.action == "next") {
try {
let questions = await questionsPromise;
let answers = req.body.answers,
numberQuestionsCompleted,
newNumberOfQuestionsCompleted;
console.log(req.body.answers);
if (individualQuestions) {
// For individual questions, we have to withstand using the current question index, otherwise somebody could theoretically change the question code on submission
numberQuestionsCompleted = record.fields["Current Question Index"];
let answeredQuestion = questions.find(
(q) => q.index == numberQuestionsCompleted
);
testsTable.update(recordId, {
[answeredQuestion.questionCode]: req.body.answers[0].text,
});
newNumberOfQuestionsCompleted =
parseInt(record.fields["Current Question Index"]) + 1;
if (newNumberOfQuestionsCompleted === questions.length) {
const time = await testsTable.update(record.id, {
"Submission Time": Date.now(),
});
res.send("FINISHED");
} else {
res.status(200).json({
questions: [questions[newNumberOfQuestionsCompleted]],
closingTime: tests.getEndTime(competition, record).toString(),
});
}
} else {
newNumberOfQuestionsCompleted = questions.length;
await Promise.all(
answers.map((answer) => {
// returning a promise which is received and awaited by Promise.all
return testsTable.update(recordId, {
[answer.questionCode]: answer.text,
});
})
);
const time = await testsTable.update(record.id, {
"Submission Time": Date.now(),
});
res.status(200).send("FINISHED");
}
testsTable.update(recordId, {
"Current Question Index": newNumberOfQuestionsCompleted,
});
} catch (e) {
console.log(e);
}
} else {
res.status(400).send("Unknown Request");
}
});
require("./schedule.js")(
app,
{ eventsTable, studentsTable, schoolsTable, testsTable, alertsTable },
websocket,
error
);
websocket.buildWebsocket(http, app, alertsTable);
app.get("/error", (req, res) => {
error(res);
});
app.get("**", async (req, res) => {
let path = req.path;
let redirected = false;
console.log(path);
let possibleRedirects = [];
let events = await eventsTable.read();
events.forEach((event) => {
possibleRedirects.push({
from: `/${event.fields.ID}`,
to: event.fields["Zoom Link"],
});
});
// Eliminate events
// possibleRedirects = []
let redirects = await extraneousRedirectsTable.read();
redirects.forEach((extraneousRedirect) => {
possibleRedirects.push({
from: `${extraneousRedirect.fields.Origin}`,
to: extraneousRedirect.fields.Redirect,
});
});
possibleRedirects.forEach((r) => {
let fn = match(r.from, { decode: decodeURIComponent });
// console.log(fn, r.from, path, fn(path));
if (fn(path)) {
console.log(path, fn.from);
res.redirect(r.to);
redirected = true;
}
});
if (!redirected) {
res.status(404).render("pages/404.ejs");
}
});
process.on("unhandledRejection", (reason, p) => {
console.log("Unhandled Rejection at: Promise", p, "reason:", reason);
// application specific logging, throwing an error, or other logic here
});
const server = http.listen(8080, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`App listening at http://localhost:${port}`);
});