7ccaa76fbf135bcf64a24c2c9906a9e535e1ca07
[vchess.git] / server / models / Challenge.js
1 var db = require("../utils/database");
2 const UserModel = require("./User");
3
4 /*
5 * Structure:
6 * id: integer
7 * added: datetime
8 * uid: user id (int)
9 * target: recipient id (optional)
10 * vid: variant id (int)
11 * fen: varchar (optional)
12 * timeControl: string (3m+2s, 7d+1d ...)
13 */
14
15 const ChallengeModel =
16 {
17 checkChallenge: function(c)
18 {
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";
25 if (!!c.to)
26 return UserModel.checkNameEmail({name: c.to});
27 return "";
28 },
29
30 // fen cannot be undefined
31 create: function(c, cb)
32 {
33 db.serialize(function() {
34 const query =
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});
42 });
43 });
44 },
45
46 getOne: function(id, cb)
47 {
48 db.serialize(function() {
49 const query =
50 "SELECT * " +
51 "FROM Challenges " +
52 "WHERE id = " + id;
53 db.get(query, (err,challenge) => {
54 return cb(err, challenge);
55 });
56 });
57 },
58
59 // All challenges except where target is defined and not me
60 getByUser: function(uid, cb)
61 {
62 db.serialize(function() {
63 const query =
64 "SELECT * " +
65 "FROM Challenges " +
66 "WHERE target IS NULL OR target = " + uid;
67 db.all(query, (err,challenges) => {
68 return cb(err, challenges);
69 });
70 });
71 },
72
73 remove: function(id)
74 {
75 db.serialize(function() {
76 const query =
77 "DELETE FROM Challenges " +
78 "WHERE id = " + id;
79 db.run(query);
80 });
81 },
82
83 safeRemove: function(id, uid, cb)
84 {
85 db.serialize(function() {
86 const query =
87 "SELECT 1 " +
88 "FROM Challenges " +
89 "WHERE id = " + id + " AND uid = " + uid;
90 db.get(query, (err,chall) => {
91 if (!chall)
92 return cb({errmsg: "Not your challenge"});
93 ChallengeModel.remove(id);
94 cb(null);
95 });
96 });
97 },
98
99 // Remove challenges older than 1 month, and 1to1 older than 2 days
100 removeOld: function()
101 {
102 const tsNow = Date.now();
103 // 86400000 = 24 hours in milliseconds
104 const day = 86400000;
105 db.serialize(function() {
106 const query =
107 "SELECT id, target, added " +
108 "FROM Challenges";
109 db.all(query, (err, challenges) => {
110 challenges.forEach(c => {
111 if ((!c.target && tsNow - c.added > 30*day) ||
112 (!!c.target && tsNow - c.added > 2*day))
113 {
114 db.run("DELETE FROM Challenges WHERE id = " + c.id);
115 }
116 });
117 });
118 });
119 },
120 }
121
122 module.exports = ChallengeModel;