'update'
[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 remainingTime: assessment.time, //integer or array
27 stage: assessment.mode != "open" ? 0 : 1,
28 warnMsg: "",
29 },
30 computed: {
31 countdown: function() {
32 const remainingTime = assessment.display == "one" && _.isArray(assessment.time)
33 ? this.remainingTime[this.answers.index]
34 : this.remainingTime;
35 let seconds = remainingTime % 60;
36 let minutes = Math.floor(remainingTime / 60);
37 return this.padWithZero(minutes) + ":" + this.padWithZero(seconds);
38 },
39 },
40 mounted: function() {
41 $(".modal").modal();
42 if (["exam","open"].includes(assessment.mode))
43 return;
44 window.addEventListener("blur", () => {
45 if (this.stage != 2)
46 return;
47 if (assessment.mode == "secure")
48 {
49 this.sendAnswer();
50 document.location.href= "/noblur";
51 }
52 else //"watch" mode
53 socket.emit(message.studentBlur, {number:this.student.number});
54 }, false);
55 if (assessment.mode == "watch")
56 {
57 window.addEventListener("focus", () => {
58 if (this.stage != 2)
59 return;
60 socket.emit(message.studentFocus, {number:this.student.number});
61 }, false);
62 }
63 window.addEventListener("resize", e => {
64 if (this.stage != 2)
65 return;
66 if (assessment.mode == "secure")
67 {
68 this.sendAnswer();
69 document.location.href = "/fullscreen";
70 }
71 else //"watch" mode
72 {
73 if (checkWindowSize())
74 socket.emit(message.studentFullscreen, {number:this.student.number});
75 else
76 socket.emit(message.studentResize, {number:this.student.number});
77 }
78 }, false);
79 },
80 methods: {
81 // In case of AJAX errors (not blur-ing)
82 showWarning: function(message) {
83 this.warnMsg = message;
84 $("#warning").modal("open");
85 },
86 padWithZero: function(x) {
87 if (x < 10)
88 return "0" + x;
89 return x;
90 },
91 // stage 0 --> 1
92 getStudent: function() {
93 $.ajax("/courses/student", {
94 method: "GET",
95 data: {
96 number: this.student.number,
97 cid: assessment.cid,
98 },
99 dataType: "json",
100 success: s => {
101 if (!!s.errmsg)
102 return this.showWarning(s.errmsg);
103 this.stage = 1;
104 this.student = s.student;
105 Vue.nextTick( () => { Materialize.updateTextFields(); });
106 },
107 });
108 },
109 // stage 1 --> 0
110 cancelStudent: function() {
111 this.stage = 0;
112 },
113 // stage 1 --> 2 (get all questions, set password)
114 startAssessment: function() {
115 let initializeStage2 = paper => {
116 $("#leftButton, #rightButton").hide();
117 // Initialize structured answer(s) based on questions type and nesting (TODO: more general)
118
119 // if display == "all" getQuestionS
120 // otherwise get first question
121
122
123 if (!!questions)
124 assessment.questions = questions;
125 this.answers.inputs = [ ];
126 for (let q of assessment.questions)
127 this.answers.inputs.push( _(q.options.length).times( _.constant(false) ) );
128 if (!paper)
129 {
130 this.answers.indices = assessment.fixed
131 ? _.range(assessment.questions.length)
132 : _.shuffle( _.range(assessment.questions.length) );
133 }
134 else
135 {
136 // Resuming
137 let indices = paper.inputs.map( input => { return input.index; });
138 let remainingIndices = _.difference( _.range(assessment.questions.length).map(String), indices );
139 this.answers.indices = indices.concat( _.shuffle(remainingIndices) );
140 }
141
142
143
144
145
146
147
148 if (assessment.time > 0)
149 {
150
151 // TODO: distinguish total exam time AND question time
152
153 const deltaTime = !!paper ? Date.now() - paper.startTime : 0;
154 this.remainingTime = assessment.time * 60 - Math.round(deltaTime / 1000);
155 this.runTimer();
156 }
157
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("/assessments/start", {
167 method: "PUT",
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
197
198 // stage 2
199 runGlobalTimer: function() {
200 if (assessment.time <= 0)
201 return;
202 let self = this;
203 setInterval( function() {
204 self.remainingTime--;
205 if (self.remainingTime <= 0)
206 {
207 if (self.stage == 2)
208 self.endAssessment();
209 clearInterval(this);
210 }
211 }, 1000);
212 },
213 runQuestionTimer: function(idx) {
214 if (assessment.questions[idx].time <= 0)
215 return;
216 let self = this; //TODO: question remaining time
217 setInterval( function() {
218 self.remainingTime--;
219 if (self.remainingTime <= 0)
220 {
221 if (self.stage == 2)
222 self.endAssessment();
223 clearInterval(this);
224 }
225 }, 1000);
226 },
227
228 //TODO: get question after sending answer
229
230 // stage 2
231 sendOneAnswer: function() {
232 const realIndex = this.answers.indices[this.answers.index];
233 let gotoNext = () => {
234 if (this.answers.index == assessment.questions.length - 1)
235 this.endAssessment();
236 else
237 this.answers.index++;
238 this.$children[0].$forceUpdate(); //TODO: bad HACK, and shouldn't be required...
239 };
240 if (assessment.mode == "open")
241 return gotoNext(); //only local
242 let answerData = {
243 aid: assessment._id,
244 answer: JSON.stringify({
245 index: realIndex.toString(),
246 input: this.answers.inputs[realIndex]
247 .map( (tf,i) => { return {val:tf,idx:i}; } )
248 .filter( item => { return item.val; })
249 .map( item => { return item.idx; })
250 }),
251 number: this.student.number,
252 password: this.student.password,
253 };
254 $.ajax("/assessments/answer", {
255 method: "PUT",
256 data: answerData,
257 dataType: "json",
258 success: ret => {
259 if (!!ret.errmsg)
260 return this.showWarning(ret.errmsg);
261 gotoNext();
262 socket.emit(message.newAnswer, answerData);
263 },
264 });
265 },
266 // TODO: I don't like that + sending should not be definitive in exam mode with display = all
267 sendAnswer: function() {
268 if (assessment.display == "one")
269 this.sendOneAnswer();
270 else
271 assessment.questions.forEach(this.sendOneAnswer);
272 },
273 // stage 2 --> 3 (or 4)
274 // from a message by statements component, or time over
275 endAssessment: function() {
276 // Set endTime, destroy password
277 $("#leftButton, #rightButton").show();
278 if (assessment.mode == "open")
279 {
280 this.stage = 4;
281 this.answers.showSolution = true;
282 this.answers.displayAll = true;
283 return;
284 }
285 $.ajax("/assessments/end", {
286 method: "PUT",
287 data: {
288 aid: assessment._id,
289 number: this.student.number,
290 password: this.student.password,
291 },
292 dataType: "json",
293 success: ret => {
294 if (!!ret.errmsg)
295 return this.showWarning(ret.errmsg);
296 this.stage = 3;
297 delete this.student["password"]; //unable to send new answers now
298 },
299 });
300 },
301 // stage 3 --> 4 (on socket message "feedback")
302 setAnswers: function(m) {
303 const answers = JSON.parse(m.answers);
304 for (let i=0; i<answers.length; i++)
305 assessment.questions[i].answer = answers[i];
306 this.answers.showSolution = true;
307 this.answers.displayAll = true;
308 this.stage = 4;
309 socket.disconnect();
310 socket = null;
311 },
312 },
313 });