Revise server code + a few fixes in trnalsations and ComputerGame
[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
f41ce580 211 update: function(id, obj)
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 }
866842c3 238 if (obj.move)
f41ce580 239 {
afc42601 240 const m = obj.move;
f41ce580 241 query =
63ca2b89 242 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
58e7b94e
BA
243 "(" + id + ",?," + m.played + "," + m.idx + ")";
244 db.run(query, JSON.stringify(m.squares));
f41ce580 245 }
866842c3 246 if (obj.chat)
3837d4f7 247 {
dac39588
BA
248 query =
249 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
41c80bb6 250 + id + ",?,'" + obj.chat.name + "'," + Date.now() + ")";
58e7b94e 251 db.run(query, obj.chat.msg);
3837d4f7 252 }
3d55deea
BA
253 });
254 },
255
dac39588
BA
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 },
d431028c
BA
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 =
0f7011a2 285 "SELECT id, created " +
d431028c
BA
286 "FROM Games ";
287 db.all(query, (err,games) => {
288 games.forEach(g => {
289 query =
fd41e587 290 "SELECT count(*) as nbMoves, max(played) AS lastMaj " +
d431028c
BA
291 "FROM Moves " +
292 "WHERE gid = " + g.id;
fd41e587
BA
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))
d431028c 298 {
89021f18 299 GameModel.remove(g.id);
d431028c
BA
300 }
301 });
302 });
303 });
304 });
305 },
00f2759e 306}
ab4f4bf2
BA
307
308module.exports = GameModel;