From 3837d4f7885a3c3cdb468da2f3fa3fa1e5a1415a Mon Sep 17 00:00:00 2001
From: Benjamin Auder <benjamin.auder@somewhere>
Date: Fri, 31 Jan 2020 01:25:03 +0100
Subject: [PATCH] Fixes

---
 client/src/App.vue                   |  2 +-
 client/src/components/BaseGame.vue   |  2 +-
 client/src/components/Chat.vue       |  6 ++-
 client/src/components/MoveList.vue   |  2 +
 client/src/components/UpsertUser.vue |  2 +-
 client/src/views/Game.vue            |  5 ++-
 server/db/create.sql                 |  3 +-
 server/models/Game.js                | 67 ++++++++++++++++++++--------
 server/sockets.js                    |  4 +-
 9 files changed, 66 insertions(+), 27 deletions(-)

diff --git a/client/src/App.vue b/client/src/App.vue
index 77fed7af..6c945663 100644
--- a/client/src/App.vue
+++ b/client/src/App.vue
@@ -26,7 +26,7 @@
                 | {{ st.tr["Forum"] }}
             #rightMenu
               .clickable(onClick="doClick('modalUser')")
-                | {{ st.user.id > 0 ? "Update" : "Login" }}
+                | {{ st.user.id > 0 ? (st.user.name || "@nonymous") : "Login" }}
               .clickable(onClick="doClick('modalSettings')")
                 | {{ st.tr["Settings"] }}
               .clickable#flagContainer(onClick="doClick('modalLang')")
diff --git a/client/src/components/BaseGame.vue b/client/src/components/BaseGame.vue
index 1ea862fb..608a98d4 100644
--- a/client/src/components/BaseGame.vue
+++ b/client/src/components/BaseGame.vue
@@ -255,7 +255,7 @@ export default {
           else
             this.moves = this.moves.slice(0,this.cursor).concat([move]);
         }
-        if (this.game.mode != "analyze")
+        if (!navigate && this.game.mode != "analyze")
           this.$emit("newmove", move); //post-processing (e.g. computer play)
         // Is opponent in check?
         this.incheck = this.vr.getCheckSquares(this.vr.turn);
diff --git a/client/src/components/Chat.vue b/client/src/components/Chat.vue
index cd3c3c89..8f1646f4 100644
--- a/client/src/components/Chat.vue
+++ b/client/src/components/Chat.vue
@@ -3,7 +3,8 @@
   input#inputChat(type="text" :placeholder="st.tr['Type here']"
     @keyup.enter="sendChat")
   button#sendChatBtn(@click="sendChat") {{ st.tr["Send"] }}
-  p(v-for="chat in chats" :class="classObject(chat)" v-html="chat.msg")
+  p(v-for="chat in pastChats" :class="classObject(chat)" v-html="chat.name + ': ' + chat.msg")
+  p(v-for="chat in chats" :class="classObject(chat)" v-html="chat.name + ': ' + chat.msg")
 </template>
 
 <script>
@@ -11,7 +12,8 @@ import { store } from "@/store";
 
 export default {
   name: "my-chat",
-  props: ["players"],
+  // Prop 'pastChats' for corr games where chats are on server
+  props: ["players","pastChats"],
   data: function() {
     return {
       st: store.state,
diff --git a/client/src/components/MoveList.vue b/client/src/components/MoveList.vue
index 91607c25..1e19a2bd 100644
--- a/client/src/components/MoveList.vue
+++ b/client/src/components/MoveList.vue
@@ -25,6 +25,8 @@ export default {
 	props: ["moves","cursor","score","message"],
   watch: {
     cursor: function(newValue) {
+      if (newValue < 0)
+        newValue = 0; //avoid rows[-1] --> error
       // $nextTick to wait for table > tr to be rendered
       this.$nextTick( () => {
         let rows = document.querySelectorAll('#movesList tr');
diff --git a/client/src/components/UpsertUser.vue b/client/src/components/UpsertUser.vue
index c8df869a..93c1fd4b 100644
--- a/client/src/components/UpsertUser.vue
+++ b/client/src/components/UpsertUser.vue
@@ -5,7 +5,7 @@ div
     .card
       label.modal-close(for="modalUser")
       h3 {{ stage }}
-      form#userForm(@submit.prevent="onSubmit()")
+      form#userForm(@submit.prevent="onSubmit()" @keyup.enter="onSubmit")
         div(v-show="stage!='Login'")
           fieldset
             label(for="username") Name
diff --git a/client/src/views/Game.vue b/client/src/views/Game.vue
index 7b14055f..2f33bc58 100644
--- a/client/src/views/Game.vue
+++ b/client/src/views/Game.vue
@@ -2,7 +2,8 @@
 main
   .row
     #chat.col-sm-12.col-md-4.col-md-offset-4
-      Chat(:players="game.players" @newchat="processChat")
+      Chat(:players="game.players" :pastChats="game.chats"
+        @newchat="processChat")
   .row
     .col-sm-12
       #actions(v-if="game.mode!='analyze' && game.score=='*'")
@@ -364,6 +365,8 @@ export default {
               end: s.end,
             };
           });
+          // Also sort chat messages (if any)
+          game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
         }
         const myIdx = game.players.findIndex(p => {
           return p.sid == this.st.user.sid || p.uid == this.st.user.id;
diff --git a/server/db/create.sql b/server/db/create.sql
index 5357b843..4f7b547c 100644
--- a/server/db/create.sql
+++ b/server/db/create.sql
@@ -48,8 +48,9 @@ create table Games (
 create table Chats (
   gid integer,
   name varchar,
+  sid varchar,
   msg varchar,
-  added datetime,
+  added datetime
 );
 
 -- Store informations about players in a corr game
diff --git a/server/models/Game.js b/server/models/Game.js
index 67550779..0ac822e8 100644
--- a/server/models/Game.js
+++ b/server/models/Game.js
@@ -18,9 +18,15 @@ var db = require("../utils/database");
  * Structure table Moves:
  *   gid: ref game id
  *   squares: varchar (description)
- *   message: text
  *   played: datetime
  *   idx: integer
+ *
+ * Structure table Chats:
+ *   gid: game id (int)
+ *   msg: varchar
+ *   name: varchar
+ *   sid: varchar (socket ID when sending message)
+ *   added: datetime
  */
 
 const GameModel =
@@ -73,20 +79,29 @@ const GameModel =
 					if (!!err2)
 						return cb(err2);
 					query =
-						"SELECT squares, message, played, idx " +
+						"SELECT squares, played, idx " +
 						"FROM Moves " +
 						"WHERE gid = " + id;
 					db.all(query, (err3,moves) => {
 						if (!!err3)
 							return cb(err3);
-						const game = Object.assign({},
-              gameInfo,
-						  {
-							  players: players,
-							  moves: moves
-              }
-            );
-						return cb(null, game);
+			      query =
+              "SELECT msg, name, sid, added " +
+              "FROM Chats " +
+              "WHERE gid = " + id;
+			      db.all(query, (err4,chats) => {
+						  if (!!err4)
+							  return cb(err4);
+						  const game = Object.assign({},
+                gameInfo,
+                {
+                  players: players,
+                  moves: moves,
+                  chats: chats,
+                }
+              );
+						  return cb(null, game);
+            });
 					});
 				});
 			});
@@ -134,24 +149,28 @@ const GameModel =
     });
   },
 
-  // obj can have fields move, message, fen, drawOffer and/or score
+  // obj can have fields move, chat, fen, drawOffer and/or score
   update: function(id, obj)
   {
 		db.parallelize(function() {
       let query =
         "UPDATE Games " +
         "SET ";
+      let modifs = "";
       if (!!obj.message)
-        query += "message = message || ' ' || '" + obj.message + "',";
+        modifs += "message = message || ' ' || '" + obj.message + "',";
       if (!!obj.drawOffer)
-        query += "drawOffer = " + obj.drawOffer + ",";
+        modifs += "drawOffer = " + obj.drawOffer + ",";
       if (!!obj.fen)
-        query += "fen = '" + obj.fen + "',";
+        modifs += "fen = '" + obj.fen + "',";
       if (!!obj.score)
-        query += "score = '" + obj.score + "',";
-      query = query.slice(0,-1); //remove last comma
-      query += " WHERE id = " + id;
-      db.run(query);
+        modifs += "score = '" + obj.score + "',";
+      modifs = modifs.slice(0,-1); //remove last comma
+      if (modifs.length > 0)
+      {
+        query += modifs + " WHERE id = " + id;
+        db.run(query);
+      }
       if (!!obj.move)
       {
         const m = obj.move;
@@ -161,6 +180,14 @@ const GameModel =
             + m.played + "," + m.idx + ")";
         db.run(query);
       }
+      if (!!obj.chat)
+      {
+			  query =
+	        "INSERT INTO Chats (gid, msg, name, sid, added) VALUES " +
+            "(" + id + ",'" + obj.chat.msg + "','" + obj.chat.name +
+            "','" + obj.chat.sid + "'," + Date.now() + ")";
+        db.run(query);
+      }
     });
   },
 
@@ -179,6 +206,10 @@ const GameModel =
 				"DELETE FROM Moves " +
 				"WHERE gid = " + id;
 			db.run(query);
+			query =
+				"DELETE FROM Chats " +
+				"WHERE gid = " + id;
+			db.run(query);
 		});
 	},
 
diff --git a/server/sockets.js b/server/sockets.js
index e4aa4493..fae71106 100644
--- a/server/sockets.js
+++ b/server/sockets.js
@@ -150,11 +150,11 @@ module.exports = function(wss) {
           break;
         case "resign":
           clients[obj.target].sock.send(JSON.stringify(
-            {code:"resign"}));
+            {code:"resign", side:obj.side}));
           break;
         case "abort":
           clients[obj.target].sock.send(JSON.stringify(
-            {code:"abort",msg:obj.msg}));
+            {code:"abort"}));
           break;
         case "drawoffer":
           clients[obj.target].sock.send(JSON.stringify(
-- 
2.44.0