-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
435 lines (392 loc) · 11.9 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
import express from "express";
import { gen_test } from "./test_icle/modules/test2pdf.js";
import * as globals from "./test_icle/globals.js";
import fs from "fs";
import chalk from "chalk";
import { TestIcle } from "./test_icle/test_icle.js";
const port = process.env.PORT || 8080;
const app = express();
const testicle_api = new TestIcle();
const log_path = "logs/generallog.log";
const PDF_HEADER = { "Content-Type": "application/pdf" };
const JSON_HEADER = { "Content-Type": "application/json" };
const log_types = {
ERROR: chalk.red("[-]"),
WARNING: chalk.yellow("[~]"),
INFO: chalk.cyan("[*]"),
};
app.use(express.static("static"));
app.use(express.json({ limit: "100mb" }));
// This needs to be adjusted to the exact db-design later
app.put("/api/createQuestion", async (req, res) => {
const typ = req.body.typ;
const points = req.body.points;
const title = req.body.title;
const question = req.body.question;
const exAns = req.body.exAns;
const answers = req.body.answers;
const topicID = req.body.topicID;
try {
const content = [points, title, question, exAns, topicID]
.filter((element) => element !== undefined)
.map((element) => (element ? element : null));
if (typ == globals.MULTIPLE_CHOICE_TN) {
await testicle_api.CreateMultQuestion(content, answers);
} else if (typ == globals.TEXT_QUESTIONS_TN) {
await testicle_api.CreateTextQuestion(content);
} else {
res.status(400).send("Unallowed question type").end();
return;
}
log(`New question created! Questionname: ${title}`, log_types.INFO);
res.writeHead(204).end();
} catch (err) {
log(err);
res.status(400).send("Not all needed elements were supplied").end();
}
});
app.put("/api/createSubject", async (req, res) => {
const name = req.body.name;
if (!name) {
res.status(404).send("Not all needed Elements were supplied").end();
return;
}
try {
await testicle_api.CreateSubject([name]);
res.status(204).end();
} catch (err) {
log(err, log_types.WARNING);
res.status(400).send("Not all needed elements were supplied").end();
}
});
app.put("/api/createTopic", async (req, res) => {
const name = req.body.name;
const subjectID = req.body.subjectID;
if (!name) {
res.status(404).send("Not all needed Elements were supplied").end();
return;
}
try {
await testicle_api.CreateTopic([name, subjectID]);
res.status(204).end();
} catch (err) {
log(err, log_types.WARNING);
res.status(400).send("Not all needed elements were supplied").end();
}
});
app.put("/api/createTest", async (req, res) => {
// Assumes that the questionID is present on the front-end
const title = req.body.title;
const date = req.body.date;
const logo = req.body.logo;
const limit_mult = req.body.mult_limit == 0 ? null : req.body.mult_limit;
const limit_txt = req.body.txt_limit == 0 ? null : req.body.txt_limit;
const topics = req.body.topics;
const grading = req.body.gradingsheet;
var multiple_choice = []
if (limit_mult != null) {
multiple_choice = await testicle_api
.GetRandomMultQuestions(limit_mult, topics)
.catch((err) => {
log(err);
res.status(400).write("Limit was of unallowed size");
});
}
var text_questions = []
if (limit_txt != null) {
text_questions = await testicle_api
.GetRandomTextQuestions(limit_txt, topics)
.catch((err) => {
log(err);
res.status(400).write("Limit was of unallowed size");
});
}
const content = [title, date, logo, grading].map((element) =>
element ? element : null
);
if (!text_questions && !multiple_choice) {
res.status(400).write("Not matching questions found");
res.end();
return;
}
try {
const test_id = await testicle_api.InsertIntoDB(
globals.TEST_TN,
content,
true
);
for (let topic of topics) {
testicle_api.InsertIntoDB(globals.TOPIC_TEST_TN, [test_id, topic]);
}
if (multiple_choice) {
for (let question of multiple_choice) {
testicle_api.InsertIntoDB(globals.TEST_MULTIPLE_CHOICE_TN, [
test_id,
question["questionID"],
]);
}
}
if (text_questions) {
for (let question of text_questions) {
testicle_api.InsertIntoDB(globals.TEST_TXT_QUESTION_TN, [
test_id,
question["questionID"],
]);
}
}
log(`New test created! Name of new test: ${title}`, log_types.INFO);
res.status(204);
res.end();
} catch (err) {
log(err, log_types.WARNING);
res.status(400).write("Not all needed Elements were supplied");
res.end();
return;
}
});
app.put("/api/createGrading", async (req, res) => {
const sheet_name = req.body.sheet_name;
const grading = req.body.grading;
if (!sheet_name || !grading) {
res.status(400).send("Not all needed Elements were supplied").end();
return;
}
try {
await testicle_api.CreateGrading(sheet_name, grading);
res.status(204).end();
} catch (err) {
log(err, log_types.WARNING);
res.status(400).send("Not all needed elements were supplied").end();
}
})
app.get("/api/getGrading", async (req, res) => {
try {
let data = await testicle_api.GetGrading();
for (let element of data) {
element["Modify"] = element["ID"];
element["Delete"] = element["ID"];
}
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(data));
} catch (err) {
log(err, log_types.WARNING);
res.writeHead(400).write("Can't get from database");
}
res.end();
})
app.post("/api/modifyRandomTextQuestion", async (req, res) => {
try {
const testID = req.body.testID;
const questionID = req.body.questionID;
const resp = await testicle_api.GetRandomTextQuestionToTest(testID, questionID);
if (resp["textQuestionID"]) {
await testicle_api.DeleteEntry(globals.TEST_TXT_QUESTION_TN, { "textQuestionID": questionID, "testID": testID })
await testicle_api.InsertIntoDB(globals.TEST_TXT_QUESTION_TN, [testID, resp["textQuestionID"]])
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(resp));
} else {
res.writeHead(204).write("No matching entry found")
}
} catch (err) {
log(err);
res.writeHead(400).write("Invalid Param");
}
res.end();
});
app.post("/api/modifyRandomMult", async (req, res) => {
try {
const testID = req.body.testID;
const questionID = req.body.questionID;
const resp = await testicle_api.GetRandomMultChoiceToTest(testID, questionID);
if (resp["multipleChoiceID"]) {
await testicle_api.DeleteEntry(globals.TEST_MULTIPLE_CHOICE_TN, { "multipleChoiceID": questionID, "testID": testID });
await testicle_api.InsertIntoDB(globals.TEST_MULTIPLE_CHOICE_TN, [testID, resp["multipleChoiceID"]])
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(resp));
} else {
res.writeHead(204).write("No matching entry found")
}
} catch (err) {
log(err);
res.writeHead(400).write("Invalid Param");
}
res.end();
});
app.patch("/api/modify", async (req, res) => {
const condi = req.body.condi;
const tablename = req.body.tablename;
const attribute_change = req.body.attribute;
if (!condi || !tablename || !attribute_change) {
res.status(400).send("Not all needed Elements were supplied").end();
return;
}
try {
await testicle_api.UpdateEntry(tablename, attribute_change, condi);
res.status(204).end();
} catch (err) {
log(err, log_types.WARNING);
res
.status(404)
.send("There was an error inserting into the database")
.end();
}
});
app.delete("/api/delete", async (req, res) => {
const condi = req.body.condi;
const tablename = req.body.tablename;
if (!condi || !tablename) {
res.status(400).send("Not all needed Elements were supplied").end();
return;
}
try {
await testicle_api.DeleteEntry(tablename, condi);
res.status(204).end();
} catch (err) {
log(err, log_types.WARNING);
res
.status(404)
.send("There was an error inserting into the database")
.end();
}
});
// Normal Generation is /api/pdf/1/ (with 1 being the ID of the test)
// Correction Generation is /api/pdf/1/corrected (you can write whatever you want as second param)
app.get("/api/pdf/*/*", async (req, res) => {
const id = Number.parseInt(req.params[0].split(".")[0]);
try {
var test_body = await testicle_api.GetAllTestData(id);
} catch (err) {
log(
`An Error Occured when trying to get the body of a test. TestID: ${id}. Error: ${err}`,
log_types.ERROR
);
res.status(400).write("There is no test with the requested id");
res.end();
return;
}
if (test_body[0]) {
const pdf_content = await gen_test(test_body[0], "A4", req.params[1]).catch(
(err) => {
log(err);
res.status(404);
res.end();
return;
}
);
log(`New PDF created from test with id: ${id}`, log_types.INFO);
res.writeHead(200, PDF_HEADER);
res.write(pdf_content);
} else {
log(`Test doesnt exist`, log_types.WARNING);
res.status(404);
}
res.end();
});
app.get("/api/getSubjects", async (req, res) => {
try {
let data = await testicle_api.GetAllSubjects();
for (let element of data) {
element["Modify"] = element["ID"];
element["Delete"] = element["ID"];
}
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(data));
} catch (err) {
log(err, log_types.WARNING);
res.writeHead(400).write("Can't get from database");
}
res.end();
});
app.get("/api/getTests", async (req, res) => {
const resp = await testicle_api.GetAllTestData().catch((err) => {
log(err, log_types.ERROR);
});
if (resp) {
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(resp));
} else {
log("No Tests were found!", log_types.WARNING);
res.writeHead(400);
}
res.end();
});
app.get("/api/getTopics", async (req, res) => {
try {
let data = await testicle_api.GetAllTopics();
for (let element of data) {
element["Modify"] = element["ID"];
element["Delete"] = element["ID"];
}
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(data));
} catch (err) {
log(err, log_types.WARNING);
res.writeHead(400).write("Can't get from database");
}
res.end();
});
app.get("/api/logo/*", async (req, res) => {
const id = req.params[0].split(".")[0];
try {
var logo = await testicle_api.GetLogo(id);
} catch (err) {
res.writeHead(200).end()
return
}
try {
if (logo[0].logo == null) {
log("This Test doesn't exist or doesn't have a logo", log_types.WARNING);
res.writeHead(200).end();
return;
}
} catch (err) {
log(err, log_types.ERROR);
res.writeHead(200).end();
return
}
try {
const b64 = logo[0].logo.split(";base64,")[1];
const buffer = new Buffer.from(b64, "base64");
res.status(200).contentType("image/png").write(buffer);
}
catch (err) {
log(err)
res.writeHead(200);
}
res.end();
});
app.get("/api/getQuestions", async (req, res) => {
const resp = await testicle_api.GetAllQuestions();
if (resp) {
res.writeHead(200, JSON_HEADER);
res.write(JSON.stringify(resp));
} else {
log("No Questions were found!", log_types.WARNING);
res.writeHead(400);
}
res.end();
});
function log(message, info = log_types.ERROR) {
const log_msg = format_log(message, info);
console.log(log_msg.trim());
fs.appendFile(log_path, log_msg, function (err) {
if (err) throw err;
});
}
function format_log(message, info = log_types.ERROR) {
return `${info} ${chalk.blue(new Date().toLocaleString())} - ${message}\n`;
}
fs.mkdir("logs", (err) => {
if (err) {
log("Can't make new directory. Error: " + err, log_types.WARNING);
} else {
log("Logs directory created", log_types.INFO);
}
});
app.listen(port, (err) => {
if (err) {
log(err, log_types.ERROR);
} else {
log("Server listening on port: " + port, log_types.INFO);
}
});