Start server implementation for correspondance play (early debug stage)
[vchess.git] / public / javascripts / shared / challengeCheck.js
CommitLineData
ab4f4bf2
BA
1function checkChallenge(c)
2{
3 const vid = parseInt(c.vid);
4 if (isNaN(vid) || vid <= 0)
5 return "Please select a variant";
6
7 const mainTime = parseInt(c.mainTime);
8 const increment = parseInt(c.increment);
9 if (isNaN(mainTime) || mainTime <= 0)
10 return "Main time should be strictly positive";
11 if (isNaN(increment) || increment < 0)
12 return "Increment must be positive";
13
14 // Basic alphanumeric check for players names
15 let playerCount = 0;
16 for (p of c.players)
17 {
18 if (p.length > 0)
19 {
20 if (!p.match(/^[\w]+$/))
21 return "Wrong characters in players names";
22 playerCount++;
23 }
24 }
25
26 if (playerCount > 0 && playerCount != c.nbPlayers)
27 return "None, or all of the opponent names must be filled"
28
29 if (!!document) //client side
30 {
31 const idxInVariants = variantArray.findIndex(v => v.id == c.vid);
32 const vname = variantArray[idxInVariants].name;
33 const scriptId = vname + "RulesScript";
34 const afterRulesAreLoaded = () => {
35 const V = eval(vname + "Rules");
36 // Allow custom FEN (and check it) only for individual challenges
37 if (c.fen.length > 0 && playerCount > 0)
38 {
39 if (!V.IsGoodFen(c.fen))
40 return "Bad FEN string";
41 }
42 else
43 {
44 // Generate a FEN
45 c.fen = V.GenRandInitFen();
46 }
47 };
48 if (!document.getElementById(scriptId))
49 {
50 // Load variant rules (only once)
51 var script = document.createElement("script");
52 script.id = scriptId;
53 script.src = "/javascripts/variants/" + vname + ".js";
54 document.body.appendChild(script);
55 script.onload = afterRulesAreLoaded;
56 }
57 }
58 else
59 {
60 // Just characters check on server:
61 if (!c.fen.match(/^[a-zA-Z0-9, /-]*$/))
62 return "Bad FEN string";
63 }
64}
65
66try { module.exports = checkChallenge; } catch(e) { } //for server