-
Notifications
You must be signed in to change notification settings - Fork 0
/
schedule.js
78 lines (68 loc) · 2.04 KB
/
schedule.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
var mongoose = require('mongoose');
var nodemailer = require('nodemailer');
var hbs_mail = require('nodemailer-express-handlebars');
var schedule = require('node-schedule');
// Mongoose models
var User = mongoose.model('User');
var Event = mongoose.model('Event');
var Gift = mongoose.model('Gift');
// Nodemailer transporter, email config
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '[email protected]',
pass: 'giftit12'
}
});
// Email templates
transporter.use('compile', hbs_mail({
viewPath: 'emails/',
extName: '.hbs'
}));
// Every day at 5pm
var rule = new schedule.RecurrenceRule();
rule.hour = 17;
rule.minute = 0;
var checkEventsJob = schedule.scheduleJob(rule, checkEvents);
function checkEvents () {
// Today
var today = new Date();
// Get all users
User.find({}).populate('eventlist').exec(function (err, users) {
if (err) return;
// Get only users who request notifications
users.filter(function (user) {
return user.options.notify_me;
}).forEach(function (user) {
// Get dates of user's events
var dates = user.eventlist.map(function(evt) {
return {
'date': new Date(evt.date),
'evt': evt.name,
'id': evt._id
}
});
// Calculate the date difference from today
dates.forEach(function (date) {
var diff = Math.floor((today - date)/(1000 * 3600 * 24));
if (diff == user.options.notify_time) {
// Send an email to remind the user
transporter.sendMail({
from: '[email protected]',
to: user.email,
subject: 'Reminder! You have an event coming up...',
template: 'reminder',
context: {
name: user.first_name,
evt_name: dates.evt,
evt_id: dates.id
}
}, function (err, info) {
if (err) return console.log(error);
console.log('Message sent', info.response);
});
}
});
});
});
}