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
.fen
.match(/^[a-zA-Z0-9, /-]*$/) &&
44 g
.players
.length
== 2 &&
45 g
.players
.every(p
=> p
.id
.toString().match(/^[0-9]+$/))
49 incrementCounter: function(vid
, cb
) {
50 db
.serialize(function() {
53 "SET total = total + 1 " +
59 create: function(vid
, fen
, options
, cadence
, players
, cb
) {
60 db
.serialize(function() {
62 "INSERT INTO Games " +
64 "vid, fenStart, fen, options, " +
70 vid
+ ",'" + fen
+ "','" + fen
+ "',?," +
71 players
[0].id
+ "," + players
[1].id
+ "," +
72 "'" + cadence
+ "'," + Date
.now() +
74 db
.run(query
, options
, function(err
) {
75 cb(err
, { id: this.lastID
});
80 // TODO: some queries here could be async
81 getOne: function(id
, cb
) {
82 // NOTE: ignoring errors (shouldn't happen at this stage)
83 db
.serialize(function() {
86 "id, vid, fen, fenStart, cadence, created, " +
87 "white, black, options, score, scoreMsg, " +
88 "chatReadWhite, chatReadBlack, drawOffer, rematchOffer " +
91 db
.get(query
, (err
, gameInfo
) => {
93 cb(err
|| { errmsg: "Game not found" }, undefined);
99 "WHERE id IN (" + gameInfo
.white
+ "," + gameInfo
.black
+ ")";
100 db
.all(query
, (err2
, players
) => {
101 if (players
[0].id
== gameInfo
.black
) players
= players
.reverse();
102 // The original players' IDs info isn't required anymore
103 delete gameInfo
["white"];
104 delete gameInfo
["black"];
106 "SELECT squares, played, idx " +
109 db
.all(query
, (err3
, moves
) => {
111 "SELECT msg, name, added " +
114 db
.all(query
, (err4
, chats
) => {
115 const game
= Object
.assign(
131 // For display on Hall: no need for moves or chats
132 getObserved: function(uid
, cursor
, cb
) {
133 db
.serialize(function() {
135 "SELECT id, vid, cadence, created, score, white, black " +
137 "WHERE created < " + cursor
+ " ";
140 " AND white <> " + uid
+ " " +
141 " AND black <> " + uid
+ " ";
144 "ORDER BY created DESC " +
145 "LIMIT 20"; //TODO: 20 hard-coded...
146 db
.all(query
, (err
, games
) => {
147 // Query players names
150 if (!pids
[g
.white
]) pids
[g
.white
] = true;
151 if (!pids
[g
.black
]) pids
[g
.black
] = true;
153 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
155 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
167 { id: g
.white
, name: names
[g
.white
] },
168 { id: g
.black
, name: names
[g
.black
] }
179 // For display on MyGames: registered user only
180 getRunning: function(uid
, cb
) {
181 db
.serialize(function() {
183 "SELECT id, vid, cadence, created, white, black " +
185 "WHERE score = '*' AND (white = " + uid
+ " OR black = " + uid
+ ")";
186 db
.all(query
, (err
, games
) => {
187 // Get movesCount (could be done in // with next query)
189 "SELECT gid, COUNT(*) AS nbMoves " +
191 "WHERE gid IN " + "(" + games
.map(g
=> g
.id
).join(",") + ") " +
193 db
.all(query
, (err
, mstats
) => {
194 let movesCounts
= {};
195 mstats
.forEach(ms
=> { movesCounts
[ms
.gid
] = ms
.nbMoves
; });
196 // Query player names
199 if (!pids
[g
.white
]) pids
[g
.white
] = true;
200 if (!pids
[g
.black
]) pids
[g
.black
] = true;
202 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
204 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
215 movesCount: movesCounts
[g
.id
] || 0,
217 { id: g
.white
, name: names
[g
.white
] },
218 { id: g
.black
, name: names
[g
.black
] }
230 // These games could be deleted on some side. movesCount not required
231 getCompleted: function(uid
, cursor
, cb
) {
232 db
.serialize(function() {
234 "SELECT id, vid, cadence, created, score, scoreMsg, " +
235 "white, black, deletedByWhite, deletedByBlack " +
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();
383 else cb({ errmsg: "Wrong move index" });
386 if (ret
.maxIdx
< 2) cb({ errmsg: "Time not over" });
388 // We also need the game cadence
393 db
.get(query
, (err2
, ret2
) => {
394 const daysTc
= parseInt(ret2
.cadence
.match(/^[0-9]+/)[0]);
395 if (Date
.now() - ret
.lastPlayed
> daysTc
* 24 * 3600 * 1000)
396 finishAndSendQuery();
397 else cb({ errmsg: "Time not over" });
403 else finishAndSendQuery();
404 // NOTE: chat and delchat are mutually exclusive
407 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
408 + id
+ ",?,'" + obj
.chat
.name
+ "'," + Date
.now() + ")";
409 db
.run(query
, obj
.chat
.msg
);
411 else if (obj
.delchat
) {
418 if (!!obj
.deletedBy
) {
419 // Did my opponent delete it too?
422 (obj
.deletedBy
== 'w' ? "Black" : "White") +
425 "SELECT " + selection
+ " " +
428 db
.get(query
, (err
,ret
) => {
429 // If yes: just remove game
430 if (!!ret
.deletedByOpp
) GameModel
.remove(id
);
436 remove: function(id_s
) {
439 ? " IN (" + id_s
.join(",") + ")"
441 db
.parallelize(function() {
443 "DELETE FROM Games " +
444 "WHERE id " + suffix
;
447 "DELETE FROM Moves " +
448 "WHERE gid " + suffix
;
451 "DELETE FROM Chats " +
452 "WHERE gid " + suffix
;
457 cleanGamesDb: function() {
458 const tsNow
= Date
.now();
459 // 86400000 = 24 hours in milliseconds
460 const day
= 86400000;
461 db
.serialize(function() {
463 "SELECT id, created, cadence, score " +
465 db
.all(query
, (err
, games
) => {
467 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
470 db
.all(query
, (err2
, mstats
) => {
471 // Reorganize moves data to avoid too many array lookups:
472 let movesGroups
= {};
473 mstats
.forEach(ms
=> {
474 movesGroups
[ms
.gid
] = {
479 // Remove games still not really started,
480 // with no action in the last 2 weeks, or result != '*':
482 let lostOnTime
= [ [], [] ];
486 !movesGroups
[g
.id
] &&
487 (g
.score
!= '*' || tsNow
- g
.created
> 14*day
)
491 !!movesGroups
[g
.id
] &&
492 movesGroups
[g
.id
].nbMoves
== 1 &&
493 (g
.score
!= '*' || tsNow
- movesGroups
[g
.id
].lastMaj
> 14*day
)
498 // Set score if lost on time and >= 2 moves:
501 !!movesGroups
[g
.id
] &&
502 movesGroups
[g
.id
].nbMoves
>= 2 &&
503 tsNow
- movesGroups
[g
.id
].lastMaj
>
504 // cadence in days * nb seconds per day:
505 parseInt(g
.cadence
.slice(0, -1), 10) * day
507 lostOnTime
[movesGroups
[g
.id
].nbMoves
% 2].push(g
.id
);
510 if (toRemove
.length
> 0) GameModel
.remove(toRemove
);
511 if (lostOnTime
.some(l
=> l
.length
> 0)) {
512 db
.parallelize(function() {
513 for (let i
of [0, 1]) {
514 if (lostOnTime
[i
].length
> 0) {
515 const score
= (i
== 0 ? "0-1" : "1-0");
518 "SET score = '" + score
+ "', scoreMsg = 'Time' " +
519 "WHERE id IN (" + lostOnTime
[i
].join(',') + ")";
532 module
.exports
= GameModel
;