forked from codeforamerica/demophone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.js
More file actions
56 lines (48 loc) · 1.45 KB
/
web.js
File metadata and controls
56 lines (48 loc) · 1.45 KB
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
var path = require('path');
var logfmt = require('logfmt');
var twilio = require('twilio');
var express = require('express');
var app = express();
var client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
// Enabled Basic Auth if username and password configured
if (process.env.HTTP_BASIC_USER && process.env.HTTP_BASIC_PASS) {
app.use(express.basicAuth(process.env.HTTP_BASIC_USER, process.env.HTTP_BASIC_PASS));
}
// Express Middleware
app.use(logfmt.requestLogger());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.static(path.join(__dirname, 'public')));
// Enable long-polling of text responses.
// Quick and fast solution, not meant to scale.
connections = [];
app.get('/getResponses', function(req, res) {
connections.push(res);
});
// Send messages to Twilio
app.post('/sendText', function(req, res) {
client.sendMessage({
to: req.body.to,
from: process.env.TWILIO_PHONE_NUMBER,
body: req.body.body,
}, function(err, result) {
if (err) {
console.log('Error sending!');
console.log(err);
res.send(500);
}
res.send(200);
});
});
// Receive messages from Twilio
app.post('/receiveText', function(req, res) {
connections.forEach(function(c) {
c.send(req.body);
});
var twiml = new twilio.TwimlResponse();
res.send(twiml.toString());
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});