forked from codeforamerica/courtbot
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsendReminders.js
74 lines (66 loc) · 2.12 KB
/
sendReminders.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
var crypto = require('crypto');
var Knex = require('knex');
var twilio = require('twilio');
var client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
var knex = Knex.initialize({
client: 'pg',
connection: process.env.DATABASE_URL
});
// Finds reminders for cases happening tomorrow
var findReminders = function() {
return knex('reminders')
.where('sent', false)
.join('cases', 'reminders.case_id', '=', 'cases.id')
.where('cases.date', 'tomorrow')
.select();
};
function sendReminderMessages(reminders) {
return new Promise(function(resolve, reject) {
if (reminders.length === 0) {
console.log('No reminders to send out today.');
resolve();
}
var count = 0;
// Send SMS reminder
reminders.forEach(function(reminder) {
var decipher = crypto.createDecipher('aes256', process.env.PHONE_ENCRYPTION_KEY);
var phone = decipher.update(reminder.phone, 'hex', 'utf8') + decipher.final('utf8');
client.sendMessage({
to: phone,
from: process.env.TWILIO_PHONE_NUMBER,
body: 'Reminder: You\'ve got a court case tomorrow at ' + reminder.time +
' in court room ' + reminder.room +
'. Call us at (404) 954-7914 with any questions. -Atlanta Municipal Court'
}, function(err, result) {
if (err) {
console.log(err);
}
console.log('Reminder sent to ' + reminder.phone);
// Update table
knex('reminders')
.where('reminder_id', '=', reminder.reminder_id)
.update({'sent': true})
.exec(function(err, results) {
if (err) {
console.log(err);
}
}).then(function(err, data) {
if (err) {
console.log(err);
}
count++;
if (count === reminders.length) {
resolve();
}
});
});
});
});
};
module.exports = function() {
return new Promise(function(resolve, reject) {
findReminders().then(function(resp) {
sendReminderMessages(resp).then(resolve, reject);
}).catch(reject);
});
};