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