-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
229 lines (201 loc) · 6.73 KB
/
app.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
const express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
jwt = require('jsonwebtoken'),
_ = require('underscore'),
moment = require('moment'),
countdown = require('countdown'),
path = require('path'),
URL = require('url'),
basicAuth = require('basic-auth'),
{ Pool } = require('pg');
const config = {
cloudmailinForwardAddress: process.env.CLOUDMAILIN_FORWARD_ADDRESS,
jwtSecret: process.env.JWT_SECRET || process.env.DATABASE_URL,
name : process.env.NAME,
email : process.env.EMAIL,
webRoot : process.env.WEB_ROOT.replace(/\/$/, '')
};
const db = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
const nodemailer = require('nodemailer');
const mg = require('nodemailer-mailgun-transport');
const auth = {
auth: {
api_key: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN,
},
}
const nodemailerMailgun = nodemailer.createTransport(mg(auth));
function createBasicAuth(username, password) {
return 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
}
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use('/public', express.static(path.join(__dirname, 'public')));
/**
* Convert app.render to an async function for use in async routes.
* @param name
* @param options
* @returns {Promise<unknown>}
*/
async function render(name, options) {
return new Promise((resolve, reject) => {
app.render(name, options, function(err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
})
});
}
/**
* Simple HTTP basic auth that looks for a valid, signed JWT in the password
* field. Username is ignored.
*/
app.use(function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.status(401).end();
};
const user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
jwt.verify(user.pass, config.jwtSecret, function(err, jwt) {
if (err) {
return unauthorized(res);
}
return next();
});
});
app.get('/', async function(req, res, next) {
try {
const entries = await getEntries();
_.each(entries, function (entry) {
entry.formattedDate = moment(entry.createdat).format('MMMM Do YYYY');
entry.formattedDay = moment(entry.createdat).format('dddd');
entry.formattedText = '<p>' + entry.text;
entry.formattedText = entry.formattedText.replace(/\r/g, '');
entry.formattedText = entry.formattedText.replace(/\n\n/g, '<p>');
entry.formattedText = entry.formattedText.replace(/\n/g, ' ');
entry.formattedText = entry.formattedText.trim();
});
res.render('index', {
name: config.name,
entries: entries
});
}
catch (err) {
return next(err);
}
});
app.post('/emails', async function(req, res, next) {
try {
if (!req.body.reply_plain) {
return res.status(404).end();
}
const doc = {
createdat : new Date(),
text : req.body.reply_plain.trim()
};
await createEntry(doc);
res.status(200).end();
}
catch (err) {
return next(err);
}
});
app.post('/jobs/send', async function(req, res, next) {
function createPreviousEntriesUrl(webRoot) {
const token = jwt.sign({},
config.jwtSecret,
{ expiresIn : '24h' });
const url = URL.parse(webRoot);
url.auth = 'a:' + token;
return URL.format(url);
}
try {
const previousEntry = await getRandomEntry();
const previousEntriesUrl = createPreviousEntriesUrl(config.webRoot);
const subject = await render('email-subject', {
date : moment().format('dddd, MMM Do'),
});
let bodyParams = {
previousEntriesUrl : createPreviousEntriesUrl(config.webRoot),
};
if (previousEntry) {
bodyParams.previousEntryDate = capitalize(countdown(previousEntry.createdat, null, null, 2));
bodyParams.previousEntryBody = previousEntry.text;
}
const body = await render('email-body-text', bodyParams);
let bodyHtmlParams = {
previousEntriesUrl : createPreviousEntriesUrl(config.webRoot),
};
if (previousEntry) {
bodyHtmlParams.previousEntryDate = capitalize(countdown(previousEntry.createdat, null, null, 2));
bodyHtmlParams.previousEntryBody = previousEntry.text.replace(/\n/g, '<br>');
}
const bodyHtml = await render('email-body-html', bodyHtmlParams);
await nodemailerMailgun.sendMail({
from: `"WhoaLife" <${config.cloudmailinForwardAddress}>`,
to: `"${config.name}" <${config.email}>`,
subject: subject,
text: body,
html: bodyHtml
});
res.status(200).end();
}
catch (err) {
console.log(err);
return next(err);
}
});
async function getRandomEntry() {
let rows = (await db.query(`
select * from entries
where date_part('month', createdat) = date_part('month', now())
and date_part('day', createdat) = date_part('day', now())
`)).rows;
if (!rows.length) {
rows = (await db.query("select * from entries where date_part('dow', createdat) = date_part('dow', now())")).rows;
}
if (!rows.length) {
rows = (await db.query("select * from entries where date_part('day', createdat) = date_part('day', now())")).rows;
}
if (!rows.length) {
rows = (await db.query("select * from entries")).rows;
}
return _.sample(rows);
}
async function getEntries() {
return (await db.query('select * from entries order by createdat desc')).rows;
}
async function createEntry(entry) {
return (await db.query('insert into entries (createdat, text) values ($1, $2)', [entry.createdat, entry.text])).rows;
}
function capitalize(str) {
if (!str || !str.length) {
return str;
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
module.exports = app;
// Print handy startup messages
const token = jwt.sign({}, config.jwtSecret);
let url = URL.parse(config.webRoot);
url.auth = 'a:' + token;
url = URL.format(url);
console.log('WhoaLife');
console.log();
console.log('Scheduler Send Mail Command: curl -XPOST \'' + url + 'jobs/send\'');
console.log();
console.log('Cloudmailin Target URL: ' + url + 'emails');