Experimental change: options replacing randomness (more general)
[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 =
f14572c4 135 "SELECT id, vid, cadence, 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,
0234201f
BA
164 created: g.created,
165 score: g.score,
f14572c4
BA
166 players: [
167 { id: g.white, name: names[g.white] },
168 { id: g.black, name: names[g.black] }
169 ]
0234201f
BA
170 };
171 }
172 )
173 );
174 });
175 });
176 });
177 },
178
179 // For display on MyGames: registered user only
180 getRunning: function(uid, cb) {
181 db.serialize(function() {
aae89b49 182 let query =
eaa5ad3e
BA
183 "SELECT id, vid, cadence, created, white, black " +
184 "FROM Games " +
f14572c4 185 "WHERE score = '*' AND (white = " + uid + " OR black = " + uid + ")";
0234201f
BA
186 db.all(query, (err, games) => {
187 // Get movesCount (could be done in // with next query)
aae89b49 188 query =
0234201f
BA
189 "SELECT gid, COUNT(*) AS nbMoves " +
190 "FROM Moves " +
191 "WHERE gid IN " + "(" + games.map(g => g.id).join(",") + ") " +
192 "GROUP BY gid";
193 db.all(query, (err, mstats) => {
194 let movesCounts = {};
195 mstats.forEach(ms => { movesCounts[ms.gid] = ms.nbMoves; });
196 // Query player names
197 let pids = {};
198 games.forEach(g => {
199 if (!pids[g.white]) pids[g.white] = true;
200 if (!pids[g.black]) pids[g.black] = true;
201 });
f14572c4 202 UserModel.getByIds(Object.keys(pids), (err2, users) => {
0234201f
BA
203 let names = {};
204 users.forEach(u => { names[u.id] = u.name; });
205 cb(
f14572c4 206 null,
0234201f
BA
207 games.map(
208 g => {
209 return {
210 id: g.id,
d807470f 211 vid: g.vid,
f14572c4 212 cadence: g.cadence,
0234201f
BA
213 created: g.created,
214 score: g.score,
f14572c4
BA
215 movesCount: movesCounts[g.id] || 0,
216 players: [
217 { id: g.white, name: names[g.white] },
218 { id: g.black, name: names[g.black] }
219 ]
0234201f
BA
220 };
221 }
222 )
aae89b49 223 );
aae89b49
BA
224 });
225 });
226 });
0234201f
BA
227 });
228 },
229
230 // These games could be deleted on some side. movesCount not required
231 getCompleted: function(uid, cursor, cb) {
dac39588 232 db.serialize(function() {
0234201f 233 let query =
eaa5ad3e
BA
234 "SELECT id, vid, cadence, created, score, scoreMsg, " +
235 "white, black, deletedByWhite, deletedByBlack " +
236 "FROM Games " +
0234201f 237 "WHERE " +
11589e7c
BA
238 " score <> '*' AND" +
239 " created < " + cursor + " AND" +
0234201f 240 " (" +
11589e7c
BA
241 " (" +
242 " white = " + uid + " AND" +
243 " (deletedByWhite IS NULL OR NOT deletedByWhite)" +
244 " )" +
245 " OR " +
246 " (" +
247 " black = " + uid + " AND" +
248 " (deletedByBlack IS NULL OR NOT deletedByBlack)" +
249 " )" +
0234201f
BA
250 " ) ";
251 query +=
252 "ORDER BY created DESC " +
253 "LIMIT 20";
254 db.all(query, (err, games) => {
255 // Query player names
256 let pids = {};
257 games.forEach(g => {
258 if (!pids[g.white]) pids[g.white] = true;
259 if (!pids[g.black]) pids[g.black] = true;
260 });
f14572c4 261 UserModel.getByIds(Object.keys(pids), (err2, users) => {
0234201f
BA
262 let names = {};
263 users.forEach(u => { names[u.id] = u.name; });
264 cb(
f14572c4 265 null,
0234201f
BA
266 games.map(
267 g => {
268 return {
269 id: g.id,
eaa5ad3e 270 vid: g.vid,
f14572c4 271 cadence: g.cadence,
0234201f
BA
272 created: g.created,
273 score: g.score,
274 scoreMsg: g.scoreMsg,
f14572c4
BA
275 players: [
276 { id: g.white, name: names[g.white] },
277 { id: g.black, name: names[g.black] }
278 ],
0234201f
BA
279 deletedByWhite: g.deletedByWhite,
280 deletedByBlack: g.deletedByBlack
281 };
282 }
283 )
284 );
285 });
dac39588
BA
286 });
287 });
288 },
ab4f4bf2 289
0234201f 290 getPlayers: function(id, cb) {
411d23cd
BA
291 db.serialize(function() {
292 const query =
0234201f
BA
293 "SELECT white, black " +
294 "FROM Games " +
f14572c4
BA
295 "WHERE id = " + id;
296 db.get(query, (err, players) => {
411d23cd
BA
297 return cb(err, players);
298 });
299 });
300 },
301
0234201f 302 checkGameUpdate: function(obj) {
58e7b94e 303 // Check all that is possible (required) in obj:
866842c3
BA
304 return (
305 (
8be8238c 306 !obj.move || !!(obj.move.idx.toString().match(/^[0-9]+$/))
866842c3 307 ) && (
188b4a8f 308 !obj.drawOffer || !!(obj.drawOffer.match(/^[wbtn]$/))
c292ebb2
BA
309 ) && (
310 !obj.rematchOffer || !!(obj.rematchOffer.match(/^[wbn]$/))
866842c3 311 ) && (
5c4ea2bb 312 !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9,.:{}\[\]" /-]*$/))
866842c3 313 ) && (
188b4a8f 314 !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
1ef65040 315 ) && (
077ba344 316 !obj.chatRead || ['w','b'].includes(obj.chatRead)
866842c3 317 ) && (
188b4a8f 318 !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
866842c3
BA
319 ) && (
320 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
321 )
322 );
58e7b94e
BA
323 },
324
866842c3 325 // obj can have fields move, chat, fen, drawOffer and/or score + message
0234201f 326 update: function(id, obj, cb) {
dac39588 327 db.parallelize(function() {
f14572c4 328 let updateQuery =
3d55deea
BA
329 "UPDATE Games " +
330 "SET ";
3837d4f7 331 let modifs = "";
633959bf 332 // NOTE: if drawOffer is set, we should check that it's player's turn
dfeb96ea 333 // A bit overcomplicated. Let's trust the client on that for now...
f14572c4
BA
334 if (!!obj.drawOffer) {
335 if (obj.drawOffer == "n")
336 // Special "None" update
633959bf
BA
337 obj.drawOffer = "";
338 modifs += "drawOffer = '" + obj.drawOffer + "',";
339 }
f14572c4
BA
340 if (!!obj.rematchOffer) {
341 if (obj.rematchOffer == "n")
342 // Special "None" update
c292ebb2
BA
343 obj.rematchOffer = "";
344 modifs += "rematchOffer = '" + obj.rematchOffer + "',";
345 }
f14572c4 346 if (!!obj.fen) modifs += "fen = '" + obj.fen + "',";
aae89b49
BA
347 if (!!obj.deletedBy) {
348 const myColor = obj.deletedBy == 'w' ? "White" : "Black";
349 modifs += "deletedBy" + myColor + " = true,";
350 }
1ef65040
BA
351 if (!!obj.chatRead) {
352 const myColor = obj.chatRead == 'w' ? "White" : "Black";
353 modifs += "chatRead" + myColor + " = " + Date.now() + ",";
354 }
f14572c4
BA
355 if (!!obj.score) {
356 modifs += "score = '" + obj.score + "'," +
357 "scoreMsg = '" + obj.scoreMsg + "',";
3837d4f7 358 }
f14572c4
BA
359 const finishAndSendQuery = () => {
360 modifs = modifs.slice(0, -1); //remove last comma
361 if (modifs.length > 0) {
362 updateQuery += modifs + " WHERE id = " + id;
363 db.run(updateQuery);
364 }
365 cb(null);
366 };
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.
370 let query =
371 "SELECT MAX(idx) AS maxIdx, MAX(played) AS lastPlayed " +
fb68b0c2
BA
372 "FROM Moves " +
373 "WHERE gid = " + id;
f14572c4
BA
374 db.get(query, (err, ret) => {
375 if (!!obj.move ) {
376 if (!ret.maxIdx || ret.maxIdx + 1 == obj.move.idx) {
377 query =
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();
58aedcd1
BA
382 }
383 else cb({ errmsg: "Wrong move index" });
384 }
385 else {
f14572c4
BA
386 if (ret.maxIdx < 2) cb({ errmsg: "Time not over" });
387 else {
388 // We also need the game cadence
389 query =
390 "SELECT cadence " +
391 "FROM Games " +
392 "WHERE id = " + id;
393 db.get(query, (err2, ret2) => {
1112f1fd 394 const daysTc = parseInt(ret2.cadence.match(/^[0-9]+/)[0]);
f14572c4
BA
395 if (Date.now() - ret.lastPlayed > daysTc * 24 * 3600 * 1000)
396 finishAndSendQuery();
397 else cb({ errmsg: "Time not over" });
398 });
399 }
fb68b0c2 400 }
fb68b0c2 401 });
58aedcd1
BA
402 }
403 else finishAndSendQuery();
f14572c4
BA
404 // NOTE: chat and delchat are mutually exclusive
405 if (!!obj.chat) {
406 const query =
dac39588 407 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 408 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 409 db.run(query, obj.chat.msg);
58aedcd1
BA
410 }
411 else if (obj.delchat) {
f14572c4 412 const query =
db1f1f9a
BA
413 "DELETE " +
414 "FROM Chats " +
415 "WHERE gid = " + id;
23ecf008 416 db.run(query);
db1f1f9a 417 }
aae89b49
BA
418 if (!!obj.deletedBy) {
419 // Did my opponent delete it too?
420 let selection =
421 "deletedBy" +
422 (obj.deletedBy == 'w' ? "Black" : "White") +
423 " AS deletedByOpp";
f14572c4 424 const query =
aae89b49
BA
425 "SELECT " + selection + " " +
426 "FROM Games " +
427 "WHERE id = " + id;
428 db.get(query, (err,ret) => {
429 // If yes: just remove game
430 if (!!ret.deletedByOpp) GameModel.remove(id);
431 });
432 }
3d55deea
BA
433 });
434 },
435
0234201f
BA
436 remove: function(id_s) {
437 const suffix =
438 Array.isArray(id_s)
439 ? " IN (" + id_s.join(",") + ")"
440 : " = " + id_s;
dac39588
BA
441 db.parallelize(function() {
442 let query =
443 "DELETE FROM Games " +
0234201f 444 "WHERE id " + suffix;
dac39588
BA
445 db.run(query);
446 query =
447 "DELETE FROM Moves " +
0234201f 448 "WHERE gid " + suffix;
dac39588
BA
449 db.run(query);
450 query =
451 "DELETE FROM Chats " +
0234201f 452 "WHERE gid " + suffix;
dac39588
BA
453 db.run(query);
454 });
455 },
d431028c 456
0234201f 457 cleanGamesDb: function() {
d431028c
BA
458 const tsNow = Date.now();
459 // 86400000 = 24 hours in milliseconds
460 const day = 86400000;
461 db.serialize(function() {
462 let query =
7ec05c0e 463 "SELECT id, created, cadence, score " +
0234201f
BA
464 "FROM Games";
465 db.all(query, (err, games) => {
466 query =
467 "SELECT gid, count(*) AS nbMoves, MAX(played) AS lastMaj " +
468 "FROM Moves " +
469 "GROUP BY gid";
6f2f9437 470 db.all(query, (err2, mstats) => {
0234201f
BA
471 // Reorganize moves data to avoid too many array lookups:
472 let movesGroups = {};
473 mstats.forEach(ms => {
474 movesGroups[ms.gid] = {
475 nbMoves: ms.nbMoves,
476 lastMaj: ms.lastMaj
477 };
478 });
479 // Remove games still not really started,
7ec05c0e 480 // with no action in the last 2 weeks, or result != '*':
0234201f 481 let toRemove = [];
7ec05c0e 482 let lostOnTime = [ [], [] ];
0234201f
BA
483 games.forEach(g => {
484 if (
485 (
486 !movesGroups[g.id] &&
7ec05c0e 487 (g.score != '*' || tsNow - g.created > 14*day)
0234201f
BA
488 )
489 ||
490 (
b49527c4 491 !!movesGroups[g.id] &&
0234201f 492 movesGroups[g.id].nbMoves == 1 &&
7ec05c0e 493 (g.score != '*' || tsNow - movesGroups[g.id].lastMaj > 14*day)
0234201f
BA
494 )
495 ) {
496 toRemove.push(g.id);
d431028c 497 }
7ec05c0e
BA
498 // Set score if lost on time and >= 2 moves:
499 else if (
b5ead37a 500 g.score == '*' &&
7ec05c0e
BA
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
506 ) {
507 lostOnTime[movesGroups[g.id].nbMoves % 2].push(g.id);
508 }
d431028c 509 });
0234201f 510 if (toRemove.length > 0) GameModel.remove(toRemove);
7ec05c0e
BA
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");
516 const query =
517 "UPDATE Games " +
518 "SET score = '" + score + "', scoreMsg = 'Time' " +
519 "WHERE id IN (" + lostOnTime[i].join(',') + ")";
520 db.run(query);
521 }
522 }
523 });
524 }
d431028c
BA
525 });
526 });
527 });
0234201f 528 }
937c24ab
BA
529
530};
ab4f4bf2
BA
531
532module.exports = GameModel;