Fixes
[vchess.git] / server / models / Game.js
CommitLineData
00f2759e 1var 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) {
58e7b94e
BA
37 if (!g.vid.toString().match(/^[0-9]+$/))
38 return "Wrong variant ID";
71468011 39 if (!g.cadence.match(/^[0-9dhms +]+$/))
58e7b94e
BA
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
71468011 50 create: function(vid, fen, cadence, players, cb)
dac39588
BA
51 {
52 db.serialize(function() {
53 let query =
71468011
BA
54 "INSERT INTO Games " +
55 "(vid, fenStart, fen, score, cadence, created, drawOffer) " +
56 "VALUES " +
57 "(" + vid + ",'" + fen + "','" + fen + "','*','" + cadence + "'," + Date.now() + ",'')";
8c564f46 58 db.run(query, function(err) {
cf742aaf
BA
59 if (!!err)
60 return cb(err);
8c564f46
BA
61 players.forEach((p,idx) => {
62 const color = (idx==0 ? "w" : "b");
2be5d614
BA
63 query =
64 "INSERT INTO Players VALUES " +
f41ce580 65 "(" + this.lastID + "," + p.id + ",'" + color + "')";
2be5d614
BA
66 db.run(query);
67 });
68 cb(null, {gid: this.lastID});
dac39588
BA
69 });
70 });
71 },
00f2759e 72
71468011
BA
73 // TODO: some queries here could be async
74 getOne: function(id, light, cb)
dac39588
BA
75 {
76 db.serialize(function() {
dac39588 77 let query =
dcd68c41
BA
78 // NOTE: g.scoreMsg can be NULL
79 // (in this case score = "*" and no reason to look at it)
71468011 80 "SELECT g.id, g.vid, g.fen, g.fenStart, g.cadence, g.score, " +
633959bf 81 "g.scoreMsg, g.drawOffer, v.name AS vname " +
dac39588 82 "FROM Games g " +
f41ce580
BA
83 "JOIN Variants v " +
84 " ON g.vid = v.id " +
dac39588
BA
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 " +
f41ce580
BA
92 "JOIN Users u " +
93 " ON p.uid = u.id " +
dac39588
BA
94 "WHERE p.gid = " + id;
95 db.all(query, (err2,players) => {
96 if (!!err2)
97 return cb(err2);
71468011
BA
98 if (light)
99 {
100 const game = Object.assign({},
101 gameInfo,
102 {players: players}
103 );
104 return cb(null, game);
105 }
dac39588
BA
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 =
dcd68c41 114 "SELECT msg, name, added " +
3837d4f7
BA
115 "FROM Chats " +
116 "WHERE gid = " + id;
dac39588
BA
117 db.all(query, (err4,chats) => {
118 if (!!err4)
119 return cb(err4);
120 const game = Object.assign({},
3837d4f7
BA
121 gameInfo,
122 {
123 players: players,
124 moves: moves,
125 chats: chats,
126 }
127 );
dac39588 128 return cb(null, game);
3837d4f7 129 });
dac39588
BA
130 });
131 });
132 });
133 });
134 },
00f2759e 135
71468011 136 // For display on MyGames or Hall: no need for moves or chats
dac39588
BA
137 getByUser: function(uid, excluded, cb)
138 {
139 db.serialize(function() {
dac39588 140 const query =
77c50966 141 "SELECT DISTINCT gid " +
dac39588
BA
142 "FROM Players " +
143 "WHERE uid " + (excluded ? "<>" : "=") + " " + uid;
144 db.all(query, (err,gameIds) => {
145 if (!!err)
146 return cb(err);
99f12ac0
BA
147 if (gameIds.length == 0)
148 return cb(null, []);
dac39588
BA
149 let gameArray = [];
150 for (let i=0; i<gameIds.length; i++)
151 {
71468011 152 GameModel.getOne(gameIds[i]["gid"], true, (err2,game) => {
dac39588
BA
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 },
ab4f4bf2 164
411d23cd
BA
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
58e7b94e
BA
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 }
633959bf
BA
188 if (!!obj.drawOffer && !obj.drawOffer.match(/^[wbtn]$/))
189 return "Wrong draw offer format";
58e7b94e
BA
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";
dcd68c41
BA
194 if (!!obj.scoreMsg && !obj.scoreMsg.match(/^[a-zA-Z ]+$/))
195 return "Wrong characters in score message";
58e7b94e 196 if (!!obj.chat)
58e7b94e 197 return UserModel.checkNameEmail({name: obj.chat.name});
58e7b94e
BA
198 return "";
199 },
200
3837d4f7 201 // obj can have fields move, chat, fen, drawOffer and/or score
f41ce580 202 update: function(id, obj)
3d55deea 203 {
dac39588 204 db.parallelize(function() {
3d55deea
BA
205 let query =
206 "UPDATE Games " +
207 "SET ";
3837d4f7 208 let modifs = "";
63ca2b89 209 if (!!obj.message)
3837d4f7 210 modifs += "message = message || ' ' || '" + obj.message + "',";
633959bf 211 // NOTE: if drawOffer is set, we should check that it's player's turn
dfeb96ea
BA
212 // A bit overcomplicated. Let's trust the client on that for now...
213 if (!!obj.drawOffer)
633959bf
BA
214 {
215 if (obj.drawOffer == "n") //Special "None" update
216 obj.drawOffer = "";
217 modifs += "drawOffer = '" + obj.drawOffer + "',";
218 }
3d55deea 219 if (!!obj.fen)
3837d4f7 220 modifs += "fen = '" + obj.fen + "',";
3d55deea 221 if (!!obj.score)
3837d4f7 222 modifs += "score = '" + obj.score + "',";
dcd68c41
BA
223 if (!!obj.scoreMsg)
224 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
3837d4f7
BA
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 }
f41ce580
BA
231 if (!!obj.move)
232 {
afc42601 233 const m = obj.move;
f41ce580 234 query =
63ca2b89 235 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
58e7b94e
BA
236 "(" + id + ",?," + m.played + "," + m.idx + ")";
237 db.run(query, JSON.stringify(m.squares));
f41ce580 238 }
3837d4f7
BA
239 if (!!obj.chat)
240 {
dac39588
BA
241 query =
242 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 243 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 244 db.run(query, obj.chat.msg);
3837d4f7 245 }
3d55deea
BA
246 });
247 },
248
dac39588
BA
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 },
d431028c
BA
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 =
fd41e587 278 "SELECT id,created " +
d431028c
BA
279 "FROM Games ";
280 db.all(query, (err,games) => {
281 games.forEach(g => {
282 query =
fd41e587 283 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
d431028c
BA
284 "FROM Moves " +
285 "WHERE gid = " + g.id;
fd41e587
BA
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))
d431028c 291 {
fd41e587 292 return GameModel.remove(g.id);
d431028c
BA
293 }
294 });
295 });
296 });
297 });
298 },
00f2759e 299}
ab4f4bf2
BA
300
301module.exports = GameModel;