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