e970bfbe39a115c0e49f7f81b4650ccdb43206b5
[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, score, cadence, created, drawOffer) " +
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, light, 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, 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 if (light)
93 {
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 });
106 }
107 else
108 {
109 // Full game requested:
110 query =
111 "SELECT squares, played, idx " +
112 "FROM Moves " +
113 "WHERE gid = " + id;
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 });
130 });
131 }
132 });
133 });
134 });
135 },
136
137 // For display on MyGames or Hall: no need for moves or chats
138 getByUser: function(uid, excluded, cb)
139 {
140 db.serialize(function() {
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 }
159 db.all(query, (err,gameIds) => {
160 if (err || gameIds.length == 0)
161 cb(err, []);
162 else
163 {
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 }
176 }
177 });
178 });
179 },
180
181 getPlayers: function(id, cb)
182 {
183 db.serialize(function() {
184 const query =
185 "SELECT uid " +
186 "FROM Players " +
187 "WHERE gid = " + id;
188 db.all(query, (err,players) => {
189 return cb(err, players);
190 });
191 });
192 },
193
194 checkGameUpdate: function(obj)
195 {
196 // Check all that is possible (required) in obj:
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 );
215 },
216
217 // obj can have fields move, chat, fen, drawOffer and/or score + message
218 update: function(id, obj, cb)
219 {
220 db.parallelize(function() {
221 let query =
222 "UPDATE Games " +
223 "SET ";
224 let modifs = "";
225 // NOTE: if drawOffer is set, we should check that it's player's turn
226 // A bit overcomplicated. Let's trust the client on that for now...
227 if (obj.drawOffer)
228 {
229 if (obj.drawOffer == "n") //Special "None" update
230 obj.drawOffer = "";
231 modifs += "drawOffer = '" + obj.drawOffer + "',";
232 }
233 if (obj.fen)
234 modifs += "fen = '" + obj.fen + "',";
235 if (obj.score)
236 modifs += "score = '" + obj.score + "',";
237 if (obj.scoreMsg)
238 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
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 }
245
246
247 return cb({errmsg: JSON.stringify(obj.move) + " " + (!!obj.move)});
248
249
250 // NOTE: move, chat and delchat are mutually exclusive
251 if (!!obj.move)
252 {
253 // Security: only update moves if index is right
254 query =
255 "SELECT MAX(idx) AS maxIdx " +
256 "FROM Moves " +
257 "WHERE gid = " + id;
258 db.get(query, (err,ret) => {
259 const m = obj.move;
260
261 //return cb({errmsg: ret.maxIdx + " " + m.idx + " " + (!ret.maxIdx || ret.maxIdx + 1 == m.idx) + " " + query});
262
263
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 });
273 }
274 else cb(null);
275 if (obj.chat)
276 {
277 query =
278 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
279 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
280 db.run(query, obj.chat.msg);
281 }
282 else if (obj.delchat)
283 {
284 query =
285 "DELETE " +
286 "FROM Chats " +
287 "WHERE gid = " + id;
288 db.run(query);
289 }
290 });
291 },
292
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 },
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 =
322 "SELECT id, created " +
323 "FROM Games ";
324 db.all(query, (err,games) => {
325 games.forEach(g => {
326 query =
327 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
328 "FROM Moves " +
329 "WHERE gid = " + g.id;
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))
335 {
336 GameModel.remove(g.id);
337 }
338 });
339 });
340 });
341 });
342 },
343 }
344
345 module.exports = GameModel;