0a3a9917e3a4eda28101c93e62984efffdad958e
[vchess.git] / client / src / data / challengeCheck.js
1
2
3 function timeUnitToSeconds(value, unit)
4 {
5 let seconds = value;
6 switch (unit)
7 {
8 case 'd':
9 seconds *= 24;
10 case 'h':
11 seconds *= 60;
12 case 'm':
13 seconds *= 60;
14 }
15 return seconds;
16 }
17
18 function isLargerUnit(unit1, unit2)
19 {
20 return (unit1 == 'd' && unit2 != 'd')
21 || (unit1 == 'h' && ['s','m'].includes(unit2))
22 || (unit1 == 'm' && unit2 == 's');
23 }
24
25 export function checkChallenge(c)
26 {
27 const vid = parseInt(c.vid);
28 if (isNaN(vid) || vid <= 0)
29 return "Please select a variant";
30
31 const tcParts = c.timeControl.replace(/ /g,"").split('+');
32 const mainTime = tcParts[0].match(/([0-9]+)([smhd])/);
33 if (!mainTime)
34 return "Wrong time control";
35 const mainTimeValue = parseInt(mainTime[1]);
36 const mainTimeUnit = mainTime[2];
37 if (isNaN(mainTimeValue) || mainTimeValue <= 0)
38 return "Main time should be strictly positive";
39 c.mainTime = timeUnitToSeconds(mainTimeValue, mainTimeUnit);
40 if (tcParts.length >= 2)
41 {
42 const increment = tcParts[1].match(/([0-9]+)([smhd])/);
43 if (!increment)
44 return "Wrong time control";
45 const incrementValue = parseInt(increment[1]);
46 const incrementUnit = increment[2];
47 if (isLargerUnit(incrementUnit, mainTimeUnit))
48 return "Increment unit cannot be larger than main unit";
49 if (isNaN(incrementValue) || incrementValue < 0)
50 return "Increment must be positive";
51 c.increment = timeUnitToSeconds(incrementValue, incrementUnit);
52 }
53
54 // Basic alphanumeric check for players names
55 let playerCount = 0;
56 for (p of c.players)
57 {
58 if (p.name.length > 0)
59 {
60 // TODO: slightly redundant (see data/userCheck.js)
61 if (!p.name.match(/^[\w]+$/))
62 return "Wrong characters in players names";
63 playerCount++;
64 }
65 }
66
67 if (playerCount > 0 && playerCount != c.nbPlayers-1)
68 return "None, or all of the opponent names must be filled"
69
70 // Allow custom FEN (and check it) only for individual challenges
71 if (c.fen.length > 0 && playerCount > 0)
72 {
73 if (!V.IsGoodFen(c.fen))
74 return "Bad FEN string";
75 }
76 else //generate a FEN
77 c.fen = V.GenRandInitFen();
78 }