Fix rematch process
[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 * cadence: string
11 * score: varchar (result)
12 * scoreMsg: varchar ("Time", "Mutual agreement"...)
13 * created: datetime
14 * drawOffer: char ('w','b' or '' for none)
15 *
16 * Structure table Players:
17 * gid: ref game id
18 * uid: ref user id
19 * color: character
20 *
21 * Structure table Moves:
22 * gid: ref game id
23 * squares: varchar (description)
24 * played: datetime
25 * idx: integer
26 *
27 * Structure table Chats:
28 * gid: game id (int)
29 * msg: varchar
30 * name: varchar
31 * added: datetime
32 */
33
34 const GameModel =
35 {
36 checkGameInfo: function(g) {
37 return (
38 g.vid.toString().match(/^[0-9]+$/) &&
39 g.cadence.match(/^[0-9dhms +]+$/) &&
40 g.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
41 g.players.length == 2 &&
42 g.players.every(p => p.uid.toString().match(/^[0-9]+$/))
43 );
44 },
45
46 create: function(vid, fen, cadence, players, cb)
47 {
48 db.serialize(function() {
49 let query =
50 "INSERT INTO Games " +
51 "(vid, fenStart, fen, cadence, created) " +
52 "VALUES " +
53 "(" + vid + ",'" + fen + "','" + fen + "','" + cadence + "'," + Date.now() + ")";
54 db.run(query, function(err) {
55 if (err)
56 cb(err)
57 else
58 {
59 players.forEach((p,idx) => {
60 const color = (idx==0 ? "w" : "b");
61 query =
62 "INSERT INTO Players VALUES " +
63 "(" + this.lastID + "," + p.uid + ",'" + color + "')";
64 db.run(query);
65 });
66 cb(null, {gid: this.lastID});
67 }
68 });
69 });
70 },
71
72 // TODO: some queries here could be async
73 getOne: function(id, cb)
74 {
75 // NOTE: ignoring errors (shouldn't happen at this stage)
76 db.serialize(function() {
77 let query =
78 "SELECT g.id, g.vid, g.fen, g.fenStart, g.cadence, g.created, g.score, " +
79 "g.scoreMsg, g.drawOffer, g.rematchOffer, v.name AS vname " +
80 "FROM Games g " +
81 "JOIN Variants v " +
82 " ON g.vid = v.id " +
83 "WHERE g.id = " + id;
84 db.get(query, (err, gameInfo) => {
85 query =
86 "SELECT p.uid, p.color, u.name " +
87 "FROM Players p " +
88 "JOIN Users u " +
89 " ON p.uid = u.id " +
90 "WHERE p.gid = " + id;
91 db.all(query, (err2, players) => {
92 query =
93 "SELECT squares, played, idx " +
94 "FROM Moves " +
95 "WHERE gid = " + id;
96 db.all(query, (err3, moves) => {
97 query =
98 "SELECT msg, name, added " +
99 "FROM Chats " +
100 "WHERE gid = " + id;
101 db.all(query, (err4, chats) => {
102 const game = Object.assign(
103 {},
104 gameInfo,
105 {
106 players: players,
107 moves: moves,
108 chats: chats,
109 }
110 );
111 cb(null, game);
112 });
113 });
114 });
115 });
116 });
117 },
118
119 // For display on MyGames or Hall: no need for moves or chats
120 getByUser: function(uid, excluded, cb)
121 {
122 // Some fields are not required when showing a games list:
123 const getOneLight = (id, cb2) => {
124 let query =
125 "SELECT g.id, g.vid, g.fen, g.cadence, g.created, g.score, " +
126 "g.scoreMsg, g.deletedByWhite, g.deletedByBlack, v.name AS vname " +
127 "FROM Games g " +
128 "JOIN Variants v " +
129 " ON g.vid = v.id " +
130 "WHERE g.id = " + id;
131 db.get(query, (err, gameInfo) => {
132 query =
133 "SELECT p.uid, p.color, u.name " +
134 "FROM Players p " +
135 "JOIN Users u " +
136 " ON p.uid = u.id " +
137 "WHERE p.gid = " + id;
138 db.all(query, (err2, players) => {
139 query =
140 "SELECT COUNT(*) AS nbMoves " +
141 "FROM Moves " +
142 "WHERE gid = " + id;
143 db.get(query, (err,ret) => {
144 const game = Object.assign(
145 {},
146 gameInfo,
147 {
148 players: players,
149 movesCount: ret.nbMoves
150 }
151 );
152 cb2(game);
153 });
154 });
155 });
156 };
157 db.serialize(function() {
158 let query = "";
159 if (uid == 0) {
160 // Special case anonymous user: show all games
161 query =
162 "SELECT id AS gid " +
163 "FROM Games";
164 }
165 else {
166 // Registered user:
167 query =
168 "SELECT gid " +
169 "FROM Players " +
170 "GROUP BY gid " +
171 "HAVING COUNT(uid = " + uid + " OR NULL) " +
172 (excluded ? " = 0" : " > 0");
173 }
174 db.all(query, (err,gameIds) => {
175 if (err || gameIds.length == 0) cb(err, []);
176 else {
177 let gameArray = [];
178 let gCounter = 0;
179 for (let i=0; i<gameIds.length; i++) {
180 getOneLight(gameIds[i]["gid"], (game) => {
181 gameArray.push(game);
182 gCounter++; //TODO: let's hope this is atomic?!
183 // Call callback function only when gameArray is complete:
184 if (gCounter == gameIds.length)
185 cb(null, gameArray);
186 });
187 }
188 }
189 });
190 });
191 },
192
193 getPlayers: function(id, cb)
194 {
195 db.serialize(function() {
196 const query =
197 "SELECT uid " +
198 "FROM Players " +
199 "WHERE gid = " + id;
200 db.all(query, (err,players) => {
201 return cb(err, players);
202 });
203 });
204 },
205
206 checkGameUpdate: function(obj)
207 {
208 // Check all that is possible (required) in obj:
209 return (
210 (
211 !obj.move || (
212 !!(obj.move.played.toString().match(/^[0-9]+$/)) &&
213 !!(obj.move.idx.toString().match(/^[0-9]+$/))
214 )
215 ) && (
216 !obj.drawOffer || !!(obj.drawOffer.match(/^[wbtn]$/))
217 ) && (
218 !obj.rematchOffer || !!(obj.rematchOffer.match(/^[wbn]$/))
219 ) && (
220 !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9, /-]*$/))
221 ) && (
222 !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
223 ) && (
224 !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
225 ) && (
226 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
227 )
228 );
229 },
230
231 // obj can have fields move, chat, fen, drawOffer and/or score + message
232 update: function(id, obj, cb)
233 {
234 db.parallelize(function() {
235 let query =
236 "UPDATE Games " +
237 "SET ";
238 let modifs = "";
239 // NOTE: if drawOffer is set, we should check that it's player's turn
240 // A bit overcomplicated. Let's trust the client on that for now...
241 if (!!obj.drawOffer)
242 {
243 if (obj.drawOffer == "n") //special "None" update
244 obj.drawOffer = "";
245 modifs += "drawOffer = '" + obj.drawOffer + "',";
246 }
247 if (!!obj.rematchOffer)
248 {
249 if (obj.rematchOffer == "n") //special "None" update
250 obj.rematchOffer = "";
251 modifs += "rematchOffer = '" + obj.rematchOffer + "',";
252 }
253 if (!!obj.fen)
254 modifs += "fen = '" + obj.fen + "',";
255 if (!!obj.score)
256 modifs += "score = '" + obj.score + "',";
257 if (!!obj.scoreMsg)
258 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
259 if (!!obj.deletedBy) {
260 const myColor = obj.deletedBy == 'w' ? "White" : "Black";
261 modifs += "deletedBy" + myColor + " = true,";
262 }
263 modifs = modifs.slice(0,-1); //remove last comma
264 if (modifs.length > 0)
265 {
266 query += modifs + " WHERE id = " + id;
267 db.run(query);
268 }
269 // NOTE: move, chat and delchat are mutually exclusive
270 if (!!obj.move)
271 {
272 // Security: only update moves if index is right
273 query =
274 "SELECT MAX(idx) AS maxIdx " +
275 "FROM Moves " +
276 "WHERE gid = " + id;
277 db.get(query, (err,ret) => {
278 const m = obj.move;
279 if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
280 query =
281 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
282 "(" + id + ",?," + m.played + "," + m.idx + ")";
283 db.run(query, JSON.stringify(m.squares));
284 cb(null);
285 }
286 else cb({errmsg:"Wrong move index"});
287 });
288 }
289 else cb(null);
290 if (!!obj.chat)
291 {
292 query =
293 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
294 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
295 db.run(query, obj.chat.msg);
296 }
297 else if (obj.delchat)
298 {
299 query =
300 "DELETE " +
301 "FROM Chats " +
302 "WHERE gid = " + id;
303 db.run(query);
304 }
305 if (!!obj.deletedBy) {
306 // Did my opponent delete it too?
307 let selection =
308 "deletedBy" +
309 (obj.deletedBy == 'w' ? "Black" : "White") +
310 " AS deletedByOpp";
311 query =
312 "SELECT " + selection + " " +
313 "FROM Games " +
314 "WHERE id = " + id;
315 db.get(query, (err,ret) => {
316 // If yes: just remove game
317 if (!!ret.deletedByOpp) GameModel.remove(id);
318 });
319 }
320 });
321 },
322
323 remove: function(id)
324 {
325 db.parallelize(function() {
326 let query =
327 "DELETE FROM Games " +
328 "WHERE id = " + id;
329 db.run(query);
330 query =
331 "DELETE FROM Players " +
332 "WHERE gid = " + id;
333 db.run(query);
334 query =
335 "DELETE FROM Moves " +
336 "WHERE gid = " + id;
337 db.run(query);
338 query =
339 "DELETE FROM Chats " +
340 "WHERE gid = " + id;
341 db.run(query);
342 });
343 },
344
345 cleanGamesDb: function()
346 {
347 const tsNow = Date.now();
348 // 86400000 = 24 hours in milliseconds
349 const day = 86400000;
350 db.serialize(function() {
351 let query =
352 "SELECT id, created " +
353 "FROM Games ";
354 db.all(query, (err,games) => {
355 games.forEach(g => {
356 query =
357 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
358 "FROM Moves " +
359 "WHERE gid = " + g.id;
360 db.get(query, (err2,mstats) => {
361 // Remove games still not really started,
362 // with no action in the last 3 months:
363 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
364 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
365 {
366 GameModel.remove(g.id);
367 }
368 });
369 });
370 });
371 });
372 },
373 }
374
375 module.exports = GameModel;