1 const db
= require("../utils/database");
2 const UserModel
= require("./User");
5 * Structure table Games:
7 * vid: integer (variant id)
8 * fenStart: varchar (initial position)
9 * fen: varchar (current position)
13 * score: varchar (result)
14 * scoreMsg: varchar ("Time", "Mutual agreement"...)
16 * drawOffer: char ('w','b' or '' for none)
17 * rematchOffer: char (similar to drawOffer)
19 * deletedByWhite: boolean
20 * deletedByBlack: boolean
21 * chatReadWhite: datetime
22 * chatReadBlack: datetime
24 * Structure table Moves:
26 * squares: varchar (description)
30 * Structure table Chats:
39 checkGameInfo: function(g
) {
41 g
.vid
.toString().match(/^[0-9]+$/) &&
42 g
.cadence
.match(/^[0-9dhms
+]+$/) &&
43 g
.randomness
.toString().match(/^[0-2]$/) &&
44 g
.fen
.match(/^[a-zA-Z0-9, /-]*$/) &&
45 g
.players
.length
== 2 &&
46 g
.players
.every(p
=> p
.id
.toString().match(/^[0-9]+$/))
50 create: function(vid
, fen
, randomness
, cadence
, players
, cb
) {
51 db
.serialize(function() {
53 "INSERT INTO Games " +
55 "vid, fenStart, fen, randomness, " +
61 vid
+ ",'" + fen
+ "','" + fen
+ "'," + randomness
+ "," +
62 players
[0].id
+ "," + players
[1].id
+ "," +
63 "'" + cadence
+ "'," + Date
.now() +
65 db
.run(query
, function(err
) {
66 cb(err
, { id: this.lastID
});
71 // TODO: some queries here could be async
72 getOne: function(id
, cb
) {
73 // NOTE: ignoring errors (shouldn't happen at this stage)
74 db
.serialize(function() {
77 "g.id, g.fen, g.fenStart, g.cadence, g.created, " +
78 "g.white, g.black, g.score, g.scoreMsg, " +
79 "g.chatReadWhite, g.chatReadBlack, " +
80 "g.drawOffer, g.rematchOffer, v.name AS vname " +
85 db
.get(query
, (err
, gameInfo
) => {
87 cb(err
|| { errmsg: "Game not found" }, undefined);
93 "WHERE id IN (" + gameInfo
.white
+ "," + gameInfo
.black
+ ")";
94 db
.all(query
, (err2
, players
) => {
95 if (players
[0].id
== gameInfo
.black
) players
= players
.reverse();
96 // The original players' IDs info isn't required anymore
97 delete gameInfo
["white"];
98 delete gameInfo
["black"];
100 "SELECT squares, played, idx " +
103 db
.all(query
, (err3
, moves
) => {
105 "SELECT msg, name, added " +
108 db
.all(query
, (err4
, chats
) => {
109 const game
= Object
.assign(
126 // For display on Hall: no need for moves or chats
127 getObserved: function(uid
, cursor
, cb
) {
128 db
.serialize(function() {
130 "SELECT id, vid, cadence, created, score, white, black " +
132 if (uid
> 0) query
+=
134 " created < " + cursor
+ " AND " +
135 " white <> " + uid
+ " AND " +
136 " black <> " + uid
+ " ";
138 "ORDER BY created DESC " +
139 "LIMIT 20"; //TODO: 20 hard-coded...
140 db
.all(query
, (err
, games
) => {
141 // Query players names
144 if (!pids
[g
.white
]) pids
[g
.white
] = true;
145 if (!pids
[g
.black
]) pids
[g
.black
] = true;
147 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
149 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
161 { id: g
.white
, name: names
[g
.white
] },
162 { id: g
.black
, name: names
[g
.black
] }
173 // For display on MyGames: registered user only
174 getRunning: function(uid
, cb
) {
175 db
.serialize(function() {
177 "SELECT g.id, g.cadence, g.created, " +
178 "g.white, g.black, v.name AS vname " +
181 " ON g.vid = v.id " +
182 "WHERE score = '*' AND (white = " + uid
+ " OR black = " + uid
+ ")";
183 db
.all(query
, (err
, games
) => {
184 // Get movesCount (could be done in // with next query)
186 "SELECT gid, COUNT(*) AS nbMoves " +
188 "WHERE gid IN " + "(" + games
.map(g
=> g
.id
).join(",") + ") " +
190 db
.all(query
, (err
, mstats
) => {
191 let movesCounts
= {};
192 mstats
.forEach(ms
=> { movesCounts
[ms
.gid
] = ms
.nbMoves
; });
193 // Query player names
196 if (!pids
[g
.white
]) pids
[g
.white
] = true;
197 if (!pids
[g
.black
]) pids
[g
.black
] = true;
199 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
201 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
212 movesCount: movesCounts
[g
.id
] || 0,
214 { id: g
.white
, name: names
[g
.white
] },
215 { id: g
.black
, name: names
[g
.black
] }
227 // These games could be deleted on some side. movesCount not required
228 getCompleted: function(uid
, cursor
, cb
) {
229 db
.serialize(function() {
231 "SELECT g.id, g.cadence, g.created, g.score, g.scoreMsg, " +
232 "g.white, g.black, g.deletedByWhite, g.deletedByBlack, " +
236 " ON g.vid = v.id " +
238 " score <> '*' AND" +
239 " created < " + cursor
+ " AND" +
242 " white = " + uid
+ " AND" +
243 " (deletedByWhite IS NULL OR NOT deletedByWhite)" +
247 " black = " + uid
+ " AND" +
248 " (deletedByBlack IS NULL OR NOT deletedByBlack)" +
252 "ORDER BY created DESC " +
254 db
.all(query
, (err
, games
) => {
255 // Query player names
258 if (!pids
[g
.white
]) pids
[g
.white
] = true;
259 if (!pids
[g
.black
]) pids
[g
.black
] = true;
261 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
263 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
274 scoreMsg: g
.scoreMsg
,
276 { id: g
.white
, name: names
[g
.white
] },
277 { id: g
.black
, name: names
[g
.black
] }
279 deletedByWhite: g
.deletedByWhite
,
280 deletedByBlack: g
.deletedByBlack
290 getPlayers: function(id
, cb
) {
291 db
.serialize(function() {
293 "SELECT white, black " +
296 db
.get(query
, (err
, players
) => {
297 return cb(err
, players
);
302 checkGameUpdate: function(obj
) {
303 // Check all that is possible (required) in obj:
306 !obj
.move || !!(obj
.move.idx
.toString().match(/^[0-9]+$/))
308 !obj
.drawOffer
|| !!(obj
.drawOffer
.match(/^[wbtn]$/))
310 !obj
.rematchOffer
|| !!(obj
.rematchOffer
.match(/^[wbn]$/))
312 !obj
.fen
|| !!(obj
.fen
.match(/^[a-zA-Z0-9, /-]*$/))
314 !obj
.score
|| !!(obj
.score
.match(/^[012?*\/-]+$/))
316 !obj
.chatRead
|| !(['w','b'].includes(obj
.chatRead
))
318 !obj
.scoreMsg
|| !!(obj
.scoreMsg
.match(/^[a
-zA
-Z
]+$/))
320 !obj
.chat
|| UserModel
.checkNameEmail({name: obj
.chat
.name
})
325 // obj can have fields move, chat, fen, drawOffer and/or score + message
326 update: function(id
, obj
, cb
) {
327 db
.parallelize(function() {
332 // NOTE: if drawOffer is set, we should check that it's player's turn
333 // A bit overcomplicated. Let's trust the client on that for now...
334 if (!!obj
.drawOffer
) {
335 if (obj
.drawOffer
== "n")
336 // Special "None" update
338 modifs
+= "drawOffer = '" + obj
.drawOffer
+ "',";
340 if (!!obj
.rematchOffer
) {
341 if (obj
.rematchOffer
== "n")
342 // Special "None" update
343 obj
.rematchOffer
= "";
344 modifs
+= "rematchOffer = '" + obj
.rematchOffer
+ "',";
346 if (!!obj
.fen
) modifs
+= "fen = '" + obj
.fen
+ "',";
347 if (!!obj
.deletedBy
) {
348 const myColor
= obj
.deletedBy
== 'w' ? "White" : "Black";
349 modifs
+= "deletedBy" + myColor
+ " = true,";
351 if (!!obj
.chatRead
) {
352 const myColor
= obj
.chatRead
== 'w' ? "White" : "Black";
353 modifs
+= "chatRead" + myColor
+ " = " + Date
.now() + ",";
356 modifs
+= "score = '" + obj
.score
+ "'," +
357 "scoreMsg = '" + obj
.scoreMsg
+ "',";
359 const finishAndSendQuery
= () => {
360 modifs
= modifs
.slice(0, -1); //remove last comma
361 if (modifs
.length
> 0) {
362 updateQuery
+= modifs
+ " WHERE id = " + id
;
367 if (!!obj
.move || (!!obj
.score
&& obj
.scoreMsg
== "Time")) {
368 // Security: only update moves if index is right,
369 // and score with scoreMsg "Time" if really lost on time.
371 "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
374 db
.get(query
, (err
, ret
) => {
376 if (!ret
.maxIdx
|| ret
.maxIdx
+ 1 == obj
.move.idx
) {
378 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
379 "(" + id
+ ",?," + Date
.now() + "," + obj
.move.idx
+ ")";
380 db
.run(query
, JSON
.stringify(obj
.move.squares
));
381 finishAndSendQuery();
382 } else cb({ errmsg: "Wrong move index" });
384 if (ret
.maxIdx
< 2) cb({ errmsg: "Time not over" });
386 // We also need the game cadence
391 db
.get(query
, (err2
, ret2
) => {
392 const daysTc
= parseInt(ret2
.cadence
.match(/^[0-9]+/)[0]);
393 if (Date
.now() - ret
.lastPlayed
> daysTc
* 24 * 3600 * 1000)
394 finishAndSendQuery();
395 else cb({ errmsg: "Time not over" });
400 } else finishAndSendQuery();
401 // NOTE: chat and delchat are mutually exclusive
404 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
405 + id
+ ",?,'" + obj
.chat
.name
+ "'," + Date
.now() + ")";
406 db
.run(query
, obj
.chat
.msg
);
407 } else if (obj
.delchat
) {
414 if (!!obj
.deletedBy
) {
415 // Did my opponent delete it too?
418 (obj
.deletedBy
== 'w' ? "Black" : "White") +
421 "SELECT " + selection
+ " " +
424 db
.get(query
, (err
,ret
) => {
425 // If yes: just remove game
426 if (!!ret
.deletedByOpp
) GameModel
.remove(id
);
432 remove: function(id_s
) {
435 ? " IN (" + id_s
.join(",") + ")"
437 db
.parallelize(function() {
439 "DELETE FROM Games " +
440 "WHERE id " + suffix
;
443 "DELETE FROM Moves " +
444 "WHERE gid " + suffix
;
447 "DELETE FROM Chats " +
448 "WHERE gid " + suffix
;
453 cleanGamesDb: function() {
454 const tsNow
= Date
.now();
455 // 86400000 = 24 hours in milliseconds
456 const day
= 86400000;
457 db
.serialize(function() {
459 "SELECT id, created " +
461 db
.all(query
, (err
, games
) => {
463 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
466 db
.all(query
, (err2
, mstats
) => {
467 // Reorganize moves data to avoid too many array lookups:
468 let movesGroups
= {};
469 mstats
.forEach(ms
=> {
470 movesGroups
[ms
.gid
] = {
475 // Remove games still not really started,
476 // with no action in the last 2 weeks:
481 !movesGroups
[g
.id
] &&
482 tsNow
- g
.created
> 14*day
486 movesGroups
[g
.id
].nbMoves
== 1 &&
487 tsNow
- movesGroups
[g
.id
].lastMaj
> 14*day
493 if (toRemove
.length
> 0) GameModel
.remove(toRemove
);
500 module
.exports
= GameModel
;