-
Notifications
You must be signed in to change notification settings - Fork 2
/
consumer.js
1926 lines (1590 loc) · 71.7 KB
/
consumer.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("dotenv").config();
const Logger = require("./logger.js");
const Session = require("./models/Session.js");
const User = require("./models/User.js");
const Room = require("./models/Room.js");
const Test = require("./models/Test.js");
const { SystemConfig } = require("./models/SystemConfig.js");
const { dbg } = require("./logger.js");
const { get } = require("mongoose");
const axios = require("axios");
const diff = require("diff");
let uids = new Map();
let rooms = new Map();
let sessions = new Map();
let tokens = new Map();
let connectedUsers = new Map();
let userToSocketID = new Map();
let lastSessionEvent = new Map();
let threadforUser = new Map();
//A function to parse an entrance into a json
function toJSON(obj) {
return JSON.stringify(obj, null, 2);
}
async function sendMsgToLeia(pack, subject, room, bot, exerciseCounter, testCounter, pLanguage, waitTime, io) {
const systemConfig = await SystemConfig.findOne({
environment: process.env.NODE_ENV,
});
const startTime = new Date().getTime();
const language = systemConfig.language?systemConfig.language:"en";
url = process.env.LEIA_API_URL + `/api/v1/session/${subject}/room/${room}/events?lang=` + language + `&type=${pLanguage}`;
Logger.dbg("Send Message To LEIA - URL <" + url + ">");
axios.post(url, {
eventType: "message",
eventContent: {
code: pack.data.code,
message: pack.data.message,
question: pack.data.exercise,
gender: bot.gender
}},
{
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.LEIA_API_KEY
}
})
.then((response) => {
const endTime = new Date().getTime();
const elapsedTime = endTime - startTime;
Logger.dbg("Response from LEIA - " + JSON.stringify(response.data, null, 2));
if(response.data.message) {
pack.data.message = response.data.message;
// Time to think the message and type, plus the time to read the message
waitTime += parseInt(response.data.message.length) * 300 + 500;
Logger.dbg("Send Message To LEIA - TOTAL BOT WAIT TIME <" + waitTime + ">");
Logger.dbg("Send Message To LEIA - RESPONSE ELAPSED TIME <" + elapsedTime + ">");
pack.uid = "LEIA";
if (waitTime < elapsedTime) {
Logger.dbg("Send Message To LEIA - RESPONSE TIME <Sending immediately>");
io.sockets.emit("msg", pack);
} else {
const diff = waitTime - elapsedTime;
Logger.dbg("Send Message To LEIA - RESPONSE TIME <Sending in " + diff + " ms>");
setTimeout(() => {
io.sockets.emit("msg", pack);
}, diff);
}
Logger.log(
"Chat",
bot.code,
response.data.message,
exerciseCounter,
testCounter
);
}
if(response.data.code) {
pack.data.changes = getChanges(pack.data.code, response.data.code);
pack.uid = "LEIA";
io.sockets.emit("leiaCode", pack);
}
})
.catch((error) => {
Logger.dbgerr("Send Message To LEIA - ERROR <" + error + ">");
});
}
function getChanges(code1, code2) {
const differences = diff.diffChars(code1, code2);
const dmp = diff.convertChangesToDMP(differences);
const dmpCharByChar = dmp.flatMap((change) => {
const [op, text] = change;
return [...text].map((char) => [op, char]);
});
return dmpCharByChar;
}
//A simple wait function to wait a specified period of ms
async function wait(ms) {
await setTimeout(() => { }, ms);
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min));
}
// Fisher yates-shuffle to randomize an array --> https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
function shuffleArray(array) {
let i = array.length;
while (i--) {
const ri = Math.floor(Math.random() * i);
[array[i], array[ri]] = [array[ri], array[i]];
}
return array;
}
//A function to test if user has finished or to bring him/her a new exercise
async function exerciseTimeUp(id, description) {
Logger.dbg("Friend " + id + " is out of time!");
const user = await User.findOne({
socketId: id,
environment: process.env.NODE_ENV,
});
if (user) {
const room = await Room.findOne({
session: user.subject,
name: user.room.toString(),
environment: process.env.NODE_ENV,
});
if (room) {
const test = await Test.findOne({
orderNumber: room.currentTest,
environment: process.env.NODE_ENV,
session: user.subject,
});
//Until here, the function looks for an user, coinciding with id. Looks for his/her room and the test in which he/she is
const exercise = test.exercises[room.lastExercise];
//Tries a new exercise, if there's no more on the test, tries a new test
if (exercise) {
//If there is 1 more exercise on the test, user picks it
if (test.exercises[room.lastExercise + 1]) {
Logger.dbg("They are going to the next exercise");
room.lastExercise += 1;
await room.save();
} else { //if not, picks another test
const nextTest = await Test.findOne({
orderNumber: room.currentTest + 1,
environment: process.env.NODE_ENV,
session: user.subject,
});
//If there is a new test, it starts in the first exercise
if (nextTest) {
Logger.dbg("They got a new test (Prueba)");
room.lastExercise = 0;
room.test += 1;
await room.save();
} else { //If there isn't, it indicates the room has finished
Logger.dbg("They finished");
room.finished = true;
await room.save();
}
}
}
}
}
}
function getNextExerciseNumber(participant, listExercises) {
Logger.dbg(`getExercise - ${participant.code} - Init - for code ${participant.code}`);
var num2Send = null;
if (listExercises[0].type == "PAIR") {
Logger.dbg(`getExercise - ${participant.code} - <${listExercises[0].type}> exercise`);
num2Send = participant.visitedPExercises.length;
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> DEFAULT`);
if (!participant.exerciseSwitch) {
Logger.dbg(`getExercise - ${participant.code} - switch for ${participant.code} is <${participant.exerciseSwitch}>`);
num2Send += listExercises.length / 2;
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> UPDATE `);
}
if (num2Send >= listExercises.length) {
Logger.dbg(`getExercise - ${participant.code} - num2send Overflow (${num2Send} >= ${listExercises.length}) (no more available exercises) `);
num2Send -= 1;
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> UPDATE `);
}
} else {
Logger.dbg(`getExercise - ${participant.code} - <${listExercises[0].type}> exercise`);
num2Send = randomNumber(0, listExercises.length);
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> DEFAULT (random between 0 and ${listExercises.length})`);
if (participant.visitedIExercises.length < listExercises.length) {
Logger.dbg(`getExercise - ${participant.code} - (${participant.visitedIExercises.length} < ${listExercises.length}) (there are available exercises) `);
while(participant.visitedIExercises.includes(num2Send)) {
Logger.dbg(`getExercise - ${participant.code} - num2send already visited`);
num2Send = randomNumber(0, listExercises.length);
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> UPDATED (random between 0 and ${listExercises.length})`);
}
}
}
Logger.dbg(`getExercise - ${participant.code} - num2send = <${num2Send}> FINAL `);
return num2Send;
}
async function executeStandardSession(session, io) {
if (!session) {
Logger.dbg("ExecuteStandardSession - Session not found");
return;
}
var sessionName = session.name;
session.running = true;
session.save(); //Saves it on database
Logger.dbg("executeStandardSession - Running ", session, ["name", "pairingMode", "tokenPairing", "blindParticipant"]);
//Pick all tests
const tests = await Test.find({
session: session.name,
environment: process.env.NODE_ENV,
}).sort({ orderNumber: 1 });
if (tests.length == 0) {
Logger.dbg("executeStandardSession - No tests found");
return;
}
Logger.dbg("executeStandardSession - tests found", tests);
//Number of tests in a session
const numTests = tests.length;
//testCounter = session attribute that shows the order of the tests (actual test)
let timer = 0;
let maxExercises = tests[session.testCounter].exercises.length;
Logger.dbg("executeStandardSession - testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
//Here it is loaded the test
var event = ["loadTest", {
data: {
testDescription: tests[0].description,
peerChange: tests[0].peerChange,
isStandard: session.isStandard,
testCounterS: session.testCounter
}
}];
try {
Logger.dbg("executeStandardSession - Sending loadTest event");
io.to(sessionName).emit(event[0], event[1]);
} catch (err) {
Logger.dbg(`executeStandardSession - error found at executing session: ${err}`);
}
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeStandardSession - lastSessionEvent saved", event[0])
const potentialParticipants = await User.find({ //It picks all the registered users in the session
environment: process.env.NODE_ENV,
subject: sessionName,
});
if (!potentialParticipants) {
Logger.dbg("executeStandardSession - No participants found");
return;
}
try {
Logger.dbg("executeStandardSession - Saving users' new properties");
potentialParticipants.forEach((p) => {
var participantF = p;
participantF.visitedPExercises = [];
participantF.visitedIExercises = [];
participantF.nextExercise = false;
participantF.save();
});
} catch (err) {
Logger.dbg(`executeStandardSession - error saving users' new properties: ${err}`);
return;
}
Logger.log("Timing", sessionName, "T1A");
//Start of the tests, following a time line
const interval = setInterval(async function () {
//If this session quantity of tests is the same test than loaded
const potentialParticipants = await User.find({ //It picks all the registered users in the session
environment: process.env.NODE_ENV,
subject: sessionName,
});
var participants = [];
potentialParticipants.forEach((p) => {
//Filter out the one not connected : they don't have the property socketId!
if (p.socketId || /^B/.test(p.code)) {
//Logger.dbg(`executeStandardSession - participant with code <${p.code}> is connected`);
participants.push(p);
}
});
//Logger.dbg(`executeStandardSession - participants length: ${participants.length}`);
if (participants.length % 2 != 0) {
participants = participants.splice(0, participants.length-1);
}
//Logger.dbg(`executeStandardSession - sorting participants list`);
participants.sort(function(a, b) {
return a.room - b.room;
});
// Calculate the maximum amount of participants possible
// Rounding the length to the maximum even number.
const maxParticipants = (Math.floor(participants.length/2))*2;
//Logger.dbg(`executeStandardSession - maxParticipants: ${maxParticipants}`);
for (let p = 0; p < maxParticipants; p++) {
try {
var participant1 = participants[p];
var participant2 = participants[p+1];
//Logger.dbg(`executeStandardSession - checking actions for participants: ${participant1.code} and ${participant2.code}`);
if (participant1.nextExercise || participant2.nextExercise) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - ${participant1.code} or ${participant2.code} tried to validate a code`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - User <${participant1.code}> clicked on the button: ${participant1.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - User <${participant2.code}> clicked on the button: ${participant2.nextExercise}`);
Logger.dbg("NEXT EXERCISE - Starting new exercise:");
if (session.testCounter != 2) {
var testNumber = session.testCounter;
} else {
var testNumber = 0;
}
Logger.dbg(`executeStandardSession - NEXT EXERCISE - testNumber: ${testNumber}`);
let testLanguage = tests[testNumber].language;
let listExercises = tests[testNumber].exercises;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - testLanguage: ${testLanguage}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - listExercisesSize: ${listExercises.length}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Calculating the next exercise number for ${(participant1.nextExercise)?"participant1":"participant2"}`);
var exerciseNumber = (participant1.nextExercise) ? getNextExerciseNumber(participant1, listExercises) : getNextExerciseNumber(participant2, listExercises);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Exercise number calculated: <${exerciseNumber}>`);
if (exerciseNumber >= listExercises.length) {
exerciseNumber = listExercises.length - 1;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Exercise number calculated: <${exerciseNumber}> UPDATED`);
}
var exercise = listExercises[exerciseNumber];
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Exercise to be sent is: ${exercise.name}`);
if (listExercises[0].type == "PAIR") {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Exercise type ${listExercises[0].type}`);
if (participant1.visitedPExercises.length < listExercises.length/2) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - There are still exercises (${participant1.visitedPExercises.length} < ${listExercises.length/2}) `);
if (participant1.nextExercise || participant2.nextExercise) {
var newEvent = ["newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
}];
try {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Sending exercise to ${participant1.code} and ${participant2.code}`);
io.to(participant1.socketId).emit(newEvent[0], newEvent[1]);
io.to(participant2.socketId).emit(newEvent[0], newEvent[1]);
lastSessionEvent.set(participant1.socketId, newEvent);
lastSessionEvent.set(participant2.socketId, newEvent);
} catch (err) {
Logger.dbgerr(`executeStandardSession - NEXT EXERCISE - Error sending exercise to ${participant1.code} and ${participant2.code}`);
Logger.dbgerr(`executeStandardSession - NEXT EXERCISE - Error: ${err}`);
}
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Sending custom alert "New exercise begins" to ${participant1.code} and ${participant2.code}`);
io.to(participant1.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
io.to(participant2.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
Logger.dbg(`executeStandardSession - NEXT EXERCISE - changing nextExercise property to false`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 ACTUAL value ${participant1.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 ACTUAL value ${participant2.nextExercise}`);
participant1.nextExercise = false;
participant2.nextExercise = false;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 UPDATED value ${participant1.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 UPDATED value ${participant2.nextExercise}`);
}
} else {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - changing nextExercise property to false`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 ACTUAL value ${participant1.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 ACTUAL value ${participant2.nextExercise}`);
participant1.nextExercise = false;
participant2.nextExercise = false;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 UPDATED value ${participant1.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 UPDATED value ${participant2.nextExercise}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - There are no more exercises left on this test for users ${participant1.code} and ${participant2.code}`);
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Sending custom alert to ${participant1.code} and ${participant2.code}`);
io.to(participant1.socketId).emit("customAlert", {
data: {
message: "There are no more exercises left, please wait for the next part."
}
});
io.to(participant2.socketId).emit("customAlert", {
data: {
message: "There are no more exercises left, please wait for the next part."
}
});
}
} else if (listExercises[0].type == "INDIVIDUAL") {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Exercise type ${listExercises[0].type}`);
if (participant1.nextExercise) {
if (participant1.visitedIExercises.length < listExercises.length) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 IND - User with code <${participant1.code}> going to next exercise`);
var newEvent = ["newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
}];
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 IND - Sending exercise to ${participant1.code}`);
io.to(participant1.socketId).emit(newEvent[0], newEvent[1]);
lastSessionEvent.set(participant1.socketId, newEvent);
io.to(participant1.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
participant1.nextExercise = false;
} else {
participant1.nextExercise = false;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P1 IND - There are no more exercises left on this test for user ${participant1.code}`);
io.to(participant1.socketId).emit("customAlert", {
data: {
message: "There are no more exercises left on this test"
}
});
}
}
if (participant2.nextExercise) {
if (participant2.visitedIExercises.length < listExercises.length) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 IND - User with code <${participant2.code}> going to next exercise`);
var newEvent = ["newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
}];
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 IND - Sending exercise to ${participant2.code}`);
io.to(participant2.socketId).emit(newEvent[0], newEvent[1]);
lastSessionEvent.set(participant2.socketId, newEvent);
io.to(participant2.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
participant2.nextExercise = false;
} else {
participant2.nextExercise = false;
Logger.dbg(`executeStandardSession - NEXT EXERCISE - P2 IND - There are no more exercises left on this test for user ${participant2.code}`);
io.to(participant2.socketId).emit("customAlert", {
data: {
message: "There are no more exercises left on this test"
}
});
}
}
}
if (listExercises[exerciseNumber].type == "PAIR") {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Saving next exercise visited to <${participant1.code}> and <${participant2.code}>`);
participant1.visitedPExercises.push(exerciseNumber);
participant1.save();
participant2.visitedPExercises.push(exerciseNumber);
participant2.save();
} else {
if (participant1.nextExercise) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Saving next exercise visited to <${participant1.code}>`);
participant1.visitedIExercises.push(exerciseNumber);
participant1.save();
}
if (participant2.nextExercise) {
Logger.dbg(`executeStandardSession - NEXT EXERCISE - Saving next exercise visited to <${participant2.code}>`);
participant2.visitedIExercises.push(exerciseNumber);
participant2.save();
}
}
}
} catch (err) {
Logger.dbg(`executeStandardSession - Error while trying to check actions for user ${participant1.code} and ${participant2.code}`);
}
p++;
}
if (session.testCounter == 3) {
Logger.dbg("executeStandardSession - There are no more tests, the session <" + session.name + "> has finish!");
Logger.dbg("executeStandardSession - emitting 'finish' event in session " + session.name + " #############################");
io.to(sessionName).emit("finish");
for (let i = 0; i < participants.length; i++) {
lastSessionEvent.set(sessionName, ["finish"]);
}
Logger.dbg("executeStandardSession - lastSessionEvent saved", event);
clearInterval(interval);
for (let p = 0; p < participants.length; p++) {
var participantF = participants[p];
participantF.visitedPExercises = [];
participantF.visitedIExercises = [];
participantF.nextExercise = false;
participantF.save();
}
} else if (timer > 0) { //If timer hasn't finished counting, it goes down
io.to(sessionName).emit("countDown", {
data: timer,
});
//Logger.dbg(timer);
timer--;
} else if (session.exerciseCounter == maxExercises) { //If timer goes to 0, and exercise in a test is the same as actual exercise, it goes to the next test
Logger.dbg("executeStandardSession - Going to the next test!");
session.testCounter++;
session.exerciseCounter = -1;
Logger.dbg(`executeStandardSession - emitting 'nextTest' event in session ${session.name} test sent: ${session.testCounter}`);
} else if (session.exerciseCounter === -1) { //If exercises have been finished, it pass to a new test
Logger.dbg("executeStandardSession - Loading test");
Logger.dbg(`executeStandardSession - testCounter: ${session.testCounter} ACTUAL`);
if (session.testCounter != 2) {
var testNumber = session.testCounter;
} else {
var testNumber = 0;
}
Logger.dbg(`executeStandardSession - testCounter: ${session.testCounter} UPDATED`);
var event = ["loadTest", {
data: {
testDescription: tests[testNumber].description,
peerChange: tests[testNumber].peerChange,
isStandard: true,
testCounterS: session.testCounter
},
}];
Logger.dbg(`executeStandardSession - emitting 'loadTest' event in session ${session.name}`);
io.to(sessionName).emit(event[0], event[1]);
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeStandardSession - lastSessionEvent saved", event[0]);
timer = tests[testNumber].time; //Resets the timer
session.exerciseCounter = 0;
Logger.dbg("executeStandardSession - testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
} else if (session.exerciseCounter == 0) { //If nothing before happens, it means that there are more exercises to do, and then in goes to the next one
if (session.testCounter != 2) {
var testNumber = session.testCounter;
} else {
var testNumber = 0;
}
Logger.dbg("executeStandardSession - Starting new exercise:");
let testLanguage = tests[testNumber].language;
let listExercises = tests[testNumber].exercises;
// Calculate the maximum amount of participants possible
// Rounding the length to the maximum even number.
const maxParticipants = (Math.floor(participants.length/2))*2;
Logger.dbg("executeStandardSession - Send a initial exercieses to to each pair");
for (let p = 0; p < maxParticipants; p++) {
var participant1 = participants[p];
var participant2 = participants[p+1];
Logger.dbg("executeStandardSession - FIRST EXERCISE - Calculating FIRST exercise");
var exerciseNumber = getNextExerciseNumber(participant1, listExercises);
var exercise = listExercises[exerciseNumber];
Logger.dbg(`executeStandardSession - FIRST EXERCISE - Sending exercise <${exerciseNumber}> to participant1 <${participant1.code}>`);
io.to(participant1.socketId).emit("newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
});
lastSessionEvent.set(participant1.socketId, ["newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
}]);
lastSessionEvent.set(participant2.socketId, ["newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
}]);
Logger.dbg(`FIRST EXERCISE - Sending exercise <${exerciseNumber}> to participant2 <${participant2.code}>`);
io.to(participant2.socketId).emit("newExercise", {
data: {
maxTime: tests[testNumber].testTime,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
}
});
io.to(participant1.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
io.to(participant2.socketId).emit("customAlert", {
data: {
message: "New exercise begins"
}
});
participant1.visitedPExercises.push(exerciseNumber);
participant1.save();
participant2.visitedPExercises.push(exerciseNumber);
participant2.save();
p++;
}
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeStandardSession - lastSessionEvent saved", "newExercise");
sessions.set(session.name, {
session: session,
exerciseType: listExercises[0].type,
});
timer = timer == 0 ? tests[testNumber].testTime : timer;
session.exerciseCounter++; //After that, it increments the counter to test in the before code if thera are more or not
Logger.dbg(" testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
session.save();
Logger.dbg("executeStandardSession - session saved ");
} else {
//---------------------------
if (session.testCounter == 0) {
Logger.log("Timing", sessionName, "T1B");
} else if (session.testCounter == 1) {
Logger.log("Timing", sessionName, "T2A");
} else if (session.testCounter == 2) {
Logger.log("Timing", sessionName, "T2B");
}
Logger.dbg("executeStandardSession - Going to the next test!");
session.testCounter++;
session.exerciseCounter = -1;
Logger.dbg("executeStandardSession - Loading test");
if (session.testCounter < 2) {
var testNumber = session.testCounter;
} else {
var testNumber = 0;
}
var event = ["loadTest", {
data: {
testDescription: tests[testNumber].description,
peerChange: tests[testNumber].peerChange,
isStandard: true,
testCounterS: session.testCounter
},
}];
for (let p = 0; p < maxParticipants; p++) {
participants[p].visitedPExercises = [];
if (session.testCounter == 2) {
Logger.dbg(`executeStandardSession - changing exerciseSwitch <${participants[p].exerciseSwitch}> for code <${participants[p].code}>`);
participants[p].exerciseSwitch = !participants[p].exerciseSwitch;
Logger.dbg(`executeStandardSession - changed exerciseSwitch <${participants[p].exerciseSwitch}> for code <${participants[p].code}>`);
}
participants[p].save();
io.to(participants[p].socketId).emit(event[0], event[1]);
lastSessionEvent.set(participants[p].socketId, event);
}
Logger.dbg("executeStandardSession - lastSessionEvent saved", event[0]);
timer = tests[testNumber].time; //Resets the timer
session.exerciseCounter = 0;
Logger.dbg("executeStandardSession - testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
}
//If the session is not running, it's beacuse it has not been active or it has finished, so it clears all before
Session.findOne({
name: sessionName,
environment: process.env.NODE_ENV,
}).then((currentSession) => {
if (!currentSession.running) {
clearInterval(interval);
Logger.dbg("executeStandardSession - clearInterval");
}
});
}, 1000);
}
/*
TODO This function has been cloned from the execute standard session it has only been proved with standard sessions.
Technical debt: This function should be reviewed in detail and tested in order to be sure that it works properly in a custom session.
Also, there are some pieces of code than potentially only are used in standard sessions that should be removed.
*/
async function executeCustomSession(session, io) {
var sessionName = session.name;
session.running = true;
session.save(); //Saves it on database
Logger.dbg("executeSession - Running ", session, ["name", "pairingMode", "tokenPairing", "blindParticipant"]);
//Pick all tests
const tests = await Test.find({
session: session.name,
environment: process.env.NODE_ENV,
}).sort({ orderNumber: 1 });
//Number of tests in a session
const numTests = tests.length;
//testCounter = session attribute that shows the order of the tests (actual test)
let timer = 0;
let maxExercises = tests[session.testCounter].exercises.length;
Logger.dbg("executeSession - testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
//Here it is loaded the test
var event = ["loadTest", {
data: {
testDescription: tests[0].description,
peerChange: tests[0].peerChange,
isStandard: session.isStandard,
testCounterS: session.testCounter
}
}];
io.to(sessionName).emit(event[0], event[1]);
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeSession - lastSessionEvent saved", event[0])
const potentialParticipants = await User.find({ //It picks all the registered users in the session
environment: process.env.NODE_ENV,
subject: sessionName,
});
potentialParticipants.forEach((p) => {
var participantF = p;
participantF.visitedPExercises = [];
participantF.visitedIExercises = [];
participantF.nextExercise = false;
participantF.save();
});
//Start of the tests, following a time line
const interval = setInterval(async function () {
if (session.testCounter == numTests) {
Logger.dbg("There are no more tests, the session <" + session.name + "> has finish!");
Logger.dbg("executeSession - emitting 'finish' event in session " + session.name + " #############################");
io.to(sessionName).emit("finish");
lastSessionEvent.set(sessionName, ["finish"]);
Logger.dbg("executeSession - lastSessionEvent saved", event);
clearInterval(interval);
} else if (timer > 0) { //If timer hasn't finished counting, it goes down
io.to(sessionName).emit("countDown", {
data: timer,
});
Logger.dbg(timer);
timer--;
} else if (session.exerciseCounter == maxExercises) { //If timer goes to 0, and exercise in a test is the same as actual exercise, it goes to the next test
Logger.dbg("Going to the next test!");
session.testCounter++;
session.exerciseCounter = -1;
} else if (session.exerciseCounter === -1) { //If exercises have been finished, it pass to a new test
Logger.dbg("Loading test");
var event = ["loadTest", {
data: {
testDescription: tests[session.testCounter].description,
peerChange: tests[session.testCounter].peerChange,
isStandard: false,
testCounterS: session.testCounter
},
}];
io.to(sessionName).emit(event[0], event[1]);
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeSession - lastSessionEvent saved", event[0]);
timer = tests[session.testCounter].time; //Resets the timer
session.exerciseCounter = 0;
Logger.dbg("executeSession - testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
} else { //If nothing before happens, it means that there are more exercises to do, and then in goes to the next one
Logger.dbg("Starting new exercise:");
let testLanguage = tests[session.testCounter].language;
let exercise =
tests[session.testCounter].exercises[session.exerciseCounter];
if (exercise) {
Logger.dbg(" " + exercise.description.substring(0, Math.min(80, exercise.description.length)) + "...");
var event = ["newExercise", {
data: {
maxTime: exercise.time,
exerciseDescription: exercise.description,
exerciseType: exercise.type,
inputs: exercise.inputs,
solutions: exercise.solutions,
testLanguage: testLanguage,
testIndex: session.testCounter,
},
}];
io.to(sessionName).emit(event[0], event[1]);
lastSessionEvent.set(sessionName, event);
Logger.dbg("executeSession - lastSessionEvent saved", event[0]);
sessions.set(session.name, {
session: session,
exerciseType: exercise.type,
});
timer = exercise.time;
}
session.exerciseCounter++; //After that, it increments the counter to test in the before code if thera are more or not
Logger.dbg(" testCounter: " + session.testCounter + " of " + numTests + " , exerciseCounter: " + session.exerciseCounter + " of " + maxExercises);
session.save();
Logger.dbg("executeSession - session saved ");
}
//If the session is not running, it's beacuse it has not been active or it has finished, so it clears all before
Session.findOne({
name: sessionName,
environment: process.env.NODE_ENV,
}).then((currentSession) => {
if (!currentSession.running) {
clearInterval(interval);
Logger.dbg("executeSession - clearInterval");
}
});
}, 1000);
}
//Executing a new session and testing the following exercise it has to be launched
async function executeSession(sessionName, io) {
//Pick up a session by its name, and puts in true the "running" attribute
lastSessionEvent.set(sessionName, []);
Logger.dbg("executeSession - Cleared last event of session " + sessionName);
Logger.dbg("executeSession - Starting " + sessionName);
const session = await Session.findOne({
name: sessionName,
environment: process.env.NODE_ENV,
});
if (session.isStandard) {
executeStandardSession(session, io);
} else {
executeCustomSession(session, io);
}
}
//This is the "pairing method" and where the rooms are given and configured, and the first test started
async function notifyParticipants(sessionName, io) {
const potentialParticipants = await User.find({ //It picks all the registered users in the session
environment: process.env.NODE_ENV,
subject: sessionName,
})
var participants = [];
Logger.dbg("notifyParticipants - Number of potential participants: " + potentialParticipants.length);
potentialParticipants.forEach((p) => {
//Filter out the one not connected : they don't have the property socketId!
if (p.socketId || /^B/.test(p.code)) {
Logger.dbg("notifyParticipants - Including connected participant", p.mail);
participants.push(p);
} else {
Logger.dbg("notifyParticipants - Skipping NOT CONNECTED participant", p.mail);
}
});
//If participant is logged (so this function is executed after pressing the "Start sessiobn" button), he/she is introduced to "participants" list
if (participants.length < 2) { //There must be at least 2 participants to start the session
Logger.dbg("notifyParticipants - UNEXPECTED ERROR - THERE ARE NOT CONNECTED PARTICIPANTS:" + JSON.stringify(potentialParticipants, null, 2));
return;
}
const session = await Session.findOne({
name: sessionName,
environment: process.env.NODE_ENV,
});
var excluded = { code: "XXXX" };
Logger.dbg("notifyParticipants - MANUAL pairing");
var participantCount = participants.length;
//If there are an odd number of participants, one of them randomly will be disconnected
if ((participantCount % 2) == 0)
Logger.dbg("notifyParticipants - the participant count is even, PERFECT PAIRING! :-)");
else {
//If there is any bot, it will be the one disconnected
var excludedIndex = participants.findIndex((p) => /^B/.test(p.code));
Logger.dbg("notifyParticipants - Excluded index: " + excludedIndex);
excluded = excludedIndex >= 0 ? participants[excludedIndex] : participants[participantCount - 1];