+ checkGameUpdate: function(obj) {
+ // Check all that is possible (required) in obj:
+ return (
+ (
+ !obj.move || !!(obj.move.idx.toString().match(/^[0-9]+$/))
+ ) && (
+ !obj.drawOffer || !!(obj.drawOffer.match(/^[wbtn]$/))
+ ) && (
+ !obj.rematchOffer || !!(obj.rematchOffer.match(/^[wbn]$/))
+ ) && (
+ // TODO: check if commas are still used (probably not)
+ !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9,. /-]*$/))
+ ) && (
+ !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
+ ) && (
+ !obj.chatRead || ['w','b'].includes(obj.chatRead)
+ ) && (
+ !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
+ ) && (
+ !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
+ )
+ );
+ },
+
+ // obj can have fields move, chat, fen, drawOffer and/or score + message
+ update: function(id, obj, cb) {
+ db.parallelize(function() {
+ let updateQuery =
+ "UPDATE Games " +
+ "SET ";
+ let modifs = "";
+ // 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.rematchOffer) {
+ if (obj.rematchOffer == "n")
+ // Special "None" update
+ obj.rematchOffer = "";
+ modifs += "rematchOffer = '" + obj.rematchOffer + "',";
+ }
+ if (!!obj.fen) modifs += "fen = '" + obj.fen + "',";
+ if (!!obj.deletedBy) {
+ const myColor = obj.deletedBy == 'w' ? "White" : "Black";
+ modifs += "deletedBy" + myColor + " = true,";
+ }
+ if (!!obj.chatRead) {
+ const myColor = obj.chatRead == 'w' ? "White" : "Black";
+ modifs += "chatRead" + myColor + " = " + Date.now() + ",";
+ }
+ if (!!obj.score) {
+ modifs += "score = '" + obj.score + "'," +
+ "scoreMsg = '" + obj.scoreMsg + "',";
+ }
+ const finishAndSendQuery = () => {
+ modifs = modifs.slice(0, -1); //remove last comma
+ if (modifs.length > 0) {
+ updateQuery += modifs + " WHERE id = " + id;
+ db.run(updateQuery);
+ }
+ cb(null);
+ };
+ if (!!obj.move || (!!obj.score && obj.scoreMsg == "Time")) {
+ // Security: only update moves if index is right,
+ // and score with scoreMsg "Time" if really lost on time.
+ let query =
+ "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
+ "FROM Moves " +
+ "WHERE gid = " + id;
+ db.get(query, (err, ret) => {
+ if (!!obj.move ) {
+ if (!ret.maxIdx || ret.maxIdx + 1 == obj.move.idx) {
+ query =
+ "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
+ "(" + id + ",?," + Date.now() + "," + obj.move.idx + ")";
+ db.run(query, JSON.stringify(obj.move.squares));
+ finishAndSendQuery();
+ } else cb({ errmsg: "Wrong move index" });
+ } else {
+ if (ret.maxIdx < 2) cb({ errmsg: "Time not over" });
+ else {
+ // We also need the game cadence
+ query =
+ "SELECT cadence " +
+ "FROM Games " +
+ "WHERE id = " + id;
+ db.get(query, (err2, ret2) => {
+ const daysTc = parseInt(ret2.cadence.match(/^[0-9]+/)[0]);
+ if (Date.now() - ret.lastPlayed > daysTc * 24 * 3600 * 1000)
+ finishAndSendQuery();
+ else cb({ errmsg: "Time not over" });
+ });
+ }
+ }
+ });
+ } else finishAndSendQuery();
+ // NOTE: chat and delchat are mutually exclusive
+ if (!!obj.chat) {
+ const query =
+ "INSERT INTO Chats (gid, msg, name, added) VALUES ("
+ + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
+ db.run(query, obj.chat.msg);
+ } else if (obj.delchat) {
+ const query =
+ "DELETE " +
+ "FROM Chats " +
+ "WHERE gid = " + id;
+ db.run(query);
+ }
+ if (!!obj.deletedBy) {
+ // Did my opponent delete it too?
+ let selection =
+ "deletedBy" +
+ (obj.deletedBy == 'w' ? "Black" : "White") +
+ " AS deletedByOpp";
+ const query =
+ "SELECT " + selection + " " +
+ "FROM Games " +
+ "WHERE id = " + id;
+ db.get(query, (err,ret) => {
+ // If yes: just remove game
+ if (!!ret.deletedByOpp) GameModel.remove(id);
+ });
+ }
+ });
+ },
+
+ remove: function(id_s) {
+ const suffix =
+ Array.isArray(id_s)
+ ? " IN (" + id_s.join(",") + ")"
+ : " = " + id_s;
+ db.parallelize(function() {
+ let query =
+ "DELETE FROM Games " +
+ "WHERE id " + suffix;
+ db.run(query);
+ query =
+ "DELETE FROM Moves " +
+ "WHERE gid " + suffix;
+ db.run(query);
+ query =
+ "DELETE FROM Chats " +
+ "WHERE gid " + suffix;
+ db.run(query);
+ });
+ },
+
+ cleanGamesDb: function() {
+ const tsNow = Date.now();
+ // 86400000 = 24 hours in milliseconds
+ const day = 86400000;
+ db.serialize(function() {
+ let query =
+ "SELECT id, created " +
+ "FROM Games";
+ db.all(query, (err, games) => {
+ query =
+ "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
+ "FROM Moves " +
+ "GROUP BY gid";
+ db.all(query, (err2, mstats) => {
+ // Reorganize moves data to avoid too many array lookups:
+ let movesGroups = {};
+ mstats.forEach(ms => {
+ movesGroups[ms.gid] = {
+ nbMoves: ms.nbMoves,
+ lastMaj: ms.lastMaj
+ };
+ });
+ // Remove games still not really started,
+ // with no action in the last 2 weeks:
+ let toRemove = [];
+ games.forEach(g => {
+ if (
+ (
+ !movesGroups[g.id] &&
+ tsNow - g.created > 14*day
+ )
+ ||
+ (
+ !!movesGroups[g.id] &&
+ movesGroups[g.id].nbMoves == 1 &&
+ tsNow - movesGroups[g.id].lastMaj > 14*day
+ )
+ ) {
+ toRemove.push(g.id);
+ }
+ });
+ if (toRemove.length > 0) GameModel.remove(toRemove);
+ });
+ });
+ });
+ }