| 1 | var db = require("../utils/database"); |
| 2 | |
| 3 | /* |
| 4 | * Structure: |
| 5 | * id: integer |
| 6 | * added: datetime |
| 7 | * uid: user id (int) |
| 8 | * target: recipient id (optional) |
| 9 | * vid: variant id (int) |
| 10 | * fen: varchar (optional) |
| 11 | * timeControl: string (3m+2s, 7d+1d ...) |
| 12 | */ |
| 13 | |
| 14 | const ChallengeModel = |
| 15 | { |
| 16 | checkChallenge: function(c) |
| 17 | { |
| 18 | if (!c.vid.match(/^[0-9]+$/)) |
| 19 | return "Wrong variant ID"; |
| 20 | |
| 21 | if (!c.timeControl.match(/^[0-9dhms +]+$/)) |
| 22 | return "Wrong characters in time control"; |
| 23 | |
| 24 | if (!c.fen.match(/^[a-zA-Z0-9, /-]+$/)) |
| 25 | return "Bad FEN string"; |
| 26 | }, |
| 27 | |
| 28 | // fen cannot be undefined |
| 29 | create: function(c, cb) |
| 30 | { |
| 31 | db.serialize(function() { |
| 32 | let query = |
| 33 | "INSERT INTO Challenges " + |
| 34 | "(added, uid, " + (!!c.to ? "target, " : "") + |
| 35 | "vid, fen, timeControl) VALUES " + |
| 36 | "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") + |
| 37 | c.vid + ",'" + c.fen + "','" + c.timeControl + "')"; |
| 38 | db.run(query, err => { |
| 39 | return cb(err); |
| 40 | }); |
| 41 | }); |
| 42 | }, |
| 43 | |
| 44 | getOne: function(id, cb) |
| 45 | { |
| 46 | db.serialize(function() { |
| 47 | let query = |
| 48 | "SELECT * " + |
| 49 | "FROM Challenges " + |
| 50 | "WHERE id = " + id; |
| 51 | db.get(query, (err,challenge) => { |
| 52 | return cb(err, challenge); |
| 53 | }); |
| 54 | }); |
| 55 | }, |
| 56 | |
| 57 | // all challenges except where target is defined and not me |
| 58 | getByUser: function(uid, cb) |
| 59 | { |
| 60 | db.serialize(function() { |
| 61 | const query = |
| 62 | "SELECT * " + |
| 63 | "FROM Challenges " + |
| 64 | "WHERE target IS NULL OR target = " + uid; |
| 65 | db.run(query, (err,challenges) => { |
| 66 | return cb(err, challenges); |
| 67 | }); |
| 68 | }); |
| 69 | }, |
| 70 | |
| 71 | remove: function(id, uid) |
| 72 | { |
| 73 | db.serialize(function() { |
| 74 | let query = |
| 75 | "SELECT 1 " + |
| 76 | "FROM Challenges " + |
| 77 | "WHERE id = " + id + " AND uid = " + uid; |
| 78 | db.run(query, (err,rows) => { |
| 79 | if (rows.length == 0) |
| 80 | return res.json({errmsg: "Not your challenge"}); |
| 81 | query = |
| 82 | "DELETE FROM Challenges " + |
| 83 | "WHERE id = " + id; |
| 84 | db.run(query); |
| 85 | }); |
| 86 | }); |
| 87 | }, |
| 88 | } |
| 89 | |
| 90 | module.exports = ChallengeModel; |