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, options, 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
) => {
148 // Query players names
151 if (!pids
[g
.white
]) pids
[g
.white
] = true;
152 if (!pids
[g
.black
]) pids
[g
.black
] = true;
154 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
157 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
170 { id: g
.white
, name: names
[g
.white
] },
171 { id: g
.black
, name: names
[g
.black
] }
182 // For display on MyGames: registered user only
183 getRunning: function(uid
, cb
) {
184 db
.serialize(function() {
186 "SELECT id, vid, cadence, options, created, white, black " +
188 "WHERE score = '*' AND (white = " + uid
+ " OR black = " + uid
+ ")";
189 db
.all(query
, (err
, games
) => {
191 // Get movesCount (could be done in // with next query)
193 "SELECT gid, COUNT(*) AS nbMoves " +
195 "WHERE gid IN " + "(" + games
.map(g
=> g
.id
).join(",") + ") " +
197 db
.all(query
, (err
, mstats
) => {
198 let movesCounts
= {};
199 mstats
.forEach(ms
=> { movesCounts
[ms
.gid
] = ms
.nbMoves
; });
200 // Query player names
203 if (!pids
[g
.white
]) pids
[g
.white
] = true;
204 if (!pids
[g
.black
]) pids
[g
.black
] = true;
206 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
209 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
221 movesCount: movesCounts
[g
.id
] || 0,
223 { id: g
.white
, name: names
[g
.white
] },
224 { id: g
.black
, name: names
[g
.black
] }
236 // These games could be deleted on some side. movesCount not required
237 getCompleted: function(uid
, cursor
, cb
) {
238 db
.serialize(function() {
240 "SELECT id, vid, cadence, options, created, score, scoreMsg, " +
241 "white, black, deletedByWhite, deletedByBlack " +
244 " score <> '*' AND" +
245 " created < " + cursor
+ " AND" +
248 " white = " + uid
+ " AND" +
249 " (deletedByWhite IS NULL OR NOT deletedByWhite)" +
253 " black = " + uid
+ " AND" +
254 " (deletedByBlack IS NULL OR NOT deletedByBlack)" +
258 "ORDER BY created DESC " +
260 db
.all(query
, (err
, games
) => {
262 // Query player names
265 if (!pids
[g
.white
]) pids
[g
.white
] = true;
266 if (!pids
[g
.black
]) pids
[g
.black
] = true;
268 UserModel
.getByIds(Object
.keys(pids
), (err2
, users
) => {
271 users
.forEach(u
=> { names
[u
.id
] = u
.name
; });
283 scoreMsg: g
.scoreMsg
,
285 { id: g
.white
, name: names
[g
.white
] },
286 { id: g
.black
, name: names
[g
.black
] }
288 deletedByWhite: g
.deletedByWhite
,
289 deletedByBlack: g
.deletedByBlack
299 getPlayers: function(id
, cb
) {
300 db
.serialize(function() {
302 "SELECT white, black " +
305 db
.get(query
, (err
, players
) => {
306 return cb(err
, players
);
311 checkGameUpdate: function(obj
) {
312 // Check all that is possible (required) in obj:
315 !obj
.move || !!(obj
.move.idx
.toString().match(/^[0-9]+$/))
317 !obj
.drawOffer
|| !!(obj
.drawOffer
.match(/^[wbtn]$/))
319 !obj
.rematchOffer
|| !!(obj
.rematchOffer
.match(/^[wbn]$/))
321 !obj
.fen
|| !!(obj
.fen
.match(/^[a-zA-Z0-9,.:{}\[\]" /-]*$/))
323 !obj
.score
|| !!(obj
.score
.match(/^[012?*\/-]+$/))
325 !obj
.chatRead
|| ['w','b'].includes(obj
.chatRead
)
327 !obj
.scoreMsg
|| !!(obj
.scoreMsg
.match(/^[a
-zA
-Z
]+$/))
329 !obj
.chat
|| UserModel
.checkNameEmail({name: obj
.chat
.name
})
334 // obj can have fields move, chat, fen, drawOffer and/or score + message
335 update: function(id
, obj
, cb
) {
336 db
.parallelize(function() {
341 // NOTE: if drawOffer is set, we should check that it's player's turn
342 // A bit overcomplicated. Let's trust the client on that for now...
343 if (!!obj
.drawOffer
) {
344 if (obj
.drawOffer
== "n")
345 // Special "None" update
347 modifs
+= "drawOffer = '" + obj
.drawOffer
+ "',";
349 if (!!obj
.rematchOffer
) {
350 if (obj
.rematchOffer
== "n")
351 // Special "None" update
352 obj
.rematchOffer
= "";
353 modifs
+= "rematchOffer = '" + obj
.rematchOffer
+ "',";
355 if (!!obj
.fen
) modifs
+= "fen = '" + obj
.fen
+ "',";
356 if (!!obj
.deletedBy
) {
357 const myColor
= obj
.deletedBy
== 'w' ? "White" : "Black";
358 modifs
+= "deletedBy" + myColor
+ " = true,";
360 if (!!obj
.chatRead
) {
361 const myColor
= obj
.chatRead
== 'w' ? "White" : "Black";
362 modifs
+= "chatRead" + myColor
+ " = " + Date
.now() + ",";
365 modifs
+= "score = '" + obj
.score
+ "'," +
366 "scoreMsg = '" + obj
.scoreMsg
+ "',";
368 const finishAndSendQuery
= () => {
369 modifs
= modifs
.slice(0, -1); //remove last comma
370 if (modifs
.length
> 0) {
371 updateQuery
+= modifs
+ " WHERE id = " + id
;
376 if (!!obj
.move || (!!obj
.score
&& obj
.scoreMsg
== "Time")) {
377 // Security: only update moves if index is right,
378 // and score with scoreMsg "Time" if really lost on time.
380 "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
383 db
.get(query
, (err
, ret
) => {
385 if (!ret
.maxIdx
|| ret
.maxIdx
+ 1 == obj
.move.idx
) {
387 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
388 "(" + id
+ ",?," + Date
.now() + "," + obj
.move.idx
+ ")";
389 db
.run(query
, JSON
.stringify(obj
.move.squares
));
390 finishAndSendQuery();
392 else cb({ errmsg: "Wrong move index" });
395 if (ret
.maxIdx
< 2) cb({ errmsg: "Time not over" });
397 // We also need the game cadence
402 db
.get(query
, (err2
, ret2
) => {
403 const daysTc
= parseInt(ret2
.cadence
.match(/^[0-9]+/)[0]);
404 if (Date
.now() - ret
.lastPlayed
> daysTc
* 24 * 3600 * 1000)
405 finishAndSendQuery();
406 else cb({ errmsg: "Time not over" });
412 else finishAndSendQuery();
413 // NOTE: chat and delchat are mutually exclusive
416 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
417 + id
+ ",?,'" + obj
.chat
.name
+ "'," + Date
.now() + ")";
418 db
.run(query
, obj
.chat
.msg
);
420 else if (obj
.delchat
) {
427 if (!!obj
.deletedBy
) {
428 // Did my opponent delete it too?
431 (obj
.deletedBy
== 'w' ? "Black" : "White") +
434 "SELECT " + selection
+ " " +
437 db
.get(query
, (err
,ret
) => {
438 // If yes: just remove game
439 if (!!ret
.deletedByOpp
) GameModel
.remove(id
);
445 remove: function(id_s
) {
448 ? " IN (" + id_s
.join(",") + ")"
450 db
.parallelize(function() {
452 "DELETE FROM Games " +
453 "WHERE id " + suffix
;
456 "DELETE FROM Moves " +
457 "WHERE gid " + suffix
;
460 "DELETE FROM Chats " +
461 "WHERE gid " + suffix
;
466 cleanGamesDb: function() {
467 const tsNow
= Date
.now();
468 // 86400000 = 24 hours in milliseconds
469 const day
= 86400000;
470 db
.serialize(function() {
472 "SELECT id, created, cadence, score " +
474 db
.all(query
, (err
, games
) => {
476 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
479 db
.all(query
, (err2
, mstats
) => {
480 // Reorganize moves data to avoid too many array lookups:
481 let movesGroups
= {};
482 mstats
.forEach(ms
=> {
483 movesGroups
[ms
.gid
] = {
488 // Remove games still not really started,
489 // with no action in the last 2 weeks, or result != '*':
491 let lostOnTime
= [ [], [] ];
495 !movesGroups
[g
.id
] &&
496 (g
.score
!= '*' || tsNow
- g
.created
> 14*day
)
500 !!movesGroups
[g
.id
] &&
501 movesGroups
[g
.id
].nbMoves
== 1 &&
502 (g
.score
!= '*' || tsNow
- movesGroups
[g
.id
].lastMaj
> 14*day
)
507 // Set score if lost on time and >= 2 moves:
510 !!movesGroups
[g
.id
] &&
511 movesGroups
[g
.id
].nbMoves
>= 2 &&
512 tsNow
- movesGroups
[g
.id
].lastMaj
>
513 // cadence in days * nb seconds per day:
514 parseInt(g
.cadence
.slice(0, -1), 10) * day
516 lostOnTime
[movesGroups
[g
.id
].nbMoves
% 2].push(g
.id
);
519 if (toRemove
.length
> 0) GameModel
.remove(toRemove
);
520 if (lostOnTime
.some(l
=> l
.length
> 0)) {
521 db
.parallelize(function() {
522 for (let i
of [0, 1]) {
523 if (lostOnTime
[i
].length
> 0) {
524 const score
= (i
== 0 ? "0-1" : "1-0");
527 "SET score = '" + score
+ "', scoreMsg = 'Time' " +
528 "WHERE id IN (" + lostOnTime
[i
].join(',') + ")";
541 module
.exports
= GameModel
;