Improvements - untested
[vchess.git] / server / models / Game.js
CommitLineData
c5c47010 1const db = require("../utils/database");
58e7b94e 2const UserModel = require("./User");
00f2759e
BA
3
4/*
5 * Structure table Games:
6 * id: game id (int)
7 * vid: integer (variant id)
ab4f4bf2
BA
8 * fenStart: varchar (initial position)
9 * fen: varchar (current position)
71468011 10 * cadence: string
00f2759e 11 * score: varchar (result)
dcd68c41 12 * scoreMsg: varchar ("Time", "Mutual agreement"...)
83494c7f 13 * created: datetime
dfeb96ea 14 * drawOffer: char ('w','b' or '' for none)
00f2759e
BA
15 *
16 * Structure table Players:
17 * gid: ref game id
18 * uid: ref user id
19 * color: character
20 *
21 * Structure table Moves:
ab4f4bf2 22 * gid: ref game id
f41ce580 23 * squares: varchar (description)
00f2759e
BA
24 * played: datetime
25 * idx: integer
3837d4f7
BA
26 *
27 * Structure table Chats:
28 * gid: game id (int)
29 * msg: varchar
30 * name: varchar
3837d4f7 31 * added: datetime
00f2759e
BA
32 */
33
ab4f4bf2 34const GameModel =
00f2759e 35{
58e7b94e 36 checkGameInfo: function(g) {
866842c3
BA
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 );
58e7b94e
BA
44 },
45
71468011 46 create: function(vid, fen, cadence, players, cb)
dac39588
BA
47 {
48 db.serialize(function() {
49 let query =
71468011
BA
50 "INSERT INTO Games " +
51 "(vid, fenStart, fen, score, cadence, created, drawOffer) " +
52 "VALUES " +
53 "(" + vid + ",'" + fen + "','" + fen + "','*','" + cadence + "'," + Date.now() + ",'')";
8c564f46 54 db.run(query, function(err) {
866842c3
BA
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 }
dac39588
BA
68 });
69 });
70 },
00f2759e 71
71468011
BA
72 // TODO: some queries here could be async
73 getOne: function(id, light, cb)
dac39588 74 {
866842c3 75 // NOTE: ignoring errors (shouldn't happen at this stage)
dac39588 76 db.serialize(function() {
dac39588 77 let query =
2f258c37 78 "SELECT g.id, g.vid, g.fen, g.fenStart, g.cadence, g.created, g.score, " +
633959bf 79 "g.scoreMsg, g.drawOffer, v.name AS vname " +
dac39588 80 "FROM Games g " +
f41ce580
BA
81 "JOIN Variants v " +
82 " ON g.vid = v.id " +
dac39588
BA
83 "WHERE g.id = " + id;
84 db.get(query, (err,gameInfo) => {
dac39588
BA
85 query =
86 "SELECT p.uid, p.color, u.name " +
87 "FROM Players p " +
f41ce580
BA
88 "JOIN Users u " +
89 " ON p.uid = u.id " +
dac39588
BA
90 "WHERE p.gid = " + id;
91 db.all(query, (err2,players) => {
71468011
BA
92 if (light)
93 {
db1f1f9a
BA
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 });
71468011 106 }
866842c3
BA
107 else
108 {
109 // Full game requested:
dac39588 110 query =
866842c3
BA
111 "SELECT squares, played, idx " +
112 "FROM Moves " +
3837d4f7 113 "WHERE gid = " + id;
866842c3
BA
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 });
3837d4f7 130 });
866842c3 131 }
dac39588
BA
132 });
133 });
134 });
135 },
00f2759e 136
71468011 137 // For display on MyGames or Hall: no need for moves or chats
dac39588
BA
138 getByUser: function(uid, excluded, cb)
139 {
140 db.serialize(function() {
2f258c37
BA
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 }
dac39588 159 db.all(query, (err,gameIds) => {
866842c3
BA
160 if (err || gameIds.length == 0)
161 cb(err, []);
162 else
dac39588 163 {
866842c3
BA
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 }
dac39588
BA
176 }
177 });
178 });
179 },
ab4f4bf2 180
411d23cd
BA
181 getPlayers: function(id, cb)
182 {
183 db.serialize(function() {
184 const query =
1ad003ff 185 "SELECT uid " +
411d23cd
BA
186 "FROM Players " +
187 "WHERE gid = " + id;
188 db.all(query, (err,players) => {
189 return cb(err, players);
190 });
191 });
192 },
193
58e7b94e
BA
194 checkGameUpdate: function(obj)
195 {
196 // Check all that is possible (required) in obj:
866842c3
BA
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 );
58e7b94e
BA
215 },
216
866842c3 217 // obj can have fields move, chat, fen, drawOffer and/or score + message
fb68b0c2 218 update: function(id, obj, cb)
3d55deea 219 {
dac39588 220 db.parallelize(function() {
3d55deea
BA
221 let query =
222 "UPDATE Games " +
223 "SET ";
3837d4f7 224 let modifs = "";
633959bf 225 // NOTE: if drawOffer is set, we should check that it's player's turn
dfeb96ea 226 // A bit overcomplicated. Let's trust the client on that for now...
866842c3 227 if (obj.drawOffer)
633959bf
BA
228 {
229 if (obj.drawOffer == "n") //Special "None" update
230 obj.drawOffer = "";
231 modifs += "drawOffer = '" + obj.drawOffer + "',";
232 }
866842c3 233 if (obj.fen)
3837d4f7 234 modifs += "fen = '" + obj.fen + "',";
866842c3 235 if (obj.score)
3837d4f7 236 modifs += "score = '" + obj.score + "',";
866842c3 237 if (obj.scoreMsg)
dcd68c41 238 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
3837d4f7
BA
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 }
866842c3 245 if (obj.move)
f41ce580 246 {
fb68b0c2 247 // Security: only update moves if index is right
f41ce580 248 query =
fb68b0c2
BA
249 "SELECT MAX(idx) AS maxIdx " +
250 "FROM Moves " +
251 "WHERE gid = " + id;
252 db.get(query, (err,ret) => {
253 const m = obj.move;
254 if (!ret.maxIdx || ret.maxIdx + 1 == m.idx) {
255 query =
256 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
257 "(" + id + ",?," + m.played + "," + m.idx + ")";
258 db.run(query, JSON.stringify(m.squares));
259 cb(null);
260 }
261 else cb({errmsg:"Wrong move index"});
262 });
f41ce580 263 }
fb68b0c2 264 else cb(null);
866842c3 265 if (obj.chat)
3837d4f7 266 {
dac39588
BA
267 query =
268 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 269 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 270 db.run(query, obj.chat.msg);
3837d4f7 271 }
db1f1f9a
BA
272 else if (obj.delchat)
273 {
274 query =
275 "DELETE " +
276 "FROM Chats " +
277 "WHERE gid = " + id;
278 db.run(query, cb);
279 }
3d55deea
BA
280 });
281 },
282
dac39588
BA
283 remove: function(id)
284 {
285 db.parallelize(function() {
286 let query =
287 "DELETE FROM Games " +
288 "WHERE id = " + id;
289 db.run(query);
290 query =
291 "DELETE FROM Players " +
292 "WHERE gid = " + id;
293 db.run(query);
294 query =
295 "DELETE FROM Moves " +
296 "WHERE gid = " + id;
297 db.run(query);
298 query =
299 "DELETE FROM Chats " +
300 "WHERE gid = " + id;
301 db.run(query);
302 });
303 },
d431028c
BA
304
305 cleanGamesDb: function()
306 {
307 const tsNow = Date.now();
308 // 86400000 = 24 hours in milliseconds
309 const day = 86400000;
310 db.serialize(function() {
311 let query =
0f7011a2 312 "SELECT id, created " +
d431028c
BA
313 "FROM Games ";
314 db.all(query, (err,games) => {
315 games.forEach(g => {
316 query =
fd41e587 317 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
d431028c
BA
318 "FROM Moves " +
319 "WHERE gid = " + g.id;
fd41e587
BA
320 db.get(query, (err2,mstats) => {
321 // Remove games still not really started,
322 // with no action in the last 3 months:
323 if ((mstats.nbMoves == 0 && tsNow - g.created > 91*day) ||
324 (mstats.nbMoves == 1 && tsNow - mstats.lastMaj > 91*day))
d431028c 325 {
89021f18 326 GameModel.remove(g.id);
d431028c
BA
327 }
328 });
329 });
330 });
331 });
332 },
00f2759e 333}
ab4f4bf2
BA
334
335module.exports = GameModel;