Revise server code + a few fixes in trnalsations and ComputerGame
[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)
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 if (obj.move)
239 {
240 const m = obj.move;
241 query =
242 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
243 "(" + id + ",?," + m.played + "," + m.idx + ")";
244 db.run(query, JSON.stringify(m.squares));
245 }
246 if (obj.chat)
247 {
248 query =
249 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
250 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
251 db.run(query, obj.chat.msg);
252 }
253 });
254 },
255
256 remove: function(id)
257 {
258 db.parallelize(function() {
259 let query =
260 "DELETE FROM Games " +
261 "WHERE id = " + id;
262 db.run(query);
263 query =
264 "DELETE FROM Players " +
265 "WHERE gid = " + id;
266 db.run(query);
267 query =
268 "DELETE FROM Moves " +
269 "WHERE gid = " + id;
270 db.run(query);
271 query =
272 "DELETE FROM Chats " +
273 "WHERE gid = " + id;
274 db.run(query);
275 });
276 },
277
278 cleanGamesDb: function()
279 {
280 const tsNow = Date.now();
281 // 86400000 = 24 hours in milliseconds
282 const day = 86400000;
283 db.serialize(function() {
284 let query =
285 "SELECT id, created " +
286 "FROM Games ";
287 db.all(query, (err,games) => {
288 games.forEach(g => {
289 query =
290 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
291 "FROM Moves " +
292 "WHERE gid = " + g.id;
293 db.get(query, (err2,mstats) => {
294 // Remove games still not really started,
295 // with no action in the last 3 months:
296 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
297 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
298 {
299 GameModel.remove(g.id);
300 }
301 });
302 });
303 });
304 });
305 },
306 }
307
308 module.exports = GameModel;