Experimental symmetric randomness + deterministic option
[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 {
20 return (
21 c.vid.toString().match(/^[0-9]+$/) &&
22 c.cadence.match(/^[0-9dhms +]+$/) &&
23 c.randomness.toString().match(/^[0-2]$/) &&
24 c.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
25 (!c.to || UserModel.checkNameEmail({name: c.to}))
26 );
27 },
28
29 create: function(c, cb)
30 {
31 db.serialize(function() {
32 const query =
33 "INSERT INTO Challenges " +
34 "(added, uid, " + (!!c.to ? "target, " : "") +
35 "vid, randomness, fen, cadence) " +
36 "VALUES " +
37 "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
38 c.vid + "," + c.randomness + ",'" + c.fen + "','" + c.cadence + "')";
39 db.run(query, function(err) {
40 cb(err, {cid: this.lastID});
41 });
42 });
43 },
44
45 // All challenges related to user with ID uid
46 getByUser: function(uid, cb)
47 {
48 db.serialize(function() {
49 const query =
50 "SELECT * " +
51 "FROM Challenges " +
52 "WHERE target IS NULL" +
53 " OR uid = " + uid +
54 " OR target = " + uid;
55 db.all(query, (err,challenges) => {
56 cb(err, challenges);
57 });
58 });
59 },
60
61 remove: function(id)
62 {
63 db.serialize(function() {
64 const query =
65 "DELETE FROM Challenges " +
66 "WHERE id = " + id;
67 db.run(query);
68 });
69 },
70
71 safeRemove: function(id, uid)
72 {
73 db.serialize(function() {
74 const query =
75 "SELECT 1 " +
76 "FROM Challenges " +
77 "WHERE id = " + id + " AND uid = " + uid;
78 db.get(query, (err,chall) => {
79 if (!err && chall)
80 ChallengeModel.remove(id);
81 });
82 });
83 },
84 }
85
86 module.exports = ChallengeModel;