Fixes
[vchess.git] / server / models / Game.js
1 var 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 if (!g.vid.toString().match(/^[0-9]+$/))
38 return "Wrong variant ID";
39 if (!g.cadence.match(/^[0-9dhms +]+$/))
40 return "Wrong characters in time control";
41 if (!g.fen.match(/^[a-zA-Z0-9, /-]*$/))
42 return "Bad FEN string";
43 if (g.players.length != 2)
44 return "Need exactly 2 players";
45 if (g.players.some(p => !p.id.toString().match(/^[0-9]+$/)))
46 return "Wrong characters in player ID";
47 return "";
48 },
49
50 create: function(vid, fen, cadence, players, cb)
51 {
52 db.serialize(function() {
53 let query =
54 "INSERT INTO Games " +
55 "(vid, fenStart, fen, score, cadence, created, drawOffer) " +
56 "VALUES " +
57 "(" + vid + ",'" + fen + "','" + fen + "','*','" + cadence + "'," + Date.now() + ",'')";
58 db.run(query, function(err) {
59 if (!!err)
60 return cb(err);
61 players.forEach((p,idx) => {
62 const color = (idx==0 ? "w" : "b");
63 query =
64 "INSERT INTO Players VALUES " +
65 "(" + this.lastID + "," + p.id + ",'" + color + "')";
66 db.run(query);
67 });
68 cb(null, {gid: this.lastID});
69 });
70 });
71 },
72
73 // TODO: some queries here could be async
74 getOne: function(id, light, cb)
75 {
76 db.serialize(function() {
77 let query =
78 // NOTE: g.scoreMsg can be NULL
79 // (in this case score = "*" and no reason to look at it)
80 "SELECT g.id, g.vid, g.fen, g.fenStart, g.cadence, g.score, " +
81 "g.scoreMsg, g.drawOffer, v.name AS vname " +
82 "FROM Games g " +
83 "JOIN Variants v " +
84 " ON g.vid = v.id " +
85 "WHERE g.id = " + id;
86 db.get(query, (err,gameInfo) => {
87 if (!!err)
88 return cb(err);
89 query =
90 "SELECT p.uid, p.color, u.name " +
91 "FROM Players p " +
92 "JOIN Users u " +
93 " ON p.uid = u.id " +
94 "WHERE p.gid = " + id;
95 db.all(query, (err2,players) => {
96 if (!!err2)
97 return cb(err2);
98 if (light)
99 {
100 const game = Object.assign({},
101 gameInfo,
102 {players: players}
103 );
104 return cb(null, game);
105 }
106 query =
107 "SELECT squares, played, idx " +
108 "FROM Moves " +
109 "WHERE gid = " + id;
110 db.all(query, (err3,moves) => {
111 if (!!err3)
112 return cb(err3);
113 query =
114 "SELECT msg, name, added " +
115 "FROM Chats " +
116 "WHERE gid = " + id;
117 db.all(query, (err4,chats) => {
118 if (!!err4)
119 return cb(err4);
120 const game = Object.assign({},
121 gameInfo,
122 {
123 players: players,
124 moves: moves,
125 chats: chats,
126 }
127 );
128 return cb(null, game);
129 });
130 });
131 });
132 });
133 });
134 },
135
136 // For display on MyGames or Hall: no need for moves or chats
137 getByUser: function(uid, excluded, cb)
138 {
139 db.serialize(function() {
140 const query =
141 "SELECT DISTINCT gid " +
142 "FROM Players " +
143 "WHERE uid " + (excluded ? "<>" : "=") + " " + uid;
144 db.all(query, (err,gameIds) => {
145 if (!!err)
146 return cb(err);
147 if (gameIds.length == 0)
148 return cb(null, []);
149 let gameArray = [];
150 for (let i=0; i<gameIds.length; i++)
151 {
152 GameModel.getOne(gameIds[i]["gid"], true, (err2,game) => {
153 if (!!err2)
154 return cb(err2);
155 gameArray.push(game);
156 // Call callback function only when gameArray is complete:
157 if (i == gameIds.length - 1)
158 return cb(null, gameArray);
159 });
160 }
161 });
162 });
163 },
164
165 getPlayers: function(id, cb)
166 {
167 db.serialize(function() {
168 const query =
169 "SELECT id " +
170 "FROM Players " +
171 "WHERE gid = " + id;
172 db.all(query, (err,players) => {
173 return cb(err, players);
174 });
175 });
176 },
177
178 checkGameUpdate: function(obj)
179 {
180 // Check all that is possible (required) in obj:
181 if (!!obj.move)
182 {
183 if (!obj.move.played.toString().match(/^[0-9]+$/))
184 return "Wrong move played time";
185 if (!obj.move.idx.toString().match(/^[0-9]+$/))
186 return "Wrong move index";
187 }
188 if (!!obj.drawOffer && !obj.drawOffer.match(/^[wbtn]$/))
189 return "Wrong draw offer format";
190 if (!!obj.fen && !obj.fen.match(/^[a-zA-Z0-9, /-]*$/))
191 return "Wrong FEN string";
192 if (!!obj.score && !obj.score.match(/^[012?*\/-]+$/))
193 return "Wrong characters in score";
194 if (!!obj.scoreMsg && !obj.scoreMsg.match(/^[a-zA-Z ]+$/))
195 return "Wrong characters in score message";
196 if (!!obj.chat)
197 return UserModel.checkNameEmail({name: obj.chat.name});
198 return "";
199 },
200
201 // obj can have fields move, chat, fen, drawOffer and/or score
202 update: function(id, obj)
203 {
204 db.parallelize(function() {
205 let query =
206 "UPDATE Games " +
207 "SET ";
208 let modifs = "";
209 if (!!obj.message)
210 modifs += "message = message || ' ' || '" + obj.message + "',";
211 // NOTE: if drawOffer is set, we should check that it's player's turn
212 // A bit overcomplicated. Let's trust the client on that for now...
213 if (!!obj.drawOffer)
214 {
215 if (obj.drawOffer == "n") //Special "None" update
216 obj.drawOffer = "";
217 modifs += "drawOffer = '" + obj.drawOffer + "',";
218 }
219 if (!!obj.fen)
220 modifs += "fen = '" + obj.fen + "',";
221 if (!!obj.score)
222 modifs += "score = '" + obj.score + "',";
223 if (!!obj.scoreMsg)
224 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
225 modifs = modifs.slice(0,-1); //remove last comma
226 if (modifs.length > 0)
227 {
228 query += modifs + " WHERE id = " + id;
229 db.run(query);
230 }
231 if (!!obj.move)
232 {
233 const m = obj.move;
234 query =
235 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
236 "(" + id + ",?," + m.played + "," + m.idx + ")";
237 db.run(query, JSON.stringify(m.squares));
238 }
239 if (!!obj.chat)
240 {
241 query =
242 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
243 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
244 db.run(query, obj.chat.msg);
245 }
246 });
247 },
248
249 remove: function(id)
250 {
251 db.parallelize(function() {
252 let query =
253 "DELETE FROM Games " +
254 "WHERE id = " + id;
255 db.run(query);
256 query =
257 "DELETE FROM Players " +
258 "WHERE gid = " + id;
259 db.run(query);
260 query =
261 "DELETE FROM Moves " +
262 "WHERE gid = " + id;
263 db.run(query);
264 query =
265 "DELETE FROM Chats " +
266 "WHERE gid = " + id;
267 db.run(query);
268 });
269 },
270
271 cleanGamesDb: function()
272 {
273 const tsNow = Date.now();
274 // 86400000 = 24 hours in milliseconds
275 const day = 86400000;
276 db.serialize(function() {
277 let query =
278 "SELECT id,created " +
279 "FROM Games ";
280 db.all(query, (err,games) => {
281 games.forEach(g => {
282 query =
283 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
284 "FROM Moves " +
285 "WHERE gid = " + g.id;
286 db.get(query, (err2,mstats) => {
287 // Remove games still not really started,
288 // with no action in the last 3 months:
289 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
290 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
291 {
292 return GameModel.remove(g.id);
293 }
294 });
295 });
296 });
297 });
298 },
299 }
300
301 module.exports = GameModel;