-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
91 lines (65 loc) · 2.48 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
// COVID-19 Anonymous Notifer | NodeJS Server Program
// Created for the COVID-19 Global Hackathon 1.0 by @shaunakg and @abinash3366
// Hackathon: https://covid-global-hackathon.devpost.com/
// Repository: https://github.com/shaunakg/covid-19-anonymous-notifier
// Issues/Bugs: https://github.com/shaunakg/covid-19-anonymous-notifier/issues
// Initialise env and modules
require('dotenv').config({path:'sendgrid.env'});
var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http').createServer(app);
const webport = process.env.PORT || 8080;
// Initialise SendGrid's API
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// Read static email contents
var notifHtml = fs.readFileSync(__dirname + '/static/notif-html.html', 'utf8');
var notifTextOnly = fs.readFileSync(__dirname + '/static/notif.txt', 'utf8');
var processed_emails = [];
console.log(process.env.SENDGRID_API_KEY);
app.use(express.static("static"));
app.get("/api/testing", function (req, res) {
res.send(req.query);
});
app.get("/api/notify", function (req, res) {
if (req.query.emails && req.query.emails.length > 0) {
var emails = req.query.emails.split(",");
var repeat_emails = [];
for (i = 0; i < emails.length; i++) {
if (processed_emails.includes(emails[i]) && emails[i] != "[email protected]") {
repeat_emails.push(emails.splice(i, 1));
} else {
processed_emails.push(i)
}
}
console.log("Processing emails: " + emails);
console.log("Excluding repeats: "+ repeat_emails);
const msg = {
to: emails,
from: '[email protected]',
subject: 'Important! Someone you were in contact with recently tested positive to COVID-19',
text: notifTextOnly,
html: notifHtml,
};
sgMail.sendMultiple(msg).then(() => {
if (repeat_emails.length > 0) {
res.redirect("../../?status=200_repeat_emails&emails=" + emails.join() + "&repeats=" + repeat_emails.join());
} else {
res.redirect("../../?status=200_send_ok&emails=" + emails.join());
}
}).catch(error => {
console.error(error.toString());
const {message, code, response} = error;
const {headers, body} = response;
try {
res.redirect("../../?status=400_email_send_err&emails=" + emails.join());
} catch(e) {res.redirect("../../?status=400_email_send_err");}
});
} else {
res.redirect("../../?status=400_wrong_params")
}
});
http.listen(webport, function(){
console.log('listening on *:' + webport);
});