21ece2f181a872434662dedce1fa4b878acab835
[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 const game = Object.assign({},
95 gameInfo,
96 {players: players}
97 );
98 cb(null, game);
99 }
100 else
101 {
102 // Full game requested:
103 query =
104 "SELECT squares, played, idx " +
105 "FROM Moves " +
106 "WHERE gid = " + id;
107 db.all(query, (err3,moves) => {
108 query =
109 "SELECT msg, name, added " +
110 "FROM Chats " +
111 "WHERE gid = " + id;
112 db.all(query, (err4,chats) => {
113 const game = Object.assign({},
114 gameInfo,
115 {
116 players: players,
117 moves: moves,
118 chats: chats,
119 }
120 );
121 cb(null, game);
122 });
123 });
124 }
125 });
126 });
127 });
128 },
129
130 // For display on MyGames or Hall: no need for moves or chats
131 getByUser: function(uid, excluded, cb)
132 {
133 db.serialize(function() {
134 let query = "";
135 if (uid == 0)
136 {
137 // Special case anonymous user: show all games
138 query =
139 "SELECT id AS gid " +
140 "FROM Games";
141 }
142 else
143 {
144 // Registered user:
145 query =
146 "SELECT gid " +
147 "FROM Players " +
148 "GROUP BY gid " +
149 "HAVING COUNT(uid = " + uid + " OR NULL) " +
150 (excluded ? " = 0" : " > 0");
151 }
152 db.all(query, (err,gameIds) => {
153 if (err || gameIds.length == 0)
154 cb(err, []);
155 else
156 {
157 let gameArray = [];
158 let gCounter = 0;
159 for (let i=0; i<gameIds.length; i++)
160 {
161 GameModel.getOne(gameIds[i]["gid"], true, (err2,game) => {
162 gameArray.push(game);
163 gCounter++; //TODO: let's hope this is atomic?!
164 // Call callback function only when gameArray is complete:
165 if (gCounter == gameIds.length)
166 cb(null, gameArray);
167 });
168 }
169 }
170 });
171 });
172 },
173
174 getPlayers: function(id, cb)
175 {
176 db.serialize(function() {
177 const query =
178 "SELECT uid " +
179 "FROM Players " +
180 "WHERE gid = " + id;
181 db.all(query, (err,players) => {
182 return cb(err, players);
183 });
184 });
185 },
186
187 checkGameUpdate: function(obj)
188 {
189 // Check all that is possible (required) in obj:
190 return (
191 (
192 !obj.move || (
193 obj.move.played.toString().match(/^[0-9]+$/) &&
194 obj.move.idx.toString().match(/^[0-9]+$/)
195 )
196 ) && (
197 !obj.drawOffer || obj.drawOffer.match(/^[wbtn]$/)
198 ) && (
199 !obj.fen || obj.fen.match(/^[a-zA-Z0-9, /-]*$/)
200 ) && (
201 !obj.score || obj.score.match(/^[012?*\/-]+$/)
202 ) && (
203 !obj.scoreMsg || obj.scoreMsg.match(/^[a-zA-Z ]+$/)
204 ) && (
205 !obj.chat || UserModel.checkNameEmail({name: obj.chat.name})
206 )
207 );
208 },
209
210 // obj can have fields move, chat, fen, drawOffer and/or score + message
211 update: function(id, obj, cb)
212 {
213 db.parallelize(function() {
214 let query =
215 "UPDATE Games " +
216 "SET ";
217 let modifs = "";
218 // NOTE: if drawOffer is set, we should check that it's player's turn
219 // A bit overcomplicated. Let's trust the client on that for now...
220 if (obj.drawOffer)
221 {
222 if (obj.drawOffer == "n") //Special "None" update
223 obj.drawOffer = "";
224 modifs += "drawOffer = '" + obj.drawOffer + "',";
225 }
226 if (obj.fen)
227 modifs += "fen = '" + obj.fen + "',";
228 if (obj.score)
229 modifs += "score = '" + obj.score + "',";
230 if (obj.scoreMsg)
231 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
232 modifs = modifs.slice(0,-1); //remove last comma
233 if (modifs.length > 0)
234 {
235 query += modifs + " WHERE id = " + id;
236 db.run(query);
237 }
238 let wrongMoveIndex = false;
239 if (obj.move)
240 {
241 // Security: only update moves if index is right
242 query =
243 "SELECT MAX(idx) AS maxIdx " +
244 "FROM Moves " +
245 "WHERE gid = " + id;
246 db.get(query, (err,ret) => {
247 const m = obj.move;
248 if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
249 query =
250 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
251 "(" + id + ",?," + m.played + "," + m.idx + ")";
252 db.run(query, JSON.stringify(m.squares));
253 cb(null);
254 }
255 else cb({errmsg:"Wrong move index"});
256 });
257 }
258 else cb(null);
259 if (obj.chat)
260 {
261 query =
262 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
263 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
264 db.run(query, obj.chat.msg);
265 }
266 });
267 },
268
269 remove: function(id)
270 {
271 db.parallelize(function() {
272 let query =
273 "DELETE FROM Games " +
274 "WHERE id = " + id;
275 db.run(query);
276 query =
277 "DELETE FROM Players " +
278 "WHERE gid = " + id;
279 db.run(query);
280 query =
281 "DELETE FROM Moves " +
282 "WHERE gid = " + id;
283 db.run(query);
284 query =
285 "DELETE FROM Chats " +
286 "WHERE gid = " + id;
287 db.run(query);
288 });
289 },
290
291 cleanGamesDb: function()
292 {
293 const tsNow = Date.now();
294 // 86400000 = 24 hours in milliseconds
295 const day = 86400000;
296 db.serialize(function() {
297 let query =
298 "SELECT id, created " +
299 "FROM Games ";
300 db.all(query, (err,games) => {
301 games.forEach(g => {
302 query =
303 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
304 "FROM Moves " +
305 "WHERE gid = " + g.id;
306 db.get(query, (err2,mstats) => {
307 // Remove games still not really started,
308 // with no action in the last 3 months:
309 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
310 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
311 {
312 GameModel.remove(g.id);
313 }
314 });
315 });
316 });
317 });
318 },
319 }
320
321 module.exports = GameModel;