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