Adjustments
[vchess.git] / server / models / Game.js
CommitLineData
c5c47010 1const db = require("../utils/database");
58e7b94e 2const UserModel = require("./User");
00f2759e
BA
3
4/*
5 * Structure table Games:
6 * id: game id (int)
7 * vid: integer (variant id)
ab4f4bf2
BA
8 * fenStart: varchar (initial position)
9 * fen: varchar (current position)
0234201f
BA
10 * white: integer
11 * black: integer
71468011 12 * cadence: string
00f2759e 13 * score: varchar (result)
dcd68c41 14 * scoreMsg: varchar ("Time", "Mutual agreement"...)
83494c7f 15 * created: datetime
dfeb96ea 16 * drawOffer: char ('w','b' or '' for none)
0234201f 17 * rematchOffer: char (similar to drawOffer)
eb2d61de 18 * options: varchar
0234201f
BA
19 * deletedByWhite: boolean
20 * deletedByBlack: boolean
1ef65040
BA
21 * chatReadWhite: datetime
22 * chatReadBlack: datetime
00f2759e
BA
23 *
24 * Structure table Moves:
ab4f4bf2 25 * gid: ref game id
f41ce580 26 * squares: varchar (description)
00f2759e
BA
27 * played: datetime
28 * idx: integer
3837d4f7
BA
29 *
30 * Structure table Chats:
31 * gid: game id (int)
32 * msg: varchar
33 * name: varchar
3837d4f7 34 * added: datetime
00f2759e
BA
35 */
36
937c24ab
BA
37const GameModel = {
38
58e7b94e 39 checkGameInfo: function(g) {
866842c3
BA
40 return (
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 &&
f14572c4 45 g.players.every(p => p.id.toString().match(/^[0-9]+$/))
866842c3 46 );
58e7b94e
BA
47 },
48
4a209313
BA
49 incrementCounter: function(vid, cb) {
50 db.serialize(function() {
51 let query =
52 "UPDATE GameStat " +
53 "SET total = total + 1 " +
54 "WHERE vid = " + vid;
55 db.run(query, cb);
56 });
57 },
58
eb2d61de 59 create: function(vid, fen, options, cadence, players, cb) {
dac39588
BA
60 db.serialize(function() {
61 let query =
71468011 62 "INSERT INTO Games " +
0234201f 63 "(" +
eb2d61de 64 "vid, fenStart, fen, options, " +
0234201f
BA
65 "white, black, " +
66 "cadence, created" +
67 ") " +
71468011 68 "VALUES " +
0234201f 69 "(" +
eb2d61de 70 vid + ",'" + fen + "','" + fen + "',?," +
f14572c4 71 players[0].id + "," + players[1].id + "," +
0234201f
BA
72 "'" + cadence + "'," + Date.now() +
73 ")";
eb2d61de 74 db.run(query, options, function(err) {
f14572c4 75 cb(err, { id: this.lastID });
dac39588
BA
76 });
77 });
78 },
00f2759e 79
71468011 80 // TODO: some queries here could be async
0234201f 81 getOne: function(id, cb) {
866842c3 82 // NOTE: ignoring errors (shouldn't happen at this stage)
dac39588 83 db.serialize(function() {
dac39588 84 let query =
0234201f 85 "SELECT " +
eaa5ad3e 86 "id, vid, fen, fenStart, cadence, created, " +
eb2d61de 87 "white, black, options, score, scoreMsg, " +
eaa5ad3e
BA
88 "chatReadWhite, chatReadBlack, drawOffer, rematchOffer " +
89 "FROM Games " +
90 "WHERE id = " + id;
aae89b49 91 db.get(query, (err, gameInfo) => {
f14572c4
BA
92 if (!gameInfo) {
93 cb(err || { errmsg: "Game not found" }, undefined);
94 return;
95 }
dac39588 96 query =
f14572c4
BA
97 "SELECT id, name " +
98 "FROM Users " +
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"];
aae89b49 105 query =
f14572c4
BA
106 "SELECT squares, played, idx " +
107 "FROM Moves " +
aae89b49 108 "WHERE gid = " + id;
f14572c4
BA
109 db.all(query, (err3, moves) => {
110 query =
111 "SELECT msg, name, added " +
112 "FROM Chats " +
113 "WHERE gid = " + id;
114 db.all(query, (err4, chats) => {
115 const game = Object.assign(
f14572c4
BA
116 {
117 players: players,
118 moves: moves,
119 chats: chats
eaa5ad3e
BA
120 },
121 gameInfo
f14572c4
BA
122 );
123 cb(null, game);
124 });
aae89b49 125 });
dac39588
BA
126 });
127 });
128 });
129 },
00f2759e 130
0234201f
BA
131 // For display on Hall: no need for moves or chats
132 getObserved: function(uid, cursor, cb) {
133 db.serialize(function() {
134 let query =
3d9745ae 135 "SELECT id, vid, cadence, options, created, score, white, black " +
6c7cbfed
BA
136 "FROM Games " +
137 "WHERE created < " + cursor + " ";
138 if (uid > 0) {
139 query +=
140 " AND white <> " + uid + " " +
141 " AND black <> " + uid + " ";
142 }
0234201f
BA
143 query +=
144 "ORDER BY created DESC " +
145 "LIMIT 20"; //TODO: 20 hard-coded...
146 db.all(query, (err, games) => {
147 // Query players names
148 let pids = {};
149 games.forEach(g => {
150 if (!pids[g.white]) pids[g.white] = true;
151 if (!pids[g.black]) pids[g.black] = true;
152 });
153 UserModel.getByIds(Object.keys(pids), (err2, users) => {
154 let names = {};
155 users.forEach(u => { names[u.id] = u.name; });
156 cb(
f14572c4 157 err,
0234201f
BA
158 games.map(
159 g => {
160 return {
161 id: g.id,
f14572c4 162 vid: g.vid,
0234201f 163 cadence: g.cadence,
3d9745ae 164 options: g.options,
0234201f
BA
165 created: g.created,
166 score: g.score,
f14572c4
BA
167 players: [
168 { id: g.white, name: names[g.white] },
169 { id: g.black, name: names[g.black] }
170 ]
0234201f
BA
171 };
172 }
173 )
174 );
175 });
176 });
177 });
178 },
179
180 // For display on MyGames: registered user only
181 getRunning: function(uid, cb) {
182 db.serialize(function() {
aae89b49 183 let query =
3d9745ae 184 "SELECT id, vid, cadence, options, created, white, black " +
eaa5ad3e 185 "FROM Games " +
f14572c4 186 "WHERE score = '*' AND (white = " + uid + " OR black = " + uid + ")";
0234201f
BA
187 db.all(query, (err, games) => {
188 // Get movesCount (could be done in // with next query)
aae89b49 189 query =
0234201f
BA
190 "SELECT gid, COUNT(*) AS nbMoves " +
191 "FROM Moves " +
192 "WHERE gid IN " + "(" + games.map(g => g.id).join(",") + ") " +
193 "GROUP BY gid";
194 db.all(query, (err, mstats) => {
195 let movesCounts = {};
196 mstats.forEach(ms => { movesCounts[ms.gid] = ms.nbMoves; });
197 // Query player names
198 let pids = {};
199 games.forEach(g => {
200 if (!pids[g.white]) pids[g.white] = true;
201 if (!pids[g.black]) pids[g.black] = true;
202 });
f14572c4 203 UserModel.getByIds(Object.keys(pids), (err2, users) => {
0234201f
BA
204 let names = {};
205 users.forEach(u => { names[u.id] = u.name; });
206 cb(
f14572c4 207 null,
0234201f
BA
208 games.map(
209 g => {
210 return {
211 id: g.id,
d807470f 212 vid: g.vid,
f14572c4 213 cadence: g.cadence,
3d9745ae 214 options: g.options,
0234201f
BA
215 created: g.created,
216 score: g.score,
f14572c4
BA
217 movesCount: movesCounts[g.id] || 0,
218 players: [
219 { id: g.white, name: names[g.white] },
220 { id: g.black, name: names[g.black] }
221 ]
0234201f
BA
222 };
223 }
224 )
aae89b49 225 );
aae89b49
BA
226 });
227 });
228 });
0234201f
BA
229 });
230 },
231
232 // These games could be deleted on some side. movesCount not required
233 getCompleted: function(uid, cursor, cb) {
dac39588 234 db.serialize(function() {
0234201f 235 let query =
3d9745ae 236 "SELECT id, vid, cadence, options, created, score, scoreMsg, " +
eaa5ad3e
BA
237 "white, black, deletedByWhite, deletedByBlack " +
238 "FROM Games " +
0234201f 239 "WHERE " +
11589e7c
BA
240 " score <> '*' AND" +
241 " created < " + cursor + " AND" +
0234201f 242 " (" +
11589e7c
BA
243 " (" +
244 " white = " + uid + " AND" +
245 " (deletedByWhite IS NULL OR NOT deletedByWhite)" +
246 " )" +
247 " OR " +
248 " (" +
249 " black = " + uid + " AND" +
250 " (deletedByBlack IS NULL OR NOT deletedByBlack)" +
251 " )" +
0234201f
BA
252 " ) ";
253 query +=
254 "ORDER BY created DESC " +
255 "LIMIT 20";
256 db.all(query, (err, games) => {
257 // Query player names
258 let pids = {};
259 games.forEach(g => {
260 if (!pids[g.white]) pids[g.white] = true;
261 if (!pids[g.black]) pids[g.black] = true;
262 });
f14572c4 263 UserModel.getByIds(Object.keys(pids), (err2, users) => {
0234201f
BA
264 let names = {};
265 users.forEach(u => { names[u.id] = u.name; });
266 cb(
f14572c4 267 null,
0234201f
BA
268 games.map(
269 g => {
270 return {
271 id: g.id,
eaa5ad3e 272 vid: g.vid,
f14572c4 273 cadence: g.cadence,
3d9745ae 274 options: g.options,
0234201f
BA
275 created: g.created,
276 score: g.score,
277 scoreMsg: g.scoreMsg,
f14572c4
BA
278 players: [
279 { id: g.white, name: names[g.white] },
280 { id: g.black, name: names[g.black] }
281 ],
0234201f
BA
282 deletedByWhite: g.deletedByWhite,
283 deletedByBlack: g.deletedByBlack
284 };
285 }
286 )
287 );
288 });
dac39588
BA
289 });
290 });
291 },
ab4f4bf2 292
0234201f 293 getPlayers: function(id, cb) {
411d23cd
BA
294 db.serialize(function() {
295 const query =
0234201f
BA
296 "SELECT white, black " +
297 "FROM Games " +
f14572c4
BA
298 "WHERE id = " + id;
299 db.get(query, (err, players) => {
411d23cd
BA
300 return cb(err, players);
301 });
302 });
303 },
304
0234201f 305 checkGameUpdate: function(obj) {
58e7b94e 306 // Check all that is possible (required) in obj:
866842c3
BA
307 return (
308 (
8be8238c 309 !obj.move || !!(obj.move.idx.toString().match(/^[0-9]+$/))
866842c3 310 ) && (
188b4a8f 311 !obj.drawOffer || !!(obj.drawOffer.match(/^[wbtn]$/))
c292ebb2
BA
312 ) && (
313 !obj.rematchOffer || !!(obj.rematchOffer.match(/^[wbn]$/))
866842c3 314 ) && (
5c4ea2bb 315 !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9,.:{}\[\]" /-]*$/))
866842c3 316 ) && (
188b4a8f 317 !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
1ef65040 318 ) && (
077ba344 319 !obj.chatRead || ['w','b'].includes(obj.chatRead)
866842c3 320 ) && (
188b4a8f 321 !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
866842c3
BA
322 ) && (
323 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
324 )
325 );
58e7b94e
BA
326 },
327
866842c3 328 // obj can have fields move, chat, fen, drawOffer and/or score + message
0234201f 329 update: function(id, obj, cb) {
dac39588 330 db.parallelize(function() {
f14572c4 331 let updateQuery =
3d55deea
BA
332 "UPDATE Games " +
333 "SET ";
3837d4f7 334 let modifs = "";
633959bf 335 // NOTE: if drawOffer is set, we should check that it's player's turn
dfeb96ea 336 // A bit overcomplicated. Let's trust the client on that for now...
f14572c4
BA
337 if (!!obj.drawOffer) {
338 if (obj.drawOffer == "n")
339 // Special "None" update
633959bf
BA
340 obj.drawOffer = "";
341 modifs += "drawOffer = '" + obj.drawOffer + "',";
342 }
f14572c4
BA
343 if (!!obj.rematchOffer) {
344 if (obj.rematchOffer == "n")
345 // Special "None" update
c292ebb2
BA
346 obj.rematchOffer = "";
347 modifs += "rematchOffer = '" + obj.rematchOffer + "',";
348 }
f14572c4 349 if (!!obj.fen) modifs += "fen = '" + obj.fen + "',";
aae89b49
BA
350 if (!!obj.deletedBy) {
351 const myColor = obj.deletedBy == 'w' ? "White" : "Black";
352 modifs += "deletedBy" + myColor + " = true,";
353 }
1ef65040
BA
354 if (!!obj.chatRead) {
355 const myColor = obj.chatRead == 'w' ? "White" : "Black";
356 modifs += "chatRead" + myColor + " = " + Date.now() + ",";
357 }
f14572c4
BA
358 if (!!obj.score) {
359 modifs += "score = '" + obj.score + "'," +
360 "scoreMsg = '" + obj.scoreMsg + "',";
3837d4f7 361 }
f14572c4
BA
362 const finishAndSendQuery = () => {
363 modifs = modifs.slice(0, -1); //remove last comma
364 if (modifs.length > 0) {
365 updateQuery += modifs + " WHERE id = " + id;
366 db.run(updateQuery);
367 }
368 cb(null);
369 };
370 if (!!obj.move || (!!obj.score && obj.scoreMsg == "Time")) {
371 // Security: only update moves if index is right,
372 // and score with scoreMsg "Time" if really lost on time.
373 let query =
374 "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
fb68b0c2
BA
375 "FROM Moves " +
376 "WHERE gid = " + id;
f14572c4
BA
377 db.get(query, (err, ret) => {
378 if (!!obj.move ) {
379 if (!ret.maxIdx || ret.maxIdx + 1 == obj.move.idx) {
380 query =
381 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
382 "(" + id + ",?," + Date.now() + "," + obj.move.idx + ")";
383 db.run(query, JSON.stringify(obj.move.squares));
384 finishAndSendQuery();
58aedcd1
BA
385 }
386 else cb({ errmsg: "Wrong move index" });
387 }
388 else {
f14572c4
BA
389 if (ret.maxIdx < 2) cb({ errmsg: "Time not over" });
390 else {
391 // We also need the game cadence
392 query =
393 "SELECT cadence " +
394 "FROM Games " +
395 "WHERE id = " + id;
396 db.get(query, (err2, ret2) => {
1112f1fd 397 const daysTc = parseInt(ret2.cadence.match(/^[0-9]+/)[0]);
f14572c4
BA
398 if (Date.now() - ret.lastPlayed > daysTc * 24 * 3600 * 1000)
399 finishAndSendQuery();
400 else cb({ errmsg: "Time not over" });
401 });
402 }
fb68b0c2 403 }
fb68b0c2 404 });
58aedcd1
BA
405 }
406 else finishAndSendQuery();
f14572c4
BA
407 // NOTE: chat and delchat are mutually exclusive
408 if (!!obj.chat) {
409 const query =
dac39588 410 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 411 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 412 db.run(query, obj.chat.msg);
58aedcd1
BA
413 }
414 else if (obj.delchat) {
f14572c4 415 const query =
db1f1f9a
BA
416 "DELETE " +
417 "FROM Chats " +
418 "WHERE gid = " + id;
23ecf008 419 db.run(query);
db1f1f9a 420 }
aae89b49
BA
421 if (!!obj.deletedBy) {
422 // Did my opponent delete it too?
423 let selection =
424 "deletedBy" +
425 (obj.deletedBy == 'w' ? "Black" : "White") +
426 " AS deletedByOpp";
f14572c4 427 const query =
aae89b49
BA
428 "SELECT " + selection + " " +
429 "FROM Games " +
430 "WHERE id = " + id;
431 db.get(query, (err,ret) => {
432 // If yes: just remove game
433 if (!!ret.deletedByOpp) GameModel.remove(id);
434 });
435 }
3d55deea
BA
436 });
437 },
438
0234201f
BA
439 remove: function(id_s) {
440 const suffix =
441 Array.isArray(id_s)
442 ? " IN (" + id_s.join(",") + ")"
443 : " = " + id_s;
dac39588
BA
444 db.parallelize(function() {
445 let query =
446 "DELETE FROM Games " +
0234201f 447 "WHERE id " + suffix;
dac39588
BA
448 db.run(query);
449 query =
450 "DELETE FROM Moves " +
0234201f 451 "WHERE gid " + suffix;
dac39588
BA
452 db.run(query);
453 query =
454 "DELETE FROM Chats " +
0234201f 455 "WHERE gid " + suffix;
dac39588
BA
456 db.run(query);
457 });
458 },
d431028c 459
0234201f 460 cleanGamesDb: function() {
d431028c
BA
461 const tsNow = Date.now();
462 // 86400000 = 24 hours in milliseconds
463 const day = 86400000;
464 db.serialize(function() {
465 let query =
7ec05c0e 466 "SELECT id, created, cadence, score " +
0234201f
BA
467 "FROM Games";
468 db.all(query, (err, games) => {
469 query =
470 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
471 "FROM Moves " +
472 "GROUP BY gid";
6f2f9437 473 db.all(query, (err2, mstats) => {
0234201f
BA
474 // Reorganize moves data to avoid too many array lookups:
475 let movesGroups = {};
476 mstats.forEach(ms => {
477 movesGroups[ms.gid] = {
478 nbMoves: ms.nbMoves,
479 lastMaj: ms.lastMaj
480 };
481 });
482 // Remove games still not really started,
7ec05c0e 483 // with no action in the last 2 weeks, or result != '*':
0234201f 484 let toRemove = [];
7ec05c0e 485 let lostOnTime = [ [], [] ];
0234201f
BA
486 games.forEach(g => {
487 if (
488 (
489 !movesGroups[g.id] &&
7ec05c0e 490 (g.score != '*' || tsNow - g.created > 14*day)
0234201f
BA
491 )
492 ||
493 (
b49527c4 494 !!movesGroups[g.id] &&
0234201f 495 movesGroups[g.id].nbMoves == 1 &&
7ec05c0e 496 (g.score != '*' || tsNow - movesGroups[g.id].lastMaj > 14*day)
0234201f
BA
497 )
498 ) {
499 toRemove.push(g.id);
d431028c 500 }
7ec05c0e
BA
501 // Set score if lost on time and >= 2 moves:
502 else if (
b5ead37a 503 g.score == '*' &&
7ec05c0e
BA
504 !!movesGroups[g.id] &&
505 movesGroups[g.id].nbMoves >= 2 &&
506 tsNow - movesGroups[g.id].lastMaj >
507 // cadence in days * nb seconds per day:
508 parseInt(g.cadence.slice(0, -1), 10) * day
509 ) {
510 lostOnTime[movesGroups[g.id].nbMoves % 2].push(g.id);
511 }
d431028c 512 });
0234201f 513 if (toRemove.length > 0) GameModel.remove(toRemove);
7ec05c0e
BA
514 if (lostOnTime.some(l => l.length > 0)) {
515 db.parallelize(function() {
516 for (let i of [0, 1]) {
517 if (lostOnTime[i].length > 0) {
518 const score = (i == 0 ? "0-1" : "1-0");
519 const query =
520 "UPDATE Games " +
521 "SET score = '" + score + "', scoreMsg = 'Time' " +
522 "WHERE id IN (" + lostOnTime[i].join(',') + ")";
523 db.run(query);
524 }
525 }
526 });
527 }
d431028c
BA
528 });
529 });
530 });
0234201f 531 }
937c24ab
BA
532
533};
ab4f4bf2
BA
534
535module.exports = GameModel;