Try to switch off cleanGamesDb
[vchess.git] / server / models / Challenge.js
... / ...
CommitLineData
1var db = require("../utils/database");
2const 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 * cadence: string (3m+2s, 7d+1d ...)
13 */
14
15const ChallengeModel =
16{
17 checkChallenge: function(c)
18 {
19 if (!c.vid.toString().match(/^[0-9]+$/))
20 return "Wrong variant ID";
21 if (!c.cadence.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, " : "") + "vid, fen, cadence) " +
37 "VALUES " +
38 "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
39 c.vid + ",'" + c.fen + "','" + c.cadence + "')";
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 // and I'm not the sender.
61 getByUser: function(uid, cb)
62 {
63 db.serialize(function() {
64 const query =
65 "SELECT * " +
66 "FROM Challenges " +
67 "WHERE target IS NULL" +
68 " OR uid = " + uid +
69 " OR target = " + uid;
70 db.all(query, (err,challenges) => {
71 return cb(err, challenges);
72 });
73 });
74 },
75
76 remove: function(id)
77 {
78 db.serialize(function() {
79 const query =
80 "DELETE FROM Challenges " +
81 "WHERE id = " + id;
82 db.run(query);
83 });
84 },
85
86 safeRemove: function(id, uid, cb)
87 {
88 db.serialize(function() {
89 const query =
90 "SELECT 1 " +
91 "FROM Challenges " +
92 "WHERE id = " + id + " AND uid = " + uid;
93 db.get(query, (err,chall) => {
94 if (!chall)
95 return cb({errmsg: "Not your challenge"});
96 ChallengeModel.remove(id);
97 cb(null);
98 });
99 });
100 },
101}
102
103module.exports = ChallengeModel;