342e96308e2422ca4ea62a345e97eecfa6bb8c1d
[qomet.git] / public / javascripts / assessment.js
1 let socket = null; //monitor answers in real time
2
3 if (assessment.mode == "secure" && !checkWindowSize())
4 document.location.href= "/fullscreen";
5
6 function checkWindowSize()
7 {
8 // NOTE: temporarily accept smartphone (security hole: pretend being a smartphone on desktop browser...)
9 if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/))
10 return true;
11 // 3 is arbitrary, but a small tolerance is required (e.g. in Firefox)
12 return window.innerWidth >= screen.width-3 && window.innerHeight >= screen.height-3;
13 };
14
15 new Vue({
16 el: "#assessment",
17 data: {
18 assessment: assessment,
19 answers: { }, //filled later with answering parameters
20 student: { }, //filled later (name, password)
21 // Stage 0: unauthenticated (number),
22 // 1: authenticated (got a name, unvalidated)
23 // 2: locked: password set, exam started
24 // 3: completed
25 // 4: show answers
26 stage: assessment.mode != "open" ? 0 : 1,
27 remainingTime: 0, //global, in seconds
28 warnMsg: "",
29 },
30 computed: {
31 countdown: function() {
32 let seconds = this.remainingTime % 60;
33 let minutes = Math.floor(this.remainingTime / 60);
34 return this.padWithZero(minutes) + ":" + this.padWithZero(seconds);
35 },
36 showAnswers: function() {
37 return this.stage == 4;
38 },
39 },
40 mounted: function() {
41 $(".modal").modal();
42 if (assessment.mode != "open")
43 {
44 window.addEventListener("keydown", e => {
45 // Ignore F12 (avoid accidental window resize due to devtools)
46 // NOTE: in Chromium at least, fullscreen mode exit with F11 cannot be prevented.
47 // Workaround: disable key at higher level. Possible xbindkey config:
48 // "false"
49 // m:0x10 + c:95
50 // Mod2 + F11
51 if (e.keyCode == 123)
52 e.preventDefault();
53 }, false);
54 }
55 window.addEventListener("blur", () => {
56 if (!socket)
57 return;
58 if (assessment.mode == "secure")
59 {
60 this.trySendCurrentAnswer();
61 document.location.href= "/noblur";
62 }
63 else if (assessment.mode == "exam")
64 socket.emit(message.studentBlur, {number:this.student.number});
65 }, false);
66 if (assessment.mode == "exam")
67 {
68 window.addEventListener("focus", () => {
69 if (!socket)
70 return;
71 socket.emit(message.studentFocus, {number:this.student.number});
72 }, false);
73 }
74 window.addEventListener("resize", e => {
75 if (!socket)
76 return;
77 if (assessment.mode == "secure")
78 {
79 this.trySendCurrentAnswer();
80 document.location.href= "/fullscreen";
81 }
82 else if (assessment.mode == "exam")
83 {
84 if (checkWindowSize())
85 socket.emit(message.studentFullscreen, {number:this.student.number});
86 else
87 socket.emit(message.studentResize, {number:this.student.number});
88 }
89 }, false);
90 },
91 methods: {
92 // In case of AJAX errors
93 showWarning: function(message) {
94 this.warnMsg = message;
95 $("#warning").modal("open");
96 },
97 padWithZero: function(x) {
98 if (x < 10)
99 return "0" + x;
100 return x;
101 },
102 trySendCurrentAnswer: function() {
103 if (this.stage == 2)
104 this.sendAnswer();
105 },
106 // stage 0 --> 1
107 getStudent: function(cb) {
108 $.ajax("/get/student", {
109 method: "GET",
110 data: {
111 number: this.student.number,
112 cid: assessment.cid,
113 },
114 dataType: "json",
115 success: s => {
116 if (!!s.errmsg)
117 return this.showWarning(s.errmsg);
118 this.stage = 1;
119 this.student = s.student;
120 Vue.nextTick( () => { Materialize.updateTextFields(); });
121 if (!!cb)
122 cb();
123 },
124 });
125 },
126 // stage 1 --> 0
127 cancelStudent: function() {
128 this.stage = 0;
129 },
130 // stage 1 --> 2 (get all questions, set password)
131 startAssessment: function() {
132 let initializeStage2 = (questions,paper) => {
133 $("#leftButton, #rightButton").hide();
134 if (assessment.time > 0)
135 {
136 const deltaTime = !!paper ? Date.now() - paper.startTime : 0;
137 this.remainingTime = assessment.time * 60 - Math.round(deltaTime / 1000);
138 this.runTimer();
139 }
140 // Initialize structured answer(s) based on questions type and nesting (TODO: more general)
141 if (!!questions)
142 assessment.questions = questions;
143 this.answers.inputs = [ ];
144 for (let q of assessment.questions)
145 this.answers.inputs.push( _(q.options.length).times( _.constant(false) ) );
146 if (!paper)
147 {
148 this.answers.indices = assessment.fixed
149 ? _.range(assessment.questions.length)
150 : _.shuffle( _.range(assessment.questions.length) );
151 }
152 else
153 {
154 // Resuming
155 let indices = paper.inputs.map( input => { return input.index; });
156 let remainingIndices = _.difference( _.range(assessment.questions.length).map(String), indices );
157 this.answers.indices = indices.concat( _.shuffle(remainingIndices) );
158 }
159 this.answers.index = !!paper ? paper.inputs.length : 0;
160 this.answers.displayAll = assessment.display == "all";
161 this.answers.showSolution = false;
162 this.stage = 2;
163 };
164 if (assessment.mode == "open")
165 return initializeStage2();
166 $.ajax("/start/assessment", {
167 method: "GET",
168 data: {
169 number: this.student.number,
170 aid: assessment._id
171 },
172 dataType: "json",
173 success: s => {
174 if (!!s.errmsg)
175 return this.showWarning(s.errmsg);
176 if (!!s.paper)
177 {
178 // Resuming: receive stored answers + startTime
179 this.student.password = s.paper.password;
180 this.answers.inputs = s.paper.inputs.map( inp => { return inp.input; });
181 }
182 else
183 {
184 this.student.password = s.password;
185 // Got password: students answers locked to this page until potential teacher
186 // action (power failure, computer down, ...)
187 }
188 socket = io.connect("/", {
189 query: "aid=" + assessment._id + "&number=" + this.student.number + "&password=" + this.student.password
190 });
191 socket.on(message.allAnswers, this.setAnswers);
192 initializeStage2(s.questions, s.paper);
193 },
194 });
195 },
196 // stage 2
197 runTimer: function() {
198 if (assessment.time <= 0)
199 return;
200 let self = this;
201 setInterval( function() {
202 self.remainingTime--;
203 if (self.remainingTime <= 0)
204 {
205 if (self.stage == 2)
206 self.endAssessment();
207 clearInterval(this);
208 }
209 }, 1000);
210 },
211 // stage 2
212 sendOneAnswer: function() {
213 const realIndex = this.answers.indices[this.answers.index];
214 let gotoNext = () => {
215 if (this.answers.index == assessment.questions.length - 1)
216 this.endAssessment();
217 else
218 this.answers.index++;
219 this.$children[0].$forceUpdate(); //TODO: bad HACK, and shouldn't be required...
220 };
221 if (assessment.mode == "open")
222 return gotoNext(); //only local
223 let answerData = {
224 aid: assessment._id,
225 answer: JSON.stringify({
226 index: realIndex.toString(),
227 input: this.answers.inputs[realIndex]
228 .map( (tf,i) => { return {val:tf,idx:i}; } )
229 .filter( item => { return item.val; })
230 .map( item => { return item.idx; })
231 }),
232 number: this.student.number,
233 password: this.student.password,
234 };
235 $.ajax("/send/answer", {
236 method: "GET",
237 data: answerData,
238 dataType: "json",
239 success: ret => {
240 if (!!ret.errmsg)
241 return this.showWarning(ret.errmsg);
242 gotoNext();
243 socket.emit(message.newAnswer, answerData);
244 },
245 });
246 },
247 // TODO: I don't like that + sending should not be definitive in exam mode with display = all
248 sendAnswer: function() {
249 if (assessment.display == "one")
250 this.sendOneAnswer();
251 else
252 assessment.questions.forEach(this.sendOneAnswer);
253 },
254 // stage 2 --> 3 (or 4)
255 // from a message by statements component, or time over
256 endAssessment: function() {
257 // Set endTime, destroy password
258 $("#leftButton, #rightButton").show();
259 if (assessment.mode == "open")
260 {
261 this.stage = 4;
262 this.answers.showSolution = true;
263 this.answers.displayAll = true;
264 return;
265 }
266 $.ajax("/end/assessment", {
267 method: "GET",
268 data: {
269 aid: assessment._id,
270 number: this.student.number,
271 password: this.student.password,
272 },
273 dataType: "json",
274 success: ret => {
275 if (!!ret.errmsg)
276 return this.showWarning(ret.errmsg);
277 assessment.conclusion = ret.conclusion;
278 this.stage = 3;
279 delete this.student["password"]; //unable to send new answers now
280 },
281 });
282 },
283 // stage 3 --> 4 (on socket message "feedback")
284 setAnswers: function(m) {
285 const answers = JSON.parse(m.answers);
286 for (let i=0; i<answers.length; i++)
287 assessment.questions[i].answer = answers[i];
288 this.answers.showSolution = true;
289 this.answers.displayAll = true;
290 this.stage = 4;
291 socket.disconnect();
292 socket = null;
293 },
294 },
295 });