From bebcc8d45532e67902175f69084a08040f06855f Mon Sep 17 00:00:00 2001
From: Benjamin Auder <benjamin.auder@somewhere>
Date: Thu, 28 Nov 2019 16:55:41 +0100
Subject: [PATCH] Some fixes, working on corr challenges

---
 client/src/data/challengeCheck.js | 22 ++++++----------------
 client/src/main.js                |  1 +
 client/src/views/Hall.vue         | 23 +++++++++++++++++++----
 server/db/create.sql              |  5 ++---
 server/models/Challenge.js        | 22 +++++++++++-----------
 server/models/Variant.js          | 23 -----------------------
 server/routes/challenges.js       |  2 +-
 server/routes/users.js            |  4 ++++
 8 files changed, 44 insertions(+), 58 deletions(-)

diff --git a/client/src/data/challengeCheck.js b/client/src/data/challengeCheck.js
index e0aa978c..c2700008 100644
--- a/client/src/data/challengeCheck.js
+++ b/client/src/data/challengeCheck.js
@@ -9,27 +9,17 @@ export function checkChallenge(c)
   const tc = extractTime(c.timeControl);
   if (!tc)
     return "Wrong time control";
-  // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
-  c.liveGame = (tc.mainTime + 40 * tc.increment < 3*24*60*60);
 
-	// Basic alphanumeric check for players names
-	let playerCount = 0;
-	for (const pname of c.to)
+	// Basic alphanumeric check for opponent name
+	if (!!c.to)
 	{
-		if (pname.length > 0)
-		{
-      // TODO: slightly redundant (see data/userCheck.js)
-			if (!pname.match(/^[\w]+$/))
-				return "Wrong characters in players names";
-			playerCount++;
-		}
+     // TODO: slightly redundant (see data/userCheck.js)
+		if (!c.to.match(/^[\w]+$/))
+			return "Wrong characters in opponent name";
 	}
 
-	if (playerCount > 0 && playerCount != c.nbPlayers-1)
-		return "None, or all of the opponent names must be filled"
-
   // Allow custom FEN (and check it) only for individual challenges
-  if (c.fen.length > 0 && playerCount > 0)
+  if (c.fen.length > 0 && !!c.to)
   {
     if (!V.IsGoodFen(c.fen))
       return "Bad FEN string";
diff --git a/client/src/main.js b/client/src/main.js
index 08893dbc..56c6492c 100644
--- a/client/src/main.js
+++ b/client/src/main.js
@@ -13,5 +13,6 @@ new Vue({
   created: function() {
     window.doClick = (elemId) => { document.getElementById(elemId).click() };
     store.initialize();
+    // NOTE: at this point, variants and tr(anslations) might be uninitialized
   },
 }).$mount("#app");
diff --git a/client/src/views/Hall.vue b/client/src/views/Hall.vue
index c47e89f1..fb3ed630 100644
--- a/client/src/views/Hall.vue
+++ b/client/src/views/Hall.vue
@@ -143,9 +143,24 @@ export default {
         "GET",
         {uid: this.st.user.id},
         response => {
-          console.log(response.challenges);
-          // TODO: post-treatment on challenges ?
-          Array.prototype.push.apply(this.challenges, response.challenges);
+          // Gather all senders names, and then retrieve full identity:
+          // (TODO [perf]: some might be online...)
+          const uids = response.challenges.map(c => { return c.uid });
+          ajax("/users",
+            "GET",
+            { ids: uids },
+            names => {
+              this.challenges = this.challenges.concat(
+                response.challenges.map(c => {
+                  // (just players names in fact)
+                  const from = {name: names[c.uid], id: c.uid};
+                  const type = this.classifyObject(c);
+                  const vname = this.getVname(c.vid);
+                  return Object.assign({}, c, {type: type, vname: vname, from: from});
+                })
+              )
+            }
+          );
         }
       );
     }
@@ -443,7 +458,7 @@ export default {
         ajax(
           "/challenges",
           "POST",
-          chall,
+          { chall: chall },
           response => { finishAddChallenge(response.cid); }
         );
       }
diff --git a/server/db/create.sql b/server/db/create.sql
index e5cbfd7e..56d4a247 100644
--- a/server/db/create.sql
+++ b/server/db/create.sql
@@ -29,7 +29,7 @@ create table Problems (
 );
 
 -- All the following tables are for correspondance play only
--- (Live games are stored only in browsers)
+-- (Live games are stored in browser)
 
 create table Challenges (
   id integer primary key,
@@ -49,8 +49,7 @@ create table Games (
   fenStart varchar, --initial state
   fen varchar, --current state
   score varchar,
-  mainTime integer,
-  addTime integer,
+  timeControl varchar,
   foreign key (vid) references Variants(id)
 );
 
diff --git a/server/models/Challenge.js b/server/models/Challenge.js
index 3f713203..82b252fd 100644
--- a/server/models/Challenge.js
+++ b/server/models/Challenge.js
@@ -15,21 +15,20 @@ const ChallengeModel =
 {
   checkChallenge: function(c)
   {
-    if (!c.vid.match(/^[0-9]+$/))
+    if (!c.vid.toString().match(/^[0-9]+$/))
       return "Wrong variant ID";
-
     if (!c.timeControl.match(/^[0-9dhms +]+$/))
       return "Wrong characters in time control";
-
-    if (!c.fen.match(/^[a-zA-Z0-9, /-]+$/))
+    if (!c.fen.match(/^[a-zA-Z0-9, /-]*$/))
       return "Bad FEN string";
+    return "";
   },
 
   // fen cannot be undefined
   create: function(c, cb)
   {
     db.serialize(function() {
-      let query =
+      const query =
         "INSERT INTO Challenges " +
         "(added, uid, " + (!!c.to ? "target, " : "") +
           "vid, fen, timeControl) VALUES " +
@@ -44,7 +43,7 @@ const ChallengeModel =
   getOne: function(id, cb)
   {
     db.serialize(function() {
-      let query =
+      const query =
         "SELECT * " +
         "FROM Challenges " +
         "WHERE id = " + id;
@@ -62,26 +61,27 @@ const ChallengeModel =
         "SELECT * " +
         "FROM Challenges " +
         "WHERE target IS NULL OR target = " + uid;
-      db.run(query, (err,challenges) => {
+      db.all(query, (err,challenges) => {
         return cb(err, challenges);
       });
     });
   },
 
-  remove: function(id, uid)
+  remove: function(id, uid, cb)
   {
     db.serialize(function() {
       let query =
         "SELECT 1 " +
         "FROM Challenges " +
         "WHERE id = " + id + " AND uid = " + uid;
-      db.run(query, (err,rows) => {
-        if (rows.length == 0)
-          return res.json({errmsg: "Not your challenge"});
+      db.get(query, (err,chall) => {
+        if (!chall)
+          return cb({errmsg: "Not your challenge"});
         query =
           "DELETE FROM Challenges " +
           "WHERE id = " + id;
         db.run(query);
+        cb(null);
       });
     });
   },
diff --git a/server/models/Variant.js b/server/models/Variant.js
index ae417932..233d938b 100644
--- a/server/models/Variant.js
+++ b/server/models/Variant.js
@@ -9,29 +9,6 @@ var db = require("../utils/database");
 
 const VariantModel =
 {
-	// This is duplicated in client. TODO: really required here?
-	NbPlayers:
-	{
-		"Alice": [2,3,4],
-		"Antiking": [2,3,4],
-		"Atomic": [2,3,4],
-		"Baroque": [2,3,4],
-		"Berolina": [2,4],
-		"Checkered": [2,3,4],
-		"Chess960": [2,3,4],
-		"Crazyhouse": [2,3,4],
-		"Dark": [2,3,4],
-		"Extinction": [2,3,4],
-		"Grand": [2],
-		"Losers": [2,3,4],
-		"Magnetic": [2],
-		"Marseille": [2],
-		"Switching": [2,3,4],
-		"Upsidedown": [2],
-		"Wildebeest": [2],
-		"Zen": [2,3,4],
-	},
-
 	getByName: function(name, callback)
 	{
 		db.serialize(function() {
diff --git a/server/routes/challenges.js b/server/routes/challenges.js
index 2ae1327a..c2e55c8a 100644
--- a/server/routes/challenges.js
+++ b/server/routes/challenges.js
@@ -35,8 +35,8 @@ router.post("/challenges", access.logged, access.ajax, (req,res) => {
       if (!!err || !user)
         return res.json(err | {errmsg: "Typo in player name"});
       challenge.to = user.id; //ready now to insert challenge
+      insertChallenge();
     });
-    insertChallenge();
   }
   else
     insertChallenge();
diff --git a/server/routes/users.js b/server/routes/users.js
index b657920e..a9995d7f 100644
--- a/server/routes/users.js
+++ b/server/routes/users.js
@@ -27,6 +27,10 @@ router.get("/whoami", access.ajax, (req,res) => {
   });
 });
 
+router.get("/users", access.ajax, (req,res) => {
+  // TODO: list all names + id for users of given ID (query "ids")
+});
+
 // to: object user (to who we send an email)
 function setAndSendLoginToken(subject, to, res)
 {
-- 
2.44.0