Fix
[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 {
94 const game = Object.assign({},
95 gameInfo,
96 {players: players}
97 );
866842c3 98 cb(null, game);
71468011 99 }
866842c3
BA
100 else
101 {
102 // Full game requested:
dac39588 103 query =
866842c3
BA
104 "SELECT squares, played, idx " +
105 "FROM Moves " +
3837d4f7 106 "WHERE gid = " + id;
866842c3
BA
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 });
3837d4f7 123 });
866842c3 124 }
dac39588
BA
125 });
126 });
127 });
128 },
00f2759e 129
71468011 130 // For display on MyGames or Hall: no need for moves or chats
dac39588
BA
131 getByUser: function(uid, excluded, cb)
132 {
133 db.serialize(function() {
2f258c37
BA
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 }
dac39588 152 db.all(query, (err,gameIds) => {
866842c3
BA
153 if (err || gameIds.length == 0)
154 cb(err, []);
155 else
dac39588 156 {
866842c3
BA
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 }
dac39588
BA
169 }
170 });
171 });
172 },
ab4f4bf2 173
411d23cd
BA
174 getPlayers: function(id, cb)
175 {
176 db.serialize(function() {
177 const query =
1ad003ff 178 "SELECT uid " +
411d23cd
BA
179 "FROM Players " +
180 "WHERE gid = " + id;
181 db.all(query, (err,players) => {
182 return cb(err, players);
183 });
184 });
185 },
186
58e7b94e
BA
187 checkGameUpdate: function(obj)
188 {
189 // Check all that is possible (required) in obj:
866842c3
BA
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 );
58e7b94e
BA
208 },
209
866842c3 210 // obj can have fields move, chat, fen, drawOffer and/or score + message
fb68b0c2 211 update: function(id, obj, cb)
3d55deea 212 {
dac39588 213 db.parallelize(function() {
3d55deea
BA
214 let query =
215 "UPDATE Games " +
216 "SET ";
3837d4f7 217 let modifs = "";
633959bf 218 // NOTE: if drawOffer is set, we should check that it's player's turn
dfeb96ea 219 // A bit overcomplicated. Let's trust the client on that for now...
866842c3 220 if (obj.drawOffer)
633959bf
BA
221 {
222 if (obj.drawOffer == "n") //Special "None" update
223 obj.drawOffer = "";
224 modifs += "drawOffer = '" + obj.drawOffer + "',";
225 }
866842c3 226 if (obj.fen)
3837d4f7 227 modifs += "fen = '" + obj.fen + "',";
866842c3 228 if (obj.score)
3837d4f7 229 modifs += "score = '" + obj.score + "',";
866842c3 230 if (obj.scoreMsg)
dcd68c41 231 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
3837d4f7
BA
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 }
fb68b0c2 238 let wrongMoveIndex = false;
866842c3 239 if (obj.move)
f41ce580 240 {
fb68b0c2 241 // Security: only update moves if index is right
f41ce580 242 query =
fb68b0c2
BA
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 });
f41ce580 257 }
fb68b0c2 258 else cb(null);
866842c3 259 if (obj.chat)
3837d4f7 260 {
dac39588
BA
261 query =
262 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 263 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 264 db.run(query, obj.chat.msg);
3837d4f7 265 }
3d55deea
BA
266 });
267 },
268
dac39588
BA
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 },
d431028c
BA
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 =
0f7011a2 298 "SELECT id, created " +
d431028c
BA
299 "FROM Games ";
300 db.all(query, (err,games) => {
301 games.forEach(g => {
302 query =
fd41e587 303 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
d431028c
BA
304 "FROM Moves " +
305 "WHERE gid = " + g.id;
fd41e587
BA
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))
d431028c 311 {
89021f18 312 GameModel.remove(g.id);
d431028c
BA
313 }
314 });
315 });
316 });
317 });
318 },
00f2759e 319}
ab4f4bf2
BA
320
321module.exports = GameModel;