-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron.js
80 lines (78 loc) · 3.49 KB
/
cron.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var mongoose = require('mongoose');
var Metrics = mongoose.model('Metrics');
var Pack = mongoose.model('Pack');
var Author = mongoose.model('Author');
var Sticker = mongoose.model('Sticker');
var Tag = mongoose.model('Tag');
var async = require('async');
module.exports = {
run: function(callback) {
var calls = [];
// Update hits
calls.push(function(callback) {
var version = require('./package.json').version;
var today = new Date();
Metrics.findOne({
version: version
}).exec(function(err, metrics) {
if (!err) {
if (!metrics) {
metrics = new Metrics({
version: version
});
}
var last_daily_update = metrics.hits.daily;
var daily_update = last_daily_update <= today;
var subcalls = [];
[Pack, Author, Sticker, Tag].forEach(function (schema) {
subcalls.push(function (callback) {
schema.find().exec(function (err, objs) {
if (!err && objs) {
objs.forEach(function (obj) {
if (daily_update) {
var days_tracking = obj.hits.counts.length;
for (var i = 1; i < days_tracking; i++) {
obj.hits.counts[i - 1] = obj.hits.counts[i];
}
obj.hits.counts[days_tracking - 1] = 0;
obj.hits.score = 0;
for (var j = 0; j < days_tracking; j++) {
obj.hits.score += (j + 1) * obj.hits.counts[j];
}
}
obj.noUpdate = true;
obj.save(function (err, obj) {
});
});
}
callback(null);
});
});
});
async.parallel(subcalls, function(err, results) {
if (daily_update) {
var daily_future = new Date();
daily_future.setDate(daily_future.getDate() + 1);
metrics.hits.daily = daily_future;
}
metrics.save(function(err, metrics) {
if (err) {
console.log('Error saving metrics: ' + err.message);
} else {
console.log('Metrics updated and saved for app v' + version);
}
callback(null);
});
});
} else {
console.log('Error parsing metrics: ' + err.message);
callback(null);
}
});
});
async.series(calls, function(err, results) {
console.log("Cron done.");
callback();
});
}
};