Fixes. TODO: autofocus on forms, and understand why email autofill in name field
[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 // NOTE: move, chat and delchat are mutually exclusive
246 if (obj.move)
247 {
248 // Security: only update moves if index is right
249 query =
250 "SELECT MAX(idx) AS maxIdx " +
251 "FROM Moves " +
252 "WHERE gid = " + id;
253 db.get(query, (err,ret) => {
254 const m = obj.move;
255 if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
256 query =
257 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
258 "(" + id + ",?," + m.played + "," + m.idx + ")";
259 db.run(query, JSON.stringify(m.squares));
260 cb(null);
261 }
262 else cb({errmsg:"Wrong move index"});
263 });
264 }
265 else cb(null);
266 if (obj.chat)
267 {
268 query =
269 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
270 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
271 db.run(query, obj.chat.msg);
272 }
273 else if (obj.delchat)
274 {
275 query =
276 "DELETE " +
277 "FROM Chats " +
278 "WHERE gid = " + id;
279 db.run(query);
280 }
281 });
282 },
283
284 remove: function(id)
285 {
286 db.parallelize(function() {
287 let query =
288 "DELETE FROM Games " +
289 "WHERE id = " + id;
290 db.run(query);
291 query =
292 "DELETE FROM Players " +
293 "WHERE gid = " + id;
294 db.run(query);
295 query =
296 "DELETE FROM Moves " +
297 "WHERE gid = " + id;
298 db.run(query);
299 query =
300 "DELETE FROM Chats " +
301 "WHERE gid = " + id;
302 db.run(query);
303 });
304 },
305
306 cleanGamesDb: function()
307 {
308 const tsNow = Date.now();
309 // 86400000 = 24 hours in milliseconds
310 const day = 86400000;
311 db.serialize(function() {
312 let query =
313 "SELECT id, created " +
314 "FROM Games ";
315 db.all(query, (err,games) => {
316 games.forEach(g => {
317 query =
318 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
319 "FROM Moves " +
320 "WHERE gid = " + g.id;
321 db.get(query, (err2,mstats) => {
322 // Remove games still not really started,
323 // with no action in the last 3 months:
324 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
325 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
326 {
327 GameModel.remove(g.id);
328 }
329 });
330 });
331 });
332 });
333 },
334 }
335
336 module.exports = GameModel;