Allow hyphen in username on server side + add icons for navigation
[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 * fen: varchar (optional)
12 * cadence: string (3m+2s, 7d+1d ...)
13 */
14
15 const ChallengeModel =
16 {
17 checkChallenge: function(c)
18 {
19 return (
20 c.vid.toString().match(/^[0-9]+$/) &&
21 c.cadence.match(/^[0-9dhms +]+$/) &&
22 c.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
23 (!c.to || UserModel.checkNameEmail({name: c.to}))
24 );
25 },
26
27 create: function(c, cb)
28 {
29 db.serialize(function() {
30 const query =
31 "INSERT INTO Challenges " +
32 "(added, uid, " + (!!c.to ? "target, " : "") + "vid, fen, cadence) " +
33 "VALUES " +
34 "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
35 c.vid + ",'" + c.fen + "','" + c.cadence + "')";
36 db.run(query, function(err) {
37 cb(err, {cid: this.lastID});
38 });
39 });
40 },
41
42 // All challenges related to user with ID uid
43 getByUser: function(uid, cb)
44 {
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 {
60 db.serialize(function() {
61 const query =
62 "DELETE FROM Challenges " +
63 "WHERE id = " + id;
64 db.run(query);
65 });
66 },
67
68 safeRemove: function(id, uid)
69 {
70 db.serialize(function() {
71 const query =
72 "SELECT 1 " +
73 "FROM Challenges " +
74 "WHERE id = " + id + " AND uid = " + uid;
75 db.get(query, (err,chall) => {
76 if (!err && chall)
77 ChallengeModel.remove(id);
78 });
79 });
80 },
81 }
82
83 module.exports = ChallengeModel;