Fixes
[vchess.git] / server / models / Game.js
index 02e3194..9d70082 100644 (file)
@@ -7,11 +7,11 @@ const UserModel = require("./User");
  *   vid: integer (variant id)
  *   fenStart: varchar (initial position)
  *   fen: varchar (current position)
- *   timeControl: string
+ *   cadence: string
  *   score: varchar (result)
  *   scoreMsg: varchar ("Time", "Mutual agreement"...)
  *   created: datetime
- *   drawOffer: boolean
+ *   drawOffer: char ('w','b' or '' for none)
  *
  * Structure table Players:
  *   gid: ref game id
@@ -34,13 +34,9 @@ const UserModel = require("./User");
 const GameModel =
 {
   checkGameInfo: function(g) {
-    if (!g.id.toString().match(/^[0-9]+$/))
-      return "Wrong game ID";
     if (!g.vid.toString().match(/^[0-9]+$/))
       return "Wrong variant ID";
-    if (!g.vname.match(/^[a-zA-Z0-9]+$/))
-      return "Wrong variant name";
-    if (!g.timeControl.match(/^[0-9dhms +]+$/))
+    if (!g.cadence.match(/^[0-9dhms +]+$/))
       return "Wrong characters in time control";
     if (!g.fen.match(/^[a-zA-Z0-9, /-]*$/))
       return "Bad FEN string";
@@ -51,14 +47,14 @@ const GameModel =
     return "";
   },
 
-       create: function(vid, fen, timeControl, players, cb)
-       {
-               db.serialize(function() {
-                       let query =
-                               "INSERT INTO Games"
-        + " (vid, fenStart, fen, score, timeControl, created, drawOffer)"
-        + " VALUES (" + vid + ",'" + fen + "','" + fen + "','*','"
-        + timeControl + "'," + Date.now() + "," + false + ")";
+  create: function(vid, fen, cadence, players, cb)
+  {
+    db.serialize(function() {
+      let query =
+        "INSERT INTO Games " +
+        "(vid, fenStart, fen, score, cadence, created, drawOffer) " +
+        "VALUES " +
+        "(" + vid + ",'" + fen + "','" + fen + "','*','" + cadence + "'," + Date.now() + ",'')";
       db.run(query, function(err) {
         if (!!err)
           return cb(err);
@@ -70,51 +66,58 @@ const GameModel =
           db.run(query);
         });
         cb(null, {gid: this.lastID});
-                       });
-               });
-       },
+      });
+    });
+  },
 
-       // TODO: queries here could be async, and wait for all to complete
-       getOne: function(id, cb)
-       {
-               db.serialize(function() {
-      // TODO: optimize queries?
-                       let query =
+  // TODO: some queries here could be async
+  getOne: function(id, light, cb)
+  {
+    db.serialize(function() {
+      let query =
         // NOTE: g.scoreMsg can be NULL
         // (in this case score = "*" and no reason to look at it)
-                               "SELECT g.id, g.vid, g.fen, g.fenStart, g.timeControl, g.score, " +
-          "g.scoreMsg, v.name AS vname " +
-                               "FROM Games g " +
+        "SELECT g.id, g.vid, g.fen, g.fenStart, g.cadence, g.score, " +
+          "g.scoreMsg, g.drawOffer, v.name AS vname " +
+        "FROM Games g " +
         "JOIN Variants v " +
         "  ON g.vid = v.id " +
-                               "WHERE g.id = " + id;
-                       db.get(query, (err,gameInfo) => {
-                               if (!!err)
-                                       return cb(err);
-                               query =
-                                       "SELECT p.uid, p.color, u.name " +
-                                       "FROM Players p " +
+        "WHERE g.id = " + id;
+      db.get(query, (err,gameInfo) => {
+        if (!!err)
+          return cb(err);
+        query =
+          "SELECT p.uid, p.color, u.name " +
+          "FROM Players p " +
           "JOIN Users u " +
           "  ON p.uid = u.id " +
-                                       "WHERE p.gid = " + id;
-                               db.all(query, (err2,players) => {
-                                       if (!!err2)
-                                               return cb(err2);
-                                       query =
-                                               "SELECT squares, played, idx " +
-                                               "FROM Moves " +
-                                               "WHERE gid = " + id;
-                                       db.all(query, (err3,moves) => {
-                                               if (!!err3)
-                                                       return cb(err3);
-                             query =
+          "WHERE p.gid = " + id;
+        db.all(query, (err2,players) => {
+          if (!!err2)
+            return cb(err2);
+          if (light)
+          {
+            const game = Object.assign({},
+              gameInfo,
+              {players: players}
+            );
+            return cb(null, game);
+          }
+          query =
+            "SELECT squares, played, idx " +
+            "FROM Moves " +
+            "WHERE gid = " + id;
+          db.all(query, (err3,moves) => {
+            if (!!err3)
+              return cb(err3);
+            query =
               "SELECT msg, name, added " +
               "FROM Chats " +
               "WHERE gid = " + id;
-                             db.all(query, (err4,chats) => {
-                                                 if (!!err4)
-                                                         return cb(err4);
-                                                 const game = Object.assign({},
+            db.all(query, (err4,chats) => {
+              if (!!err4)
+                return cb(err4);
+              const game = Object.assign({},
                 gameInfo,
                 {
                   players: players,
@@ -122,41 +125,42 @@ const GameModel =
                   chats: chats,
                 }
               );
-                                                 return cb(null, game);
+              return cb(null, game);
             });
-                                       });
-                               });
-                       });
-               });
-       },
+          });
+        });
+      });
+    });
+  },
 
-       getByUser: function(uid, excluded, cb)
-       {
-               db.serialize(function() {
-                       // Next query is fine because a player appear at most once in a game
-                       const query =
-                               "SELECT gid " +
-                               "FROM Players " +
-                               "WHERE uid " + (excluded ? "<>" : "=") + " " + uid;
-                       db.all(query, (err,gameIds) => {
-                               if (!!err)
-                                       return cb(err);
-        gameIds = gameIds || []; //might be empty
-                               let gameArray = [];
-                               for (let i=0; i<gameIds.length; i++)
-                               {
-                                       GameModel.getOne(gameIds[i]["gid"], (err2,game) => {
-                                               if (!!err2)
-                                                       return cb(err2);
-                                               gameArray.push(game);
-                                               // Call callback function only when gameArray is complete:
-                                               if (i == gameIds.length - 1)
-                                                       return cb(null, gameArray);
-                                       });
-                               }
-                       });
-               });
-       },
+  // For display on MyGames or Hall: no need for moves or chats
+  getByUser: function(uid, excluded, cb)
+  {
+    db.serialize(function() {
+      const query =
+        "SELECT DISTINCT gid " +
+        "FROM Players " +
+        "WHERE uid " + (excluded ? "<>" : "=") + " " + uid;
+      db.all(query, (err,gameIds) => {
+        if (!!err)
+          return cb(err);
+        if (gameIds.length == 0)
+          return cb(null, []);
+        let gameArray = [];
+        for (let i=0; i<gameIds.length; i++)
+        {
+          GameModel.getOne(gameIds[i]["gid"], true, (err2,game) => {
+            if (!!err2)
+              return cb(err2);
+            gameArray.push(game);
+            // Call callback function only when gameArray is complete:
+            if (i == gameIds.length - 1)
+              return cb(null, gameArray);
+          });
+        }
+      });
+    });
+  },
 
   getPlayers: function(id, cb)
   {
@@ -181,6 +185,8 @@ const GameModel =
       if (!obj.move.idx.toString().match(/^[0-9]+$/))
         return "Wrong move index";
     }
+    if (!!obj.drawOffer && !obj.drawOffer.match(/^[wbtn]$/))
+      return "Wrong draw offer format";
     if (!!obj.fen && !obj.fen.match(/^[a-zA-Z0-9, /-]*$/))
       return "Wrong FEN string";
     if (!!obj.score && !obj.score.match(/^[012?*\/-]+$/))
@@ -195,15 +201,21 @@ const GameModel =
   // obj can have fields move, chat, fen, drawOffer and/or score
   update: function(id, obj)
   {
-               db.parallelize(function() {
+    db.parallelize(function() {
       let query =
         "UPDATE Games " +
         "SET ";
       let modifs = "";
       if (!!obj.message)
         modifs += "message = message || ' ' || '" + obj.message + "',";
-      if ([true,false].includes(obj.drawOffer))
-        modifs += "drawOffer = " + obj.drawOffer + ",";
+      // NOTE: if drawOffer is set, we should check that it's player's turn
+      // A bit overcomplicated. Let's trust the client on that for now...
+      if (!!obj.drawOffer)
+      {
+        if (obj.drawOffer == "n") //Special "None" update
+          obj.drawOffer = "";
+        modifs += "drawOffer = '" + obj.drawOffer + "',";
+      }
       if (!!obj.fen)
         modifs += "fen = '" + obj.fen + "',";
       if (!!obj.score)
@@ -226,35 +238,35 @@ const GameModel =
       }
       if (!!obj.chat)
       {
-                         query =
-               "INSERT INTO Chats (gid, msg, name, added) VALUES ("
-            + id + ",?,'" + obj.chat.name + "'," + "," + Date.now() + ")";
+        query =
+          "INSERT INTO Chats (gid, msg, name, added) VALUES ("
+            + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
         db.run(query, obj.chat.msg);
       }
     });
   },
 
-       remove: function(id)
-       {
-               db.parallelize(function() {
-                       let query =
-                               "DELETE FROM Games " +
-                               "WHERE id = " + id;
-                       db.run(query);
-                       query =
-                               "DELETE FROM Players " +
-                               "WHERE gid = " + id;
-                       db.run(query);
-                       query =
-                               "DELETE FROM Moves " +
-                               "WHERE gid = " + id;
-                       db.run(query);
-                       query =
-                               "DELETE FROM Chats " +
-                               "WHERE gid = " + id;
-                       db.run(query);
-               });
-       },
+  remove: function(id)
+  {
+    db.parallelize(function() {
+      let query =
+        "DELETE FROM Games " +
+        "WHERE id = " + id;
+      db.run(query);
+      query =
+        "DELETE FROM Players " +
+        "WHERE gid = " + id;
+      db.run(query);
+      query =
+        "DELETE FROM Moves " +
+        "WHERE gid = " + id;
+      db.run(query);
+      query =
+        "DELETE FROM Chats " +
+        "WHERE gid = " + id;
+      db.run(query);
+    });
+  },
 
   cleanGamesDb: function()
   {
@@ -263,22 +275,21 @@ const GameModel =
     const day = 86400000;
     db.serialize(function() {
       let query =
-        "SELECT id,score " +
+        "SELECT id,created " +
         "FROM Games ";
       db.all(query, (err,games) => {
         games.forEach(g => {
           query =
-            "SELECT max(played) AS lastMaj " +
+            "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
             "FROM Moves " +
             "WHERE gid = " + g.id;
-          db.get(query, (err2,updated) => {
-            if (!updated && tsNow - g.created > 7*day)
-              return GameModel.remove(g.id);
-            const lastMaj = updated.lastMaj;
-            if (g.score != "*" && tsNow - lastMaj > 7*day ||
-              g.score == "*" && tsNow - lastMaj > 91*day)
+          db.get(query, (err2,mstats) => {
+            // Remove games still not really started,
+            // with no action in the last 3 months:
+            if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
+              (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
             {
-              GameModel.remove(g.id);
+              return GameModel.remove(g.id);
             }
           });
         });