1 var db
= require("../utils/database");
2 const UserModel
= require("./User");
9 * target: recipient id (optional)
10 * vid: variant id (int)
11 * fen: varchar (optional)
12 * timeControl: string (3m+2s, 7d+1d ...)
15 const ChallengeModel
=
17 checkChallenge: function(c
)
19 if (!c
.vid
.toString().match(/^[0-9]+$/))
20 return "Wrong variant ID";
21 if (!c
.timeControl
.match(/^[0-9dhms
+]+$/))
22 return "Wrong characters in time control";
23 if (!c
.fen
.match(/^[a-zA-Z0-9, /-]*$/))
24 return "Bad FEN string";
26 return UserModel
.checkNameEmail({name: c
.to
});
30 // fen cannot be undefined
31 create: function(c
, cb
)
33 db
.serialize(function() {
35 "INSERT INTO Challenges " +
36 "(added, uid, " + (!!c
.to
? "target, " : "") +
37 "vid, fen, timeControl) VALUES " +
38 "(" + Date
.now() + "," + c
.uid
+ "," + (!!c
.to
? c
.to
+ "," : "") +
39 c
.vid
+ ",'" + c
.fen
+ "','" + c
.timeControl
+ "')";
40 db
.run(query
, function(err
) {
41 return cb(err
, {cid: this.lastID
});
46 getOne: function(id
, cb
)
48 db
.serialize(function() {
53 db
.get(query
, (err
,challenge
) => {
54 return cb(err
, challenge
);
59 // All challenges except where target is defined and not me,
60 // and I'm not the sender.
61 getByUser: function(uid
, cb
)
63 db
.serialize(function() {
67 "WHERE target IS NULL" +
69 " OR target = " + uid
;
70 db
.all(query
, (err
,challenges
) => {
71 return cb(err
, challenges
);
78 db
.serialize(function() {
80 "DELETE FROM Challenges " +
86 safeRemove: function(id
, uid
, cb
)
88 db
.serialize(function() {
92 "WHERE id = " + id
+ " AND uid = " + uid
;
93 db
.get(query
, (err
,chall
) => {
95 return cb({errmsg: "Not your challenge"});
96 ChallengeModel
.remove(id
);
102 // Remove challenges older than 1 month, and 1to1 older than 2 days
103 removeOld: function()
105 const tsNow
= Date
.now();
106 // 86400000 = 24 hours in milliseconds
107 const day
= 86400000;
108 db
.serialize(function() {
110 "SELECT id, target, added " +
112 db
.all(query
, (err
, challenges
) => {
113 challenges
.forEach(c
=> {
114 if ((!c
.target
&& tsNow
- c
.added
> 30*day
) ||
115 (!!c
.target
&& tsNow
- c
.added
> 2*day
))
117 db
.run("DELETE FROM Challenges WHERE id = " + c
.id
);
125 module
.exports
= ChallengeModel
;