summaryrefslogtreecommitdiff
path: root/modules/email/email.js
blob: d7fe171ed24189ef5ea9ebfa2cf56885834d5708 (plain)
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
var cmn = require("../$common.js"),
    fs = require("fs"),
    child_process = require("child_process"),
    bodyParser = require("body-parser");

var ratelimitAllowed = (function() {
	var numEvents = 20, period = 24 * 3600 * 1000;
	var eventList = [];

	return function ratelimitAllowed() {
		var now = new Date();
		while (now - eventList[0] > period) eventList.unshift();
		if (eventList.length >= numEvents) return false;
		eventList.push(now);
		return true;
	};
})();

function sendEmail(recip, text) {
	var opts = {
		stdio: ["pipe", "inherit", "inherit"]
	};
	var proc = child_process.spawn("msmtp", ["--read-recipients"], opts);

	// Make sure it doesn't run indefinitely
	var timeout = setTimeout(() => {proc.kill();}, 5000);
	proc.on("exit", () => clearTimeout(timeout));
	proc.on("error", err => {
		console.log("email: Failed to start msmtp:", err);
		clearTimeout(timeout);
	});
	proc.stdin.on("error", err => {
		console.log("email: Failed to write to msmtp:", err);
		clearTimeout(timeout);
	});
	proc.stdin.end(
		"To: " + recip + "\n" +
		"Subject: Mail from email module\n\n" +
		text
	);
}

module.exports = function(app, io, moddir) {
	var allowedRecipients, password;

	try {
		allowedRecipients =
			fs.readFileSync(moddir + "/allowed_recipients.txt").toString().trim().split("\n");
		password = fs.readFileSync(moddir + "/password.txt").toString().trim();
	} catch (e) {
		console.error(e);
		return false;
	}

	app.post("/email", bodyParser.json(), function(req, res) {
		var body = req.body;
		console.log(body);
		if (typeof body != "object" ||
				typeof body.password != "string" ||
				typeof body.to != "string" ||
				typeof body.text != "string" ||
				body.password != password ||
				allowedRecipients.indexOf(body.to) == -1) {
			res.status(400).send("Invalid request");
			return;
		}
		var text = body.text.slice(0, 1000000);  // 1 MB is enough
		sendEmail(body.to, body.text);
		res.end();
	});
};