Draft rematch (not working yet) + fix Crazyhouse getPromotedFen()
[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.id.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.id + ",'" + 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 gameInfo,
104 {
105 players: players,
106 moves: moves,
107 chats: chats,
108 }
109 );
110 cb(null, game);
111 });
112 });
113 });
114 });
115 });
116 },
117
118 // For display on MyGames or Hall: no need for moves or chats
119 getByUser: function(uid, excluded, cb)
120 {
121 // Some fields are not required when showing a games list:
122 const getOneLight = (id, cb2) => {
123 let query =
124 "SELECT g.id, g.vid, g.fen, g.cadence, g.created, g.score, " +
125 "g.scoreMsg, g.deletedByWhite, g.deletedByBlack, v.name AS vname " +
126 "FROM Games g " +
127 "JOIN Variants v " +
128 " ON g.vid = v.id " +
129 "WHERE g.id = " + id;
130 db.get(query, (err, gameInfo) => {
131 query =
132 "SELECT p.uid, p.color, u.name " +
133 "FROM Players p " +
134 "JOIN Users u " +
135 " ON p.uid = u.id " +
136 "WHERE p.gid = " + id;
137 db.all(query, (err2, players) => {
138 query =
139 "SELECT COUNT(*) AS nbMoves " +
140 "FROM Moves " +
141 "WHERE gid = " + id;
142 db.get(query, (err,ret) => {
143 const game = Object.assign({},
144 gameInfo,
145 {
146 players: players,
147 movesCount: ret.nbMoves
148 }
149 );
150 cb2(game);
151 });
152 });
153 });
154 };
155 db.serialize(function() {
156 let query = "";
157 if (uid == 0) {
158 // Special case anonymous user: show all games
159 query =
160 "SELECT id AS gid " +
161 "FROM Games";
162 }
163 else {
164 // Registered user:
165 query =
166 "SELECT gid " +
167 "FROM Players " +
168 "GROUP BY gid " +
169 "HAVING COUNT(uid = " + uid + " OR NULL) " +
170 (excluded ? " = 0" : " > 0");
171 }
172 db.all(query, (err,gameIds) => {
173 if (err || gameIds.length == 0) cb(err, []);
174 else {
175 let gameArray = [];
176 let gCounter = 0;
177 for (let i=0; i<gameIds.length; i++) {
178 getOneLight(gameIds[i]["gid"], (game) => {
179 gameArray.push(game);
180 gCounter++; //TODO: let's hope this is atomic?!
181 // Call callback function only when gameArray is complete:
182 if (gCounter == gameIds.length)
183 cb(null, gameArray);
184 });
185 }
186 }
187 });
188 });
189 },
190
191 getPlayers: function(id, cb)
192 {
193 db.serialize(function() {
194 const query =
195 "SELECT uid " +
196 "FROM Players " +
197 "WHERE gid = " + id;
198 db.all(query, (err,players) => {
199 return cb(err, players);
200 });
201 });
202 },
203
204 checkGameUpdate: function(obj)
205 {
206 // Check all that is possible (required) in obj:
207 return (
208 (
209 !obj.move || (
210 !!(obj.move.played.toString().match(/^[0-9]+$/)) &&
211 !!(obj.move.idx.toString().match(/^[0-9]+$/))
212 )
213 ) && (
214 !obj.drawOffer || !!(obj.drawOffer.match(/^[wbtn]$/))
215 ) && (
216 !obj.rematchOffer || !!(obj.rematchOffer.match(/^[wbn]$/))
217 ) && (
218 !obj.fen || !!(obj.fen.match(/^[a-zA-Z0-9, /-]*$/))
219 ) && (
220 !obj.score || !!(obj.score.match(/^[012?*\/-]+$/))
221 ) && (
222 !obj.scoreMsg || !!(obj.scoreMsg.match(/^[a-zA-Z ]+$/))
223 ) && (
224 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
225 )
226 );
227 },
228
229 // obj can have fields move, chat, fen, drawOffer and/or score + message
230 update: function(id, obj, cb)
231 {
232 db.parallelize(function() {
233 let query =
234 "UPDATE Games " +
235 "SET ";
236 let modifs = "";
237 // NOTE: if drawOffer is set, we should check that it's player's turn
238 // A bit overcomplicated. Let's trust the client on that for now...
239 if (!!obj.drawOffer)
240 {
241 if (obj.drawOffer == "n") //special "None" update
242 obj.drawOffer = "";
243 modifs += "drawOffer = '" + obj.drawOffer + "',";
244 }
245 if (!!obj.rematchOffer)
246 {
247 if (obj.rematchOffer == "n") //special "None" update
248 obj.rematchOffer = "";
249 modifs += "rematchOffer = '" + obj.rematchOffer + "',";
250 }
251 if (!!obj.fen)
252 modifs += "fen = '" + obj.fen + "',";
253 if (!!obj.score)
254 modifs += "score = '" + obj.score + "',";
255 if (!!obj.scoreMsg)
256 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
257 if (!!obj.deletedBy) {
258 const myColor = obj.deletedBy == 'w' ? "White" : "Black";
259 modifs += "deletedBy" + myColor + " = true,";
260 }
261 modifs = modifs.slice(0,-1); //remove last comma
262 if (modifs.length > 0)
263 {
264 query += modifs + " WHERE id = " + id;
265 db.run(query);
266 }
267 // NOTE: move, chat and delchat are mutually exclusive
268 if (!!obj.move)
269 {
270 // Security: only update moves if index is right
271 query =
272 "SELECT MAX(idx) AS maxIdx " +
273 "FROM Moves " +
274 "WHERE gid = " + id;
275 db.get(query, (err,ret) => {
276 const m = obj.move;
277 if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
278 query =
279 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
280 "(" + id + ",?," + m.played + "," + m.idx + ")";
281 db.run(query, JSON.stringify(m.squares));
282 cb(null);
283 }
284 else cb({errmsg:"Wrong move index"});
285 });
286 }
287 else cb(null);
288 if (!!obj.chat)
289 {
290 query =
291 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
292 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
293 db.run(query, obj.chat.msg);
294 }
295 else if (obj.delchat)
296 {
297 query =
298 "DELETE " +
299 "FROM Chats " +
300 "WHERE gid = " + id;
301 db.run(query);
302 }
303 if (!!obj.deletedBy) {
304 // Did my opponent delete it too?
305 let selection =
306 "deletedBy" +
307 (obj.deletedBy == 'w' ? "Black" : "White") +
308 " AS deletedByOpp";
309 query =
310 "SELECT " + selection + " " +
311 "FROM Games " +
312 "WHERE id = " + id;
313 db.get(query, (err,ret) => {
314 // If yes: just remove game
315 if (!!ret.deletedByOpp) GameModel.remove(id);
316 });
317 }
318 });
319 },
320
321 remove: function(id)
322 {
323 db.parallelize(function() {
324 let query =
325 "DELETE FROM Games " +
326 "WHERE id = " + id;
327 db.run(query);
328 query =
329 "DELETE FROM Players " +
330 "WHERE gid = " + id;
331 db.run(query);
332 query =
333 "DELETE FROM Moves " +
334 "WHERE gid = " + id;
335 db.run(query);
336 query =
337 "DELETE FROM Chats " +
338 "WHERE gid = " + id;
339 db.run(query);
340 });
341 },
342
343 cleanGamesDb: function()
344 {
345 const tsNow = Date.now();
346 // 86400000 = 24 hours in milliseconds
347 const day = 86400000;
348 db.serialize(function() {
349 let query =
350 "SELECT id, created " +
351 "FROM Games ";
352 db.all(query, (err,games) => {
353 games.forEach(g => {
354 query =
355 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
356 "FROM Moves " +
357 "WHERE gid = " + g.id;
358 db.get(query, (err2,mstats) => {
359 // Remove games still not really started,
360 // with no action in the last 3 months:
361 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
362 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
363 {
364 GameModel.remove(g.id);
365 }
366 });
367 });
368 });
369 });
370 },
371 }
372
373 module.exports = GameModel;