Experimental change: options replacing randomness (more general)
[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)
eb2d61de 11 * options: varchar
ab4f4bf2 12 * fen: varchar (optional)
7ba4a5bc 13 * cadence: string (3m+2s, 7d ...)
eb2d61de 14 * options: string (js object)
8d7e2786
BA
15 */
16
0234201f 17const ChallengeModel = {
937c24ab 18
0234201f 19 checkChallenge: function(c) {
866842c3
BA
20 return (
21 c.vid.toString().match(/^[0-9]+$/) &&
22 c.cadence.match(/^[0-9dhms +]+$/) &&
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, " : "") +
eb2d61de
BA
33 "vid, options, fen, cadence) " +
34 "VALUES (" + Date.now() + "," + c.uid + "," + (c.to ? c.to + "," : "")
35 + c.vid + ",?,'" + c.fen + "','" + c.cadence + "')";
36 db.run(query, c.options, function(err) {
0234201f 37 cb(err, { id: this.lastID });
bf20f404 38 });
b1aa927b
BA
39 });
40 },
ab4f4bf2 41
866842c3 42 // All challenges related to user with ID uid
0234201f 43 getByUser: function(uid, cb) {
b1aa927b
BA
44 db.serialize(function() {
45 const query =
46 "SELECT * " +
47 "FROM Challenges " +
fe4c7e67
BA
48 "WHERE target IS NULL" +
49 " OR uid = " + uid +
50 " OR target = " + uid;
0234201f 51 db.all(query, (err, challenges) => {
866842c3 52 cb(err, challenges);
b1aa927b
BA
53 });
54 });
55 },
8d7e2786 56
0234201f 57 remove: function(id) {
b1aa927b 58 db.serialize(function() {
2be5d614
BA
59 const query =
60 "DELETE FROM Challenges " +
61 "WHERE id = " + id;
62 db.run(query);
63 });
64 },
65
0234201f 66 safeRemove: function(id, uid) {
2be5d614
BA
67 db.serialize(function() {
68 const query =
4edfed6c
BA
69 "SELECT 1 " +
70 "FROM Challenges " +
1511c610
BA
71 "WHERE id = " + id + " " +
72 // Condition: I'm the sender or the target
51145f8c 73 "AND (uid = " + uid + " OR target = " + uid + ")";
bebcc8d4 74 db.get(query, (err,chall) => {
866842c3
BA
75 if (!err && chall)
76 ChallengeModel.remove(id);
36093eba 77 });
b1aa927b 78 });
937c24ab
BA
79 }
80
81};
d431028c 82
ab4f4bf2 83module.exports = ChallengeModel;