Fix RR notation + en-passant
[vchess.git] / server / models / Challenge.js
... / ...
CommitLineData
1const 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 * options: varchar
12 * fen: varchar (optional)
13 * cadence: string (3m+2s, 7d ...)
14 * options: string (js object)
15 */
16
17const ChallengeModel = {
18
19 checkChallenge: function(c) {
20 return (
21 c.vid.toString().match(/^[0-9]+$/) &&
22 c.cadence.match(/^[0-9dhms +]+$/) &&
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, 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) {
37 cb(err, { id: this.lastID });
38 });
39 });
40 },
41
42 // All challenges related to user with ID uid
43 getByUser: function(uid, cb) {
44 db.serialize(function() {
45 const query =
46 "SELECT * " +
47 "FROM Challenges " +
48 "WHERE target IS NULL" +
49 " OR uid = " + uid +
50 " OR target = " + uid;
51 db.all(query, (err, challenges) => {
52 cb(err, challenges);
53 });
54 });
55 },
56
57 remove: function(id) {
58 db.serialize(function() {
59 const query =
60 "DELETE FROM Challenges " +
61 "WHERE id = " + id;
62 db.run(query);
63 });
64 },
65
66 safeRemove: function(id, uid) {
67 db.serialize(function() {
68 const query =
69 "SELECT 1 " +
70 "FROM Challenges " +
71 "WHERE id = " + id + " " +
72 // Condition: I'm the sender or the target
73 "AND (uid = " + uid + " OR target = " + uid + ")";
74 db.get(query, (err,chall) => {
75 if (!err && chall)
76 ChallengeModel.remove(id);
77 });
78 });
79 }
80
81};
82
83module.exports = ChallengeModel;