This repository has been archived by the owner on Jun 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
431 lines (366 loc) · 10.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
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
// @ts-check
const express = require("express");
const bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
//Express is a package that makes server side a lot easier.
const app = express();
const database = require("./database");
const { texts } = require("./texts");
app.use(cookieParser()); // To access cookies quickly
//This line is to ensure that getting info from a HTML form is easier. (will see later)
app.use(
bodyParser.urlencoded({
extended: true,
})
);
//Shows app where to see for static content(Css,images etc)
// @ts-ignore
app.use(express.static(__dirname + "/public"));
//Sets the view engine to EJS which makes data exchanging through back-end and front-end a lot easier.
app.set("view engine", "ejs");
// Log any requests
app.use((req, res, next) => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${req.method} ${req.path}`);
next();
});
//Main route, this function is executed when the user goes on the main URL (In our case localhost:3000)
app.get("/", function (req, res) {
//When the user goes on / then render the main.ejs file(found on views.)
res.render("main");
});
/**
* The stored state & state transitions that are managed via a cookie.
*
* States:
* * null: initial state
* * demographic: user has given consent and is now answering background questions
* * tutorial: user is now in tutorial
* * reading: user is in the phase where they read text snippets
* * finished: user has completed the experiment
*
* @typedef {null | 'demographic' | 'tutorial' | 'reading' | 'finished'} State
*/
class UserState {
constructor() {
/**
* the user ID
* @type {string}
*/
this.uid = [Date.now(), 0 | (1e6 * Math.random())].join(".");
/**
* the state of this user
* @type {State}
*/
this.state = null;
/**
* the order of text snippets
* @type {number[]}
*/
// @ts-ignore
this.textOrder = shuffle([...texts.keys()]);
/**
* the number of the next text snippet to be read
* @type {number}
*/
this.index = 0;
/**
* the last speed that was manually selected
*/
this.speed = 300;
}
/**
* map the user state to a cookie value
* @returns {object}
*/
toCookie() {
let { uid, state, textOrder, index, speed } = this;
return { uid, state, textOrder, index, speed };
}
/**
* hydrate the state from a cookie value
* @param {object} cookie
*/
fromCookie(cookie) {
this.uid = cookie.uid || this.uid;
this.state = cookie.state || this.state;
this.textOrder = cookie.textOrder || this.textOrder;
this.index = cookie.index || this.index;
this.speed = cookie.speed || this.speed;
}
currentText() {
if (this.state !== "reading") return null;
return texts[this.textOrder[this.index]];
}
nextText() {
this.index++;
if (this.index >= this.textOrder.length) this.state = "finished";
}
}
/** state assertions that guard some of the below routes.
* Certain states force a particular route.
* @type {() => (req, res, next) => any}
*/
const ensureState = () => (req, res, next) => {
const state = (req.state = new UserState());
state.fromCookie(req.cookies["Information"] || {});
// no state? Get consent.
if (!state.state && req.path !== "/consent") return res.redirect("/consent");
// demographics?
if (state.state === "demographic" && req.path !== "/demographic")
return res.redirect("/demographic");
// tutorial?
if (state.state === "tutorial" && !req.path.startsWith("/tutorial/"))
return res.redirect("/tutorial/1");
// reading?
if (state.state === "reading" && req.path !== "/text-snippet")
return res.redirect("/text-snippet");
// finished? Really stay finished.
if (state.state === "finished" && req.path !== "/finished")
return res.redirect("/finished");
return next();
};
// no preconditions, can always start anew
app.get("/consent", (req, res) => {
res.render("consent");
});
app.post("/consent", (req, res) => {
const consent = req.body.consent;
if (consent !== "on") {
return res.redirect("/consent");
}
// the user has given consent, so initialize the state
const state = new UserState();
state.state = "demographic";
res.cookie("Information", state.toCookie());
return res.redirect("/demographic");
});
const DEMOGRAPHIC_DEFAULT = {
ageRange: null,
englishLevel: null,
vision: null,
source: null,
rsvpExperience: null,
device: null,
light: null,
};
app.get("/demographic", ensureState(), (req, res) => {
res.render("demographic", { currentValues: DEMOGRAPHIC_DEFAULT, message: null });
});
app.post("/demographic", ensureState(), async (req, res) => {
/** @type {UserState} */
const state = req.state;
const params = { ...DEMOGRAPHIC_DEFAULT, ...req.body };
var {
ageRange,
englishLevel,
vision,
source,
rsvpExperience,
device,
light,
} = params;
if (
!ageRange ||
!englishLevel ||
!vision ||
!source ||
!rsvpExperience ||
!device ||
!light
) {
res.status(400);
res.render("demographic", {
message: "please answer all questions or select “prefer not to answer”.",
currentValues: params,
});
return;
}
const saveDemographic = database.saveDemographic({
uid: state.uid,
date: new Date(),
ageRange,
englishLevel,
vision,
source,
rsvpExperience,
device,
light,
});
const saveTextOrder = database.saveTextOrder({
uid: state.uid,
textOrder: state.textOrder,
});
await saveDemographic;
await saveTextOrder;
state.state = "tutorial";
res.cookie("Information", state.toCookie());
res.redirect("/tutorial/1");
});
app.get("/tutorial/1", ensureState(), (req, res) => {
res.render("tutorial-1");
});
app.get("/tutorial/2", ensureState(), (req, res) => {
res.render("tutorial-2");
});
app.get("/tutorial/3", ensureState(), (req, res) => {
res.render("tutorial-3");
});
app.post("/tutorial/done", ensureState(), (req, res) => {
/** @type {UserState} */
const state = req.state;
state.state = "reading";
res.cookie("Information", state.toCookie());
return res.redirect("/text-snippet");
});
// This route contains the main evaluation:
// first show one of the text snippets with RSVP,
// then ask the comprehension question.
app.get("/text-snippet", ensureState(), function (req, res) {
/** @type {UserState} */
const state = req.state;
const textEntry = state.currentText();
let speed = state.speed;
let {
automaticSpeed,
text: inputText,
speed: speedBasedOnComplexity,
score: textComplexityScore,
question,
} = textEntry;
if (automaticSpeed) {
speed = Math.round(speedBasedOnComplexity);
console.log(
`Complexity Score = ${Math.round(textComplexityScore)}\n` +
`AutomatedSpeed = ${speed}`
);
}
//renders text-snippet.ejs and passes the text to be RSVP-rendered
res.render("text-snippet", {
text: `${inputText} Question: ${question}`,
speed,
id: state.index,
taskNumber: state.index + 1,
taskTotal: state.textOrder.length,
});
});
app.post("/text-snippet", ensureState(), async (req, res) => {
/** @type {UserState} */
const state = req.state;
// extract form data
try {
var {
id,
faster,
slower,
pause,
forward,
rewind,
elapsedSeconds: time,
speed: lastSpeed,
question: answer,
} = req.body;
} catch (err) {
if (err instanceof TypeError) return res.sendStatus(400);
throw err;
}
await database.saveAnswer({
uid: state.uid,
date: new Date(),
passage: id,
position: state.index + 1,
answer,
readingDuration: time,
interactions: {
slower,
faster,
pause,
forward,
rewind,
},
});
state.nextText(); // mark this text passage as completed
// was a new speed manually selected?
if (faster || slower) state.speed = lastSpeed;
res.cookie("Information", state.toCookie());
// go to next text snippet, or to finished page
res.redirect("/text-snippet");
});
app.get("/finished", ensureState(), (req, res) => {
return res.render("finished");
});
// bugfix to get text order
app.get("/bugfix-ids", async (req, res) => {
const state = req.cookies["Information"];
if (state && state.uid && state.textOrder) {
await database.saveTextOrder({
uid: state.uid,
textOrder: state.textOrder,
});
}
res.status(200)
.type('html')
.send("<p>Thank you! <p><a href='/'>back to start page</a>");
});
/**
* Implement HTTP Basic Authentication.
*
* Credentials `user:pass` are taken from `DOWNLOAD_CREDENTIALS` env variable
*/
const ensureDownloadAuthorization = () => (req, res, next) => {
const credentials = process.env.DOWNLOAD_CREDENTIALS;
const expectedAuthorization =
"Basic " + Buffer.from(credentials, "utf8").toString("base64");
if (credentials && req.headers.authorization === expectedAuthorization)
return next();
res.set("WWW-Authenticate", 'Basic realm="research data download"');
res.status(401);
res.send("data download requires authorization token");
};
app.get(
"/download/answers",
ensureDownloadAuthorization(),
async (req, res) => {
const data = await database.getAllAnswers();
return res.json(data);
}
);
app.get(
"/download/demographics",
ensureDownloadAuthorization(),
async (req, res) => {
const data = await database.getAllDemographics();
return res.json(data);
}
);
app.get(
"/download/text-order",
ensureDownloadAuthorization(),
async (req, res) => {
const data = await database.getAllTextOrders();
return res.json(data);
}
);
/**
* Shuffle the array *in place* and return it.
*/
function shuffle(array) {
// Fisher-Yates shuffle
// <https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i);
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
const server = app.listen(3000, () =>
console.log("The application started on port 3000")
);
process.on("SIGTERM", () => {
console.log("Shutdown initiated.");
server.close(() => {
console.log("Shutdown complete.");
});
});