Fix challenge send+accept. Now debug game launch from server
[vchess.git] / server / models / Challenge.js
1 var db = require("../utils/database");
2
3 /*
4 * Structure:
5 * id: integer
6 * added: datetime
7 * uid: user id (int)
8 * target: recipient id (optional)
9 * vid: variant id (int)
10 * fen: varchar (optional)
11 * timeControl: string (3m+2s, 7d+1d ...)
12 */
13
14 const ChallengeModel =
15 {
16 checkChallenge: function(c)
17 {
18 if (!c.vid.toString().match(/^[0-9]+$/))
19 return "Wrong variant ID";
20 if (!c.timeControl.match(/^[0-9dhms +]+$/))
21 return "Wrong characters in time control";
22 if (!c.fen.match(/^[a-zA-Z0-9, /-]*$/))
23 return "Bad FEN string";
24 return "";
25 },
26
27 // fen cannot be undefined
28 create: function(c, cb)
29 {
30 db.serialize(function() {
31 const query =
32 "INSERT INTO Challenges " +
33 "(added, uid, " + (!!c.to ? "target, " : "") +
34 "vid, fen, timeControl) VALUES " +
35 "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
36 c.vid + ",'" + c.fen + "','" + c.timeControl + "')";
37 db.run(query, function(err) {
38 return cb(err, {cid: this.lastID});
39 });
40 });
41 },
42
43 getOne: function(id, cb)
44 {
45 db.serialize(function() {
46 const query =
47 "SELECT * " +
48 "FROM Challenges " +
49 "WHERE id = " + id;
50 db.get(query, (err,challenge) => {
51 return cb(err, challenge);
52 });
53 });
54 },
55
56 // all challenges except where target is defined and not me
57 getByUser: function(uid, cb)
58 {
59 db.serialize(function() {
60 const query =
61 "SELECT * " +
62 "FROM Challenges " +
63 "WHERE target IS NULL OR target = " + uid;
64 db.all(query, (err,challenges) => {
65 return cb(err, challenges);
66 });
67 });
68 },
69
70 remove: function(id)
71 {
72 db.serialize(function() {
73 const query =
74 "DELETE FROM Challenges " +
75 "WHERE id = " + id;
76 db.run(query);
77 });
78 },
79
80 safeRemove: function(id, uid, cb)
81 {
82 db.serialize(function() {
83 const query =
84 "SELECT 1 " +
85 "FROM Challenges " +
86 "WHERE id = " + id + " AND uid = " + uid;
87 db.get(query, (err,chall) => {
88 if (!chall)
89 return cb({errmsg: "Not your challenge"});
90 ChallengeModel.remove(id);
91 cb(null);
92 });
93 });
94 },
95 }
96
97 module.exports = ChallengeModel;