02e3194b130ae3e84cf9ec4e8e29ddcdc7401b83
[vchess.git] / server / models / Game.js
1 var 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 * timeControl: string
11 * score: varchar (result)
12 * scoreMsg: varchar ("Time", "Mutual agreement"...)
13 * created: datetime
14 * drawOffer: boolean
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 if (!g.id.toString().match(/^[0-9]+$/))
38 return "Wrong game ID";
39 if (!g.vid.toString().match(/^[0-9]+$/))
40 return "Wrong variant ID";
41 if (!g.vname.match(/^[a-zA-Z0-9]+$/))
42 return "Wrong variant name";
43 if (!g.timeControl.match(/^[0-9dhms +]+$/))
44 return "Wrong characters in time control";
45 if (!g.fen.match(/^[a-zA-Z0-9, /-]*$/))
46 return "Bad FEN string";
47 if (g.players.length != 2)
48 return "Need exactly 2 players";
49 if (g.players.some(p => !p.id.toString().match(/^[0-9]+$/)))
50 return "Wrong characters in player ID";
51 return "";
52 },
53
54 create: function(vid, fen, timeControl, players, cb)
55 {
56 db.serialize(function() {
57 let query =
58 "INSERT INTO Games"
59 + " (vid, fenStart, fen, score, timeControl, created, drawOffer)"
60 + " VALUES (" + vid + ",'" + fen + "','" + fen + "','*','"
61 + timeControl + "'," + Date.now() + "," + false + ")";
62 db.run(query, function(err) {
63 if (!!err)
64 return cb(err);
65 players.forEach((p,idx) => {
66 const color = (idx==0 ? "w" : "b");
67 query =
68 "INSERT INTO Players VALUES " +
69 "(" + this.lastID + "," + p.id + ",'" + color + "')";
70 db.run(query);
71 });
72 cb(null, {gid: this.lastID});
73 });
74 });
75 },
76
77 // TODO: queries here could be async, and wait for all to complete
78 getOne: function(id, cb)
79 {
80 db.serialize(function() {
81 // TODO: optimize queries?
82 let query =
83 // NOTE: g.scoreMsg can be NULL
84 // (in this case score = "*" and no reason to look at it)
85 "SELECT g.id, g.vid, g.fen, g.fenStart, g.timeControl, g.score, " +
86 "g.scoreMsg, v.name AS vname " +
87 "FROM Games g " +
88 "JOIN Variants v " +
89 " ON g.vid = v.id " +
90 "WHERE g.id = " + id;
91 db.get(query, (err,gameInfo) => {
92 if (!!err)
93 return cb(err);
94 query =
95 "SELECT p.uid, p.color, u.name " +
96 "FROM Players p " +
97 "JOIN Users u " +
98 " ON p.uid = u.id " +
99 "WHERE p.gid = " + id;
100 db.all(query, (err2,players) => {
101 if (!!err2)
102 return cb(err2);
103 query =
104 "SELECT squares, played, idx " +
105 "FROM Moves " +
106 "WHERE gid = " + id;
107 db.all(query, (err3,moves) => {
108 if (!!err3)
109 return cb(err3);
110 query =
111 "SELECT msg, name, added " +
112 "FROM Chats " +
113 "WHERE gid = " + id;
114 db.all(query, (err4,chats) => {
115 if (!!err4)
116 return cb(err4);
117 const game = Object.assign({},
118 gameInfo,
119 {
120 players: players,
121 moves: moves,
122 chats: chats,
123 }
124 );
125 return cb(null, game);
126 });
127 });
128 });
129 });
130 });
131 },
132
133 getByUser: function(uid, excluded, cb)
134 {
135 db.serialize(function() {
136 // Next query is fine because a player appear at most once in a game
137 const query =
138 "SELECT gid " +
139 "FROM Players " +
140 "WHERE uid " + (excluded ? "<>" : "=") + " " + uid;
141 db.all(query, (err,gameIds) => {
142 if (!!err)
143 return cb(err);
144 gameIds = gameIds || []; //might be empty
145 let gameArray = [];
146 for (let i=0; i<gameIds.length; i++)
147 {
148 GameModel.getOne(gameIds[i]["gid"], (err2,game) => {
149 if (!!err2)
150 return cb(err2);
151 gameArray.push(game);
152 // Call callback function only when gameArray is complete:
153 if (i == gameIds.length - 1)
154 return cb(null, gameArray);
155 });
156 }
157 });
158 });
159 },
160
161 getPlayers: function(id, cb)
162 {
163 db.serialize(function() {
164 const query =
165 "SELECT id " +
166 "FROM Players " +
167 "WHERE gid = " + id;
168 db.all(query, (err,players) => {
169 return cb(err, players);
170 });
171 });
172 },
173
174 checkGameUpdate: function(obj)
175 {
176 // Check all that is possible (required) in obj:
177 if (!!obj.move)
178 {
179 if (!obj.move.played.toString().match(/^[0-9]+$/))
180 return "Wrong move played time";
181 if (!obj.move.idx.toString().match(/^[0-9]+$/))
182 return "Wrong move index";
183 }
184 if (!!obj.fen && !obj.fen.match(/^[a-zA-Z0-9, /-]*$/))
185 return "Wrong FEN string";
186 if (!!obj.score && !obj.score.match(/^[012?*\/-]+$/))
187 return "Wrong characters in score";
188 if (!!obj.scoreMsg && !obj.scoreMsg.match(/^[a-zA-Z ]+$/))
189 return "Wrong characters in score message";
190 if (!!obj.chat)
191 return UserModel.checkNameEmail({name: obj.chat.name});
192 return "";
193 },
194
195 // obj can have fields move, chat, fen, drawOffer and/or score
196 update: function(id, obj)
197 {
198 db.parallelize(function() {
199 let query =
200 "UPDATE Games " +
201 "SET ";
202 let modifs = "";
203 if (!!obj.message)
204 modifs += "message = message || ' ' || '" + obj.message + "',";
205 if ([true,false].includes(obj.drawOffer))
206 modifs += "drawOffer = " + obj.drawOffer + ",";
207 if (!!obj.fen)
208 modifs += "fen = '" + obj.fen + "',";
209 if (!!obj.score)
210 modifs += "score = '" + obj.score + "',";
211 if (!!obj.scoreMsg)
212 modifs += "scoreMsg = '" + obj.scoreMsg + "',";
213 modifs = modifs.slice(0,-1); //remove last comma
214 if (modifs.length > 0)
215 {
216 query += modifs + " WHERE id = " + id;
217 db.run(query);
218 }
219 if (!!obj.move)
220 {
221 const m = obj.move;
222 query =
223 "INSERT INTO Moves (gid, squares, played, idx) VALUES " +
224 "(" + id + ",?," + m.played + "," + m.idx + ")";
225 db.run(query, JSON.stringify(m.squares));
226 }
227 if (!!obj.chat)
228 {
229 query =
230 "INSERT INTO Chats (gid, msg, name, added) VALUES ("
231 + id + ",?,'" + obj.chat.name + "'," + "," + Date.now() + ")";
232 db.run(query, obj.chat.msg);
233 }
234 });
235 },
236
237 remove: function(id)
238 {
239 db.parallelize(function() {
240 let query =
241 "DELETE FROM Games " +
242 "WHERE id = " + id;
243 db.run(query);
244 query =
245 "DELETE FROM Players " +
246 "WHERE gid = " + id;
247 db.run(query);
248 query =
249 "DELETE FROM Moves " +
250 "WHERE gid = " + id;
251 db.run(query);
252 query =
253 "DELETE FROM Chats " +
254 "WHERE gid = " + id;
255 db.run(query);
256 });
257 },
258
259 cleanGamesDb: function()
260 {
261 const tsNow = Date.now();
262 // 86400000 = 24 hours in milliseconds
263 const day = 86400000;
264 db.serialize(function() {
265 let query =
266 "SELECT id,score " +
267 "FROM Games ";
268 db.all(query, (err,games) => {
269 games.forEach(g => {
270 query =
271 "SELECT max(played) AS lastMaj " +
272 "FROM Moves " +
273 "WHERE gid = " + g.id;
274 db.get(query, (err2,updated) => {
275 if (!updated && tsNow - g.created > 7*day)
276 return GameModel.remove(g.id);
277 const lastMaj = updated.lastMaj;
278 if (g.score != "*" && tsNow - lastMaj > 7*day ||
279 g.score == "*" && tsNow - lastMaj > 91*day)
280 {
281 GameModel.remove(g.id);
282 }
283 });
284 });
285 });
286 });
287 },
288 }
289
290 module.exports = GameModel;