Fix Hiddenqueen 'quasi-checkmate'
[vchess.git] / server / models / Challenge.js
1 const 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 * randomness: integer in 0..2
12 * fen: varchar (optional)
13 * cadence: string (3m+2s, 7d ...)
14 */
15
16 const ChallengeModel = {
17
18 checkChallenge: function(c) {
19 return (
20 c.vid.toString().match(/^[0-9]+$/) &&
21 c.cadence.match(/^[0-9dhms +]+$/) &&
22 c.randomness.toString().match(/^[0-2]$/) &&
23 c.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
24 (!c.to || UserModel.checkNameEmail({ name: c.to }))
25 );
26 },
27
28 create: function(c, cb) {
29 db.serialize(function() {
30 const query =
31 "INSERT INTO Challenges " +
32 "(added, uid, " + (c.to ? "target, " : "") +
33 "vid, randomness, fen, cadence) " +
34 "VALUES " +
35 "(" + Date.now() + "," + c.uid + "," + (c.to ? c.to + "," : "") +
36 c.vid + "," + c.randomness + ",'" + c.fen + "','" + c.cadence + "')";
37 db.run(query, function(err) {
38 cb(err, { id: this.lastID });
39 });
40 });
41 },
42
43 // All challenges related to user with ID uid
44 getByUser: function(uid, cb) {
45 db.serialize(function() {
46 const query =
47 "SELECT * " +
48 "FROM Challenges " +
49 "WHERE target IS NULL" +
50 " OR uid = " + uid +
51 " OR target = " + uid;
52 db.all(query, (err, challenges) => {
53 cb(err, challenges);
54 });
55 });
56 },
57
58 remove: function(id) {
59 db.serialize(function() {
60 const query =
61 "DELETE FROM Challenges " +
62 "WHERE id = " + id;
63 db.run(query);
64 });
65 },
66
67 safeRemove: function(id, uid) {
68 db.serialize(function() {
69 const query =
70 "SELECT 1 " +
71 "FROM Challenges " +
72 "WHERE id = " + id + " " +
73 // Condition: I'm the sender or the target
74 "AND (uid = " + uid + " OR target = " + uid + ")";
75 db.get(query, (err,chall) => {
76 if (!err && chall)
77 ChallengeModel.remove(id);
78 });
79 });
80 }
81
82 };
83
84 module.exports = ChallengeModel;