Saving current state
[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 else
54 c.increment = 0;
55
56 // Basic alphanumeric check for players names
57 let playerCount = 0;
58 for (const p of c.to)
59 {
60 if (p.name.length > 0)
61 {
62 // TODO: slightly redundant (see data/userCheck.js)
63 if (!p.name.match(/^[\w]+$/))
64 return "Wrong characters in players names";
65 playerCount++;
66 }
67 }
68
69 if (playerCount > 0 && playerCount != c.nbPlayers-1)
70 return "None, or all of the opponent names must be filled"
71
72 // Allow custom FEN (and check it) only for individual challenges
73 if (c.fen.length > 0 && playerCount > 0)
74 {
75 if (!V.IsGoodFen(c.fen))
76 return "Bad FEN string";
77 }
78 else //generate a FEN
79 c.fen = V.GenRandInitFen();
80 }