Save current state (unmerged, broken, not working...)
[vchess.git] / models / Challenge.js
CommitLineData
8d7e2786
BA
1var db = require("../utils/database");
2
3/*
4 * Structure:
5 * _id: BSON id
6 * vid: variant ID
7 * from: player ID
8 * to: player ID, undefined if automatch
9 */
10
11exports.create = function(vid, from, to, callback)
12{
13 let chall = {
14 "vid": vid,
15 "from": from
16 };
17 if (!!to)
18 chall.to = to;
19 db.challenges.insert(chall, callback);
20}
21
22//////////
23// GETTERS
24
25exports.getById = function(cid, callback)
26{
27 db.challenges.findOne({_id: cid}, callback);
28}
29
30// For index page: obtain challenges that the player can accept
31exports.getByPlayer = function(uid, callback)
32{
33 db.challenges.aggregate(
34 {$match: {$or: [
35 {"to": uid},
36 {$and: [{"from": {$ne: uid}}, {"to": {$exists: false}}]}
37 ]}},
38 {$project: {_id:0, vid:1}},
39 {$group: {_id:"$vid", count:{$sum:1}}},
40 callback);
41}
42
43// For variant page (challenges related to a player)
44exports.getByVariant = function(uid, vid, callback)
45{
46 db.challenges.find({$and: [
47 {"vid": vid},
48 {$or: [
49 {"to": uid},
50 {"from": uid},
51 {"to": {$exists: false}},
52 ]}
53 ]}, callback);
54}
55
56//////////
57// REMOVAL
58
59exports.remove = function(cid, callback)
60{
61 db.challenges.remove({_id: cid}, callback);
62}
63
64// Remove challenges older than 1 month, and 1to1 older than 36h
65exports.removeOld = function()
66{
67 var tsNow = new Date().getTime();
68 // 86400000 = 24 hours in milliseconds
69 var day = 86400000;
70 db.challenges.find({}, (err,challengeArray) => {
71 challengeArray.forEach( c => {
72 if (c._id.getTimestamp() + 30*day < tsNow //automatch
73 || (!!c.to && c._id.getTimestamp() + 1.5*day < tsNow)) //1 to 1
74 {
75 db.challenges.remove({"_id": c._id});
76 }
77 });
78 });
79}