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 incrementCounter: function(vid
, cb
) {
51 db
.serialize(function() {
54 "SET total = total + 1 " +
60 create: function(vid
, fen
, randomness
, cadence
, players
, cb
) {
61 db
.serialize(function() {
63 "INSERT INTO Games " +
65 "vid, fenStart, fen, randomness, " +
71 vid
+ ",'" + fen
+ "','" + fen
+ "'," + randomness
+ "," +
72 players
[0].id
+ "," + players
[1].id
+ "," +
73 "'" + cadence
+ "'," + Date
.now() +
75 db
.run(query
, function(err
) {
76 cb(err
, { id: this.lastID
});
81 // TODO: some queries here could be async
82 getOne: function(id
, cb
) {
83 // NOTE: ignoring errors (shouldn't happen at this stage)
84 db
.serialize(function() {
87 "g.id, g.fen, g.fenStart, g.cadence, g.created, " +
88 "g.white, g.black, g.randomness, g.score, g.scoreMsg, " +
89 "g.chatReadWhite, g.chatReadBlack, g.drawOffer, " +
90 // TODO: vid and vname are redundant
91 "g.rematchOffer, v.id as vid, v.name AS vname " +
96 db
.get(query
, (err
, gameInfo
) => {
98 cb(err
|| { errmsg: "Game not found" }, undefined);
104 "WHERE id IN (" + gameInfo
.white
+ "," + gameInfo
.black
+ ")";
105 db
.all(query
, (err2
, players
) => {
106 if (players
[0].id
== gameInfo
.black
) players
= players
.reverse();
107 // The original players' IDs info isn't required anymore
108 delete gameInfo
["white"];
109 delete gameInfo
["black"];
111 "SELECT squares, played, idx " +
114 db
.all(query
, (err3
, moves
) => {
116 "SELECT msg, name, added " +
119 db
.all(query
, (err4
, chats
) => {
120 const game
= Object
.assign(
137 // For display on Hall: no need for moves or chats
138 getObserved: function(uid
, cursor
, cb
) {
139 db
.serialize(function() {
141 "SELECT id, vid, cadence, created, score, white, black " +
143 "WHERE created < " + cursor
+ " ";
146 " AND white <> " + uid
+ " " +
147 " AND black <> " + uid
+ " ";
150 "ORDER BY created DESC " +
151 "LIMIT 20"; //TODO: 20 hard-coded...
152 db
.all(query
, (err
, games
) => {
153 // Query players names
156 if (!pids
[g
.white
]) pids
[g
.white
] = true;
157 if (!pids
[g
.black
]) pids
[g
.black
] = true;
159 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
161 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
173 { id: g
.white
, name: names
[g
.white
] },
174 { id: g
.black
, name: names
[g
.black
] }
185 // For display on MyGames: registered user only
186 getRunning: function(uid
, cb
) {
187 db
.serialize(function() {
189 "SELECT g.id, g.cadence, g.created, " +
190 "g.white, g.black, v.name AS vname " +
193 " ON g.vid = v.id " +
194 "WHERE score = '*' AND (white = " + uid
+ " OR black = " + uid
+ ")";
195 db
.all(query
, (err
, games
) => {
196 // Get movesCount (could be done in // with next query)
198 "SELECT gid, COUNT(*) AS nbMoves " +
200 "WHERE gid IN " + "(" + games
.map(g
=> g
.id
).join(",") + ") " +
202 db
.all(query
, (err
, mstats
) => {
203 let movesCounts
= {};
204 mstats
.forEach(ms
=> { movesCounts
[ms
.gid
] = ms
.nbMoves
; });
205 // Query player names
208 if (!pids
[g
.white
]) pids
[g
.white
] = true;
209 if (!pids
[g
.black
]) pids
[g
.black
] = true;
211 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
213 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
224 movesCount: movesCounts
[g
.id
] || 0,
226 { id: g
.white
, name: names
[g
.white
] },
227 { id: g
.black
, name: names
[g
.black
] }
239 // These games could be deleted on some side. movesCount not required
240 getCompleted: function(uid
, cursor
, cb
) {
241 db
.serialize(function() {
243 "SELECT g.id, g.cadence, g.created, g.score, g.scoreMsg, " +
244 "g.white, g.black, g.deletedByWhite, g.deletedByBlack, " +
248 " ON g.vid = v.id " +
250 " score <> '*' AND" +
251 " created < " + cursor
+ " AND" +
254 " white = " + uid
+ " AND" +
255 " (deletedByWhite IS NULL OR NOT deletedByWhite)" +
259 " black = " + uid
+ " AND" +
260 " (deletedByBlack IS NULL OR NOT deletedByBlack)" +
264 "ORDER BY created DESC " +
266 db
.all(query
, (err
, games
) => {
267 // Query player names
270 if (!pids
[g
.white
]) pids
[g
.white
] = true;
271 if (!pids
[g
.black
]) pids
[g
.black
] = true;
273 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
275 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
286 scoreMsg: g
.scoreMsg
,
288 { id: g
.white
, name: names
[g
.white
] },
289 { id: g
.black
, name: names
[g
.black
] }
291 deletedByWhite: g
.deletedByWhite
,
292 deletedByBlack: g
.deletedByBlack
302 getPlayers: function(id
, cb
) {
303 db
.serialize(function() {
305 "SELECT white, black " +
308 db
.get(query
, (err
, players
) => {
309 return cb(err
, players
);
314 checkGameUpdate: function(obj
) {
315 // Check all that is possible (required) in obj:
318 !obj
.move || !!(obj
.move.idx
.toString().match(/^[0-9]+$/))
320 !obj
.drawOffer
|| !!(obj
.drawOffer
.match(/^[wbtn]$/))
322 !obj
.rematchOffer
|| !!(obj
.rematchOffer
.match(/^[wbn]$/))
324 // TODO: check if commas are still used (probably not)
325 !obj
.fen
|| !!(obj
.fen
.match(/^[a-zA-Z0-9,. /-]*$/))
327 !obj
.score
|| !!(obj
.score
.match(/^[012?*\/-]+$/))
329 !obj
.chatRead
|| ['w','b'].includes(obj
.chatRead
)
331 !obj
.scoreMsg
|| !!(obj
.scoreMsg
.match(/^[a
-zA
-Z
]+$/))
333 !obj
.chat
|| UserModel
.checkNameEmail({name: obj
.chat
.name
})
338 // obj can have fields move, chat, fen, drawOffer and/or score + message
339 update: function(id
, obj
, cb
) {
340 db
.parallelize(function() {
345 // NOTE: if drawOffer is set, we should check that it's player's turn
346 // A bit overcomplicated. Let's trust the client on that for now...
347 if (!!obj
.drawOffer
) {
348 if (obj
.drawOffer
== "n")
349 // Special "None" update
351 modifs
+= "drawOffer = '" + obj
.drawOffer
+ "',";
353 if (!!obj
.rematchOffer
) {
354 if (obj
.rematchOffer
== "n")
355 // Special "None" update
356 obj
.rematchOffer
= "";
357 modifs
+= "rematchOffer = '" + obj
.rematchOffer
+ "',";
359 if (!!obj
.fen
) modifs
+= "fen = '" + obj
.fen
+ "',";
360 if (!!obj
.deletedBy
) {
361 const myColor
= obj
.deletedBy
== 'w' ? "White" : "Black";
362 modifs
+= "deletedBy" + myColor
+ " = true,";
364 if (!!obj
.chatRead
) {
365 const myColor
= obj
.chatRead
== 'w' ? "White" : "Black";
366 modifs
+= "chatRead" + myColor
+ " = " + Date
.now() + ",";
369 modifs
+= "score = '" + obj
.score
+ "'," +
370 "scoreMsg = '" + obj
.scoreMsg
+ "',";
372 const finishAndSendQuery
= () => {
373 modifs
= modifs
.slice(0, -1); //remove last comma
374 if (modifs
.length
> 0) {
375 updateQuery
+= modifs
+ " WHERE id = " + id
;
380 if (!!obj
.move || (!!obj
.score
&& obj
.scoreMsg
== "Time")) {
381 // Security: only update moves if index is right,
382 // and score with scoreMsg "Time" if really lost on time.
384 "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
387 db
.get(query
, (err
, ret
) => {
389 if (!ret
.maxIdx
|| ret
.maxIdx
+ 1 == obj
.move.idx
) {
391 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
392 "(" + id
+ ",?," + Date
.now() + "," + obj
.move.idx
+ ")";
393 db
.run(query
, JSON
.stringify(obj
.move.squares
));
394 finishAndSendQuery();
396 else cb({ errmsg: "Wrong move index" });
399 if (ret
.maxIdx
< 2) cb({ errmsg: "Time not over" });
401 // We also need the game cadence
406 db
.get(query
, (err2
, ret2
) => {
407 const daysTc
= parseInt(ret2
.cadence
.match(/^[0-9]+/)[0]);
408 if (Date
.now() - ret
.lastPlayed
> daysTc
* 24 * 3600 * 1000)
409 finishAndSendQuery();
410 else cb({ errmsg: "Time not over" });
416 else finishAndSendQuery();
417 // NOTE: chat and delchat are mutually exclusive
420 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
421 + id
+ ",?,'" + obj
.chat
.name
+ "'," + Date
.now() + ")";
422 db
.run(query
, obj
.chat
.msg
);
424 else if (obj
.delchat
) {
431 if (!!obj
.deletedBy
) {
432 // Did my opponent delete it too?
435 (obj
.deletedBy
== 'w' ? "Black" : "White") +
438 "SELECT " + selection
+ " " +
441 db
.get(query
, (err
,ret
) => {
442 // If yes: just remove game
443 if (!!ret
.deletedByOpp
) GameModel
.remove(id
);
449 remove: function(id_s
) {
452 ? " IN (" + id_s
.join(",") + ")"
454 db
.parallelize(function() {
456 "DELETE FROM Games " +
457 "WHERE id " + suffix
;
460 "DELETE FROM Moves " +
461 "WHERE gid " + suffix
;
464 "DELETE FROM Chats " +
465 "WHERE gid " + suffix
;
470 cleanGamesDb: function() {
471 const tsNow
= Date
.now();
472 // 86400000 = 24 hours in milliseconds
473 const day
= 86400000;
474 db
.serialize(function() {
476 "SELECT id, created, cadence, score " +
478 db
.all(query
, (err
, games
) => {
480 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
483 db
.all(query
, (err2
, mstats
) => {
484 // Reorganize moves data to avoid too many array lookups:
485 let movesGroups
= {};
486 mstats
.forEach(ms
=> {
487 movesGroups
[ms
.gid
] = {
492 // Remove games still not really started,
493 // with no action in the last 2 weeks, or result != '*':
495 let lostOnTime
= [ [], [] ];
499 !movesGroups
[g
.id
] &&
500 (g
.score
!= '*' || tsNow
- g
.created
> 14*day
)
504 !!movesGroups
[g
.id
] &&
505 movesGroups
[g
.id
].nbMoves
== 1 &&
506 (g
.score
!= '*' || tsNow
- movesGroups
[g
.id
].lastMaj
> 14*day
)
511 // Set score if lost on time and >= 2 moves:
513 !!movesGroups
[g
.id
] &&
514 movesGroups
[g
.id
].nbMoves
>= 2 &&
515 tsNow
- movesGroups
[g
.id
].lastMaj
>
516 // cadence in days * nb seconds per day:
517 parseInt(g
.cadence
.slice(0, -1), 10) * day
519 lostOnTime
[movesGroups
[g
.id
].nbMoves
% 2].push(g
.id
);
522 if (toRemove
.length
> 0) GameModel
.remove(toRemove
);
523 if (lostOnTime
.some(l
=> l
.length
> 0)) {
524 db
.parallelize(function() {
525 for (let i
of [0, 1]) {
526 if (lostOnTime
[i
].length
> 0) {
527 const score
= (i
== 0 ? "0-1" : "1-0");
530 "SET score = '" + score
+ "', scoreMsg = 'Time' " +
531 "WHERE id IN (" + lostOnTime
[i
].join(',') + ")";
544 module
.exports
= GameModel
;