Add temporary patch for preset challenges
[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 * options: varchar
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.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
44 g.players.length == 2 &&
45 g.players.every(p => p.id.toString().match(/^[0-9]+$/))
46 );
47 },
48
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
59 create: function(vid, fen, options, cadence, players, cb) {
60 db.serialize(function() {
61 let query =
62 "INSERT INTO Games " +
63 "(" +
64 "vid, fenStart, fen, options, " +
65 "white, black, " +
66 "cadence, created" +
67 ") " +
68 "VALUES " +
69 "(" +
70 vid + ",'" + fen + "','" + fen + "',?," +
71 players[0].id + "," + players[1].id + "," +
72 "'" + cadence + "'," + Date.now() +
73 ")";
74 db.run(query, options, function(err) {
75 cb(err, { id: this.lastID });
76 });
77 });
78 },
79
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() {
84 let query =
85 "SELECT " +
86 "id, vid, fen, fenStart, cadence, created, " +
87 "white, black, options, score, scoreMsg, " +
88 "chatReadWhite, chatReadBlack, drawOffer, rematchOffer " +
89 "FROM Games " +
90 "WHERE id = " + id;
91 db.get(query, (err, gameInfo) => {
92 if (!gameInfo) {
93 cb(err || { errmsg: "Game not found" }, undefined);
94 return;
95 }
96 query =
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"];
105 query =
106 "SELECT squares, played, idx " +
107 "FROM Moves " +
108 "WHERE gid = " + id;
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(
116 {
117 players: players,
118 moves: moves,
119 chats: chats
120 },
121 gameInfo
122 );
123 cb(null, game);
124 });
125 });
126 });
127 });
128 });
129 },
130
131 // For display on Hall: no need for moves or chats
132 getObserved: function(uid, cursor, cb) {
133 db.serialize(function() {
134 let query =
135 "SELECT id, vid, cadence, created, score, white, black " +
136 "FROM Games " +
137 "WHERE created < " + cursor + " ";
138 if (uid > 0) {
139 query +=
140 " AND white <> " + uid + " " +
141 " AND black <> " + uid + " ";
142 }
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(
157 err,
158 games.map(
159 g => {
160 return {
161 id: g.id,
162 vid: g.vid,
163 cadence: g.cadence,
164 created: g.created,
165 score: g.score,
166 players: [
167 { id: g.white, name: names[g.white] },
168 { id: g.black, name: names[g.black] }
169 ]
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() {
182 let query =
183 "SELECT id, vid, cadence, created, white, black " +
184 "FROM Games " +
185 "WHERE score = '*' AND (white = " + uid + " OR black = " + uid + ")";
186 db.all(query, (err, games) => {
187 // Get movesCount (could be done in // with next query)
188 query =
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 });
202 UserModel.getByIds(Object.keys(pids), (err2, users) => {
203 let names = {};
204 users.forEach(u => { names[u.id] = u.name; });
205 cb(
206 null,
207 games.map(
208 g => {
209 return {
210 id: g.id,
211 vid: g.vid,
212 cadence: g.cadence,
213 created: g.created,
214 score: g.score,
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 ]
220 };
221 }
222 )
223 );
224 });
225 });
226 });
227 });
228 },
229
230 // These games could be deleted on some side. movesCount not required
231 getCompleted: function(uid, cursor, cb) {
232 db.serialize(function() {
233 let query =
234 "SELECT id, vid, cadence, created, score, scoreMsg, " +
235 "white, black, deletedByWhite, deletedByBlack " +
236 "FROM Games " +
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 vid: g.vid,
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 !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9,.:{}\[\]" /-]*$/))
313 ) && (
314 !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
315 ) && (
316 !obj.chatRead || ['w','b'].includes(obj.chatRead)
317 ) && (
318 !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
319 ) && (
320 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
321 )
322 );
323 },
324
325 // obj can have fields move, chat, fen, drawOffer and/or score + message
326 update: function(id, obj, cb) {
327 db.parallelize(function() {
328 let updateQuery =
329 "UPDATE Games " +
330 "SET ";
331 let modifs = "";
332 // NOTE: if drawOffer is set, we should check that it's player's turn
333 // A bit overcomplicated. Let's trust the client on that for now...
334 if (!!obj.drawOffer) {
335 if (obj.drawOffer == "n")
336 // Special "None" update
337 obj.drawOffer = "";
338 modifs += "drawOffer = '" + obj.drawOffer + "',";
339 }
340 if (!!obj.rematchOffer) {
341 if (obj.rematchOffer == "n")
342 // Special "None" update
343 obj.rematchOffer = "";
344 modifs += "rematchOffer = '" + obj.rematchOffer + "',";
345 }
346 if (!!obj.fen) modifs += "fen = '" + obj.fen + "',";
347 if (!!obj.deletedBy) {
348 const myColor = obj.deletedBy == 'w' ? "White" : "Black";
349 modifs += "deletedBy" + myColor + " = true,";
350 }
351 if (!!obj.chatRead) {
352 const myColor = obj.chatRead == 'w' ? "White" : "Black";
353 modifs += "chatRead" + myColor + " = " + Date.now() + ",";
354 }
355 if (!!obj.score) {
356 modifs += "score = '" + obj.score + "'," +
357 "scoreMsg = '" + obj.scoreMsg + "',";
358 }
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 " +
372 "FROM Moves " +
373 "WHERE gid = " + id;
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();
382 }
383 else cb({ errmsg: "Wrong move index" });
384 }
385 else {
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) => {
394 const daysTc = parseInt(ret2.cadence.match(/^[0-9]+/)[0]);
395 if (Date.now() - ret.lastPlayed > daysTc * 24 * 3600 * 1000)
396 finishAndSendQuery();
397 else cb({ errmsg: "Time not over" });
398 });
399 }
400 }
401 });
402 }
403 else finishAndSendQuery();
404 // NOTE: chat and delchat are mutually exclusive
405 if (!!obj.chat) {
406 const query =
407 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
408 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
409 db.run(query, obj.chat.msg);
410 }
411 else if (obj.delchat) {
412 const query =
413 "DELETE " +
414 "FROM Chats " +
415 "WHERE gid = " + id;
416 db.run(query);
417 }
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";
424 const query =
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 }
433 });
434 },
435
436 remove: function(id_s) {
437 const suffix =
438 Array.isArray(id_s)
439 ? " IN (" + id_s.join(",") + ")"
440 : " = " + id_s;
441 db.parallelize(function() {
442 let query =
443 "DELETE FROM Games " +
444 "WHERE id " + suffix;
445 db.run(query);
446 query =
447 "DELETE FROM Moves " +
448 "WHERE gid " + suffix;
449 db.run(query);
450 query =
451 "DELETE FROM Chats " +
452 "WHERE gid " + suffix;
453 db.run(query);
454 });
455 },
456
457 cleanGamesDb: function() {
458 const tsNow = Date.now();
459 // 86400000 = 24 hours in milliseconds
460 const day = 86400000;
461 db.serialize(function() {
462 let query =
463 "SELECT id, created, cadence, score " +
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";
470 db.all(query, (err2, mstats) => {
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,
480 // with no action in the last 2 weeks, or result != '*':
481 let toRemove = [];
482 let lostOnTime = [ [], [] ];
483 games.forEach(g => {
484 if (
485 (
486 !movesGroups[g.id] &&
487 (g.score != '*' || tsNow - g.created > 14*day)
488 )
489 ||
490 (
491 !!movesGroups[g.id] &&
492 movesGroups[g.id].nbMoves == 1 &&
493 (g.score != '*' || tsNow - movesGroups[g.id].lastMaj > 14*day)
494 )
495 ) {
496 toRemove.push(g.id);
497 }
498 // Set score if lost on time and >= 2 moves:
499 else if (
500 g.score == '*' &&
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 }
509 });
510 if (toRemove.length > 0) GameModel.remove(toRemove);
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 }
525 });
526 });
527 });
528 }
529
530 };
531
532 module.exports = GameModel;