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