Fix Hiddenqueen 'quasi-checkmate'
[vchess.git] / server / models / Challenge.js
CommitLineData
c5c47010 1const db = require("../utils/database");
58e7b94e 2const UserModel = require("./User");
8d7e2786
BA
3
4/*
bf20f404 5 * Structure:
00f2759e
BA
6 * id: integer
7 * added: datetime
8 * uid: user id (int)
bf20f404 9 * target: recipient id (optional)
00f2759e 10 * vid: variant id (int)
7ba4a5bc 11 * randomness: integer in 0..2
ab4f4bf2 12 * fen: varchar (optional)
7ba4a5bc 13 * cadence: string (3m+2s, 7d ...)
8d7e2786
BA
14 */
15
0234201f 16const ChallengeModel = {
937c24ab 17
0234201f 18 checkChallenge: function(c) {
866842c3
BA
19 return (
20 c.vid.toString().match(/^[0-9]+$/) &&
21 c.cadence.match(/^[0-9dhms +]+$/) &&
7ba4a5bc 22 c.randomness.toString().match(/^[0-2]$/) &&
866842c3 23 c.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
0234201f 24 (!c.to || UserModel.checkNameEmail({ name: c.to }))
866842c3 25 );
b1aa927b 26 },
98db2082 27
0234201f 28 create: function(c, cb) {
b1aa927b 29 db.serialize(function() {
bebcc8d4 30 const query =
b1aa927b 31 "INSERT INTO Challenges " +
51145f8c 32 "(added, uid, " + (c.to ? "target, " : "") +
7ba4a5bc
BA
33 "vid, randomness, fen, cadence) " +
34 "VALUES " +
51145f8c 35 "(" + Date.now() + "," + c.uid + "," + (c.to ? c.to + "," : "") +
7ba4a5bc 36 c.vid + "," + c.randomness + ",'" + c.fen + "','" + c.cadence + "')";
8c564f46 37 db.run(query, function(err) {
0234201f 38 cb(err, { id: this.lastID });
bf20f404 39 });
b1aa927b
BA
40 });
41 },
ab4f4bf2 42
866842c3 43 // All challenges related to user with ID uid
0234201f 44 getByUser: function(uid, cb) {
b1aa927b
BA
45 db.serialize(function() {
46 const query =
47 "SELECT * " +
48 "FROM Challenges " +
fe4c7e67
BA
49 "WHERE target IS NULL" +
50 " OR uid = " + uid +
51 " OR target = " + uid;
0234201f 52 db.all(query, (err, challenges) => {
866842c3 53 cb(err, challenges);
b1aa927b
BA
54 });
55 });
56 },
8d7e2786 57
0234201f 58 remove: function(id) {
b1aa927b 59 db.serialize(function() {
2be5d614
BA
60 const query =
61 "DELETE FROM Challenges " +
62 "WHERE id = " + id;
63 db.run(query);
64 });
65 },
66
0234201f 67 safeRemove: function(id, uid) {
2be5d614
BA
68 db.serialize(function() {
69 const query =
4edfed6c
BA
70 "SELECT 1 " +
71 "FROM Challenges " +
1511c610
BA
72 "WHERE id = " + id + " " +
73 // Condition: I'm the sender or the target
51145f8c 74 "AND (uid = " + uid + " OR target = " + uid + ")";
bebcc8d4 75 db.get(query, (err,chall) => {
866842c3
BA
76 if (!err && chall)
77 ChallengeModel.remove(id);
36093eba 78 });
b1aa927b 79 });
937c24ab
BA
80 }
81
82};
d431028c 83
ab4f4bf2 84module.exports = ChallengeModel;