-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
263 lines (228 loc) · 9.97 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
const express = require('express')
const path = require('path')
const API = require('./database')
const crypto = require('crypto')
const db = new API()
const app = express()
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser");
const multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './public/facename/assets')
},
filename: async function(req, file, cb) {
cb(null, (req.body.gender.toLowerCase()) + (await db.fetch_lastimg((req.body.gender).toLowerCase())) + ".jpg")
}
})
const upload = multer({ storage: storage })
const oneDay = 1000 * 60 * 60 * 24;
app.set("view engine", "ejs");
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(require("express-session")({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
cookie: { maxAge: oneDay }
}));
app.use(express.static(path.join(__dirname, '/public')));
let allImages = [],
names = [],
affiliations = [];
async function fetchAllData() {
const imageData = await db.fetchFaceData();
console.log("Final image data: ", imageData);
for (let i = 0; i < imageData.length; i++) {
allImages.push(imageData[i].imageID);
names.push(imageData[i].name);
affiliations.push(imageData[i].affiliation);
}
}
fetchAllData();
function scoreAnswers(correctAnswers, userAnswers) {
let correct = 0;
for (let i = 0; i < correctAnswers.length; i++) {
if (correctAnswers[i].toLowerCase() == userAnswers[i].toLowerCase()) correct++;
}
return correct;
}
function scoreBoth(userAnswersNames, userAnswersAffn) {
let correct = 0;
for (let i = 0; i < userAnswersNames.length; i++) {
let name = names[i], affn = affiliations[i];
if(name && affn) {
name = name.toLowerCase()
affn = affn.toLowerCase()
if (userAnswersNames[i].toLowerCase() == name && userAnswersAffn[i].toLowerCase() == affn) correct++;
}
}
return correct;
}
function scoreRecall(correctAnswers, userAnswers) {
let correct = 0;
correctAnswers = correctAnswers.map(name => name.toLowerCase());
userAnswers = userAnswers.map(name => name.toLowerCase());
for (let i = 0; i < correctAnswers.length; i++) {
if (userAnswers.includes(correctAnswers[i])) correct++;
}
return correct;
}
function convertStringToArray(text) {
let userAnswers = text.replace(/(\r\n|\n|\r)/gm, ",");
userAnswers = userAnswers.split(",");
console.log("User Answers: ", userAnswers)
return userAnswers;
}
//GET REQUESTS
app.get("/adminPanel.html", function(req, res) {
res.redirect("/admin")
})
app.use('/corsiblocktapping', require('./corsi/server'));
app.get('/face-name', async function(req, res) {
//TODO: after development, prevent this page being directly accessed before filling form.
res.render('instructions', { redirectURL: "/displayFaces", content: "You will be shown images of people. Observe and remember the faces. You will get time of 2 seconds per face." });
});
app.get('/', function(req, res) {
res.render("input_page")
});
app.get("/namesTest1", function(req, res) {
res.render("names", { formSubmitURL: "/names/test1" });
});
app.get("/namesTest2", function(req, res) {
res.render("names", { formSubmitURL: "/names/test2" });
});
app.get("/displayFaces", function(req, res) {
res.render('displayFaces.ejs', { redirectURL: "/instructionsNames", images: allImages, figcaptions: [] });
})
app.get("/displayNames", function(req, res) {
res.render('displayNames.ejs', { redirectURL: "/nameTest", images: allImages, figcaptions: names });
})
app.get("/displayAffn", function(req, res) {
res.render('displayAffn.ejs', { redirectURL: "/affnTest", images: allImages, figcaptions: affiliations });
})
app.get("/instructionsNames", function(req, res) {
res.render("instructions", { redirectURL: "/displayNames", content: "You will be shown names of people. Observe and remember the faces and their names. You will get time of 2 seconds per face." })
})
app.get("/instructionsAffn", function(req, res) {
res.render("instructions", { redirectURL: "/displayAffn", content: "You will be shown affiliations of people. Observe and remember the faces and their affiliations. You will get time of 2 seconds per face." })
})
app.get("/nameTest", function(req, res) {
res.render('oneInputTest.ejs', { redirectURL: "/displayAffn", images: allImages, functionality: "Name" });
})
app.get("/affnTest", function(req, res) {
res.render('oneInputTest.ejs', { images: allImages, functionality: "Occupation" });
})
//TODO: The following two lines can be deleted?
app.get("/allTest1", function(req, res) {
res.render('twoInputTest.ejs', { images: allImages, redirectURL: "/wait", formSubmitURL: "/allTest/userAnswers/test1" });
})
app.get("/allTest2", function(req, res) {
res.render('twoInputTest.ejs', { images: allImages, redirectURL: "/results", formSubmitURL: "/allTest/userAnswers/test2" });
}) //for now after test completion, redirect to home page
app.get("/admin", function(req, res) {
res.sendFile('adminLogin.html', { root: './public/' })
})
app.get("/wait", function(req, res) {
res.render('waitScreen.ejs', { redirectURL: "/namesTest2" })
});
app.get("/instructionsAffn", function(req, res) {
res.render("instructions", { redirectURL: "/displayAffn", content: "You will be shown affiliations of people. Observe and remember the faces and their affiliations. You will get time of 2 seconds per face." })
});
// adding image page from admin side
app.get('/add_image', function(req, res) {
res.render("add_image");
});
app.get('/results', async function(req, res) {
const facenameResults = await db.fetchFaceNameResults(req.session.participantID);
// const facenameResults = await db.fetchFaceNameResults(169)
console.log("Facename scores fetched: ", facenameResults)
res.render("resultScreen", {results: facenameResults[0]});
});
//POST REQUESTS
app.post("/", async function(req, res) {
const formdata = req.body
participantID = await db.newParticipant(formdata);
req.session.participantID = participantID;
res.render("main_page")
});
app.post("/names/test1", function(req, res) {
let userAnswers = convertStringToArray(req.body.names);
const score = scoreRecall(names, userAnswers)
db.updateScore(req.session.participantID, 'recallNames_1', score);
res.render("occupations", { formSubmitURL: "/occupationsTestPost1" });
});
app.post("/names/test2", function(req, res) {
let userAnswers = convertStringToArray(req.body.names);
const score = scoreRecall(names, userAnswers)
db.updateScore(req.session.participantID, 'recallNames_2', score);
res.render("occupations", { formSubmitURL: "/occupationsTestPost2" });
})
app.post("/occupationsTestPost1", async function(req, res) {
let userAnswers = convertStringToArray(req.body.occupations);
const score = scoreRecall(affiliations, userAnswers)
db.updateScore(req.session.participantID, 'recallAffn_1', score);
res.render('twoInputTest.ejs', { images: allImages, redirectURL: "/wait", formSubmitURL: "/allTest/userAnswers/test1" });
});
app.post("/occupationsTestPost2", async function(req, res) {
let userAnswers = convertStringToArray(req.body.occupations)
const score = scoreRecall(affiliations, userAnswers)
db.updateScore(req.session.participantID, 'recallAffn_2', score)
res.render('twoInputTest.ejs', { images: allImages, redirectURL: "/results", formSubmitURL: "/allTest/userAnswers/test2" });
});
app.post("/login", async function(req, res) {
const formdata = req.body
const username = formdata.username,
pwd = formdata.password,
hashingKey = process.env.HASHING_KEY;
const hashedpwd = crypto.createHmac('sha256', hashingKey).update(pwd).digest('hex');
const pwdcheck = await db.checkAdmin(username, hashedpwd);
if (pwdcheck) {
res.sendFile('adminPanel.html', { root: './public/' })
} else {
res.send("Wrong username or password")
}
})
app.post("/nameTest/userAnswers", function(req, res) {
console.log("User's answers: ", req.body);
const score = scoreAnswers(names, req.body.userAnswers);
db.updateScore(req.session.participantID, 'cuedRecall_name', score);
res.send("Success")
})
app.post("/affnTest/userAnswers", function(req, res) {
console.log("User's answers: ", req.body);
const score = scoreAnswers(affiliations, req.body.userAnswers);
db.updateScore(req.session.participantID, 'cuedRecall_affn', score);
res.send("Success")
})
app.post("/allTest/userAnswers/test1", function(req, res) {
console.log("User's answers for test1: ", req.body);
const userAnswerNames = req.body.userAnswers[0],
userAnswerAffn = req.body.userAnswers[1];
const score = scoreBoth(userAnswerNames, userAnswerAffn);
db.updateScore(req.session.participantID, 'cuedRecallAll_1', score);
res.send("Success")
})
app.post("/allTest/userAnswers/test2", function(req, res) {
console.log("User's answers for test2: ", req.body);
const userAnswerNames = req.body.userAnswers[0],
userAnswerAffn = req.body.userAnswers[1];
const score = scoreBoth(userAnswerNames, userAnswerAffn);
db.updateScore(req.session.participantID, 'cuedRecallAll_2', score);
res.send("Success")
})
app.use('/public/facename/assets', express.static('public'));
app.post('/add_img', upload.single('profile-file'), async function(req, res, next) {
const obj = JSON.parse(JSON.stringify(req.body));
console.log(obj);
var num = await db.fetch_lastimg((obj.gender).toLowerCase());
var img_num = (obj.gender.toLowerCase()) + num + ".jpeg";
var num2 = await db.update_lastimg((obj.gender).toLowerCase(), num + 1);
imgID = await db.addNewFace(img_num, obj.name, obj.affiliation);
// console.log("Image data is: ", imgID);
res.render("completed");
});
var port = Number(process.env.PORT || 8080);
app.listen(port);
console.log("App running at port", port);