-
Notifications
You must be signed in to change notification settings - Fork 511
/
app.js
231 lines (201 loc) · 6.41 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
230
231
var express = require('express')
, app = express()
, _ = require('underscore')
, fs = require('fs')
, mixpanel = require('mixpanel')
, exec = require('child_process').exec
, spawn = require('child_process').spawn
, Stream = require('stream')
, providers = require('../lib/providers.js')
, redis = require('redis-url').connect()
// Optional modules
var banned_numbers;
try {
banned_numbers = require('./banned_numbers.js')
} catch(e) {
banned_numbers = {BLACKLIST: {}};
}
var mpq;
try {
mixpanel_config = require('./mixpanel_config.js')
mpq = new mixpanel.Client(mixpanel_config.api_key);
} catch(e) {
mpq = {track: function() {}};
}
var access_keys;
try {
// Optionally, you may specify special access keys in a keys.json file.
// These access keys are not rate-limited.
// See example_keys.json for format.
access_keys = require('./keys.json');
} catch (e) {
access_keys = {};
}
// Express config
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
// App routes
app.get('/', function(req, res) {
fs.readFile(__dirname + '/views/index.html', 'utf8', function(err, text){
res.send(text);
});
});
app.get('/providers/:region', function(req, res) {
// Utility function, just to check the providers currently loaded
res.send(providers[req.params.region]);
});
app.post('/text', function(req, res) {
var number = stripPhone(req.body.number);
if (number.length < 9 || number.length > 10) {
res.send({success:false, message:'Invalid phone number.'});
return;
}
textRequestHandler(req, res, number, 'us', req.query.key);
});
app.post('/canada', function(req, res) {
textRequestHandler(req, res, stripPhone(req.body.number), 'canada', req.query.key);
});
app.post('/intl', function(req, res) {
textRequestHandler(req, res, stripPhone(req.body.number), 'intl', req.query.key);
});
// App helper functions
function textRequestHandler(req, res, number, region, key) {
if (!number || !req.body.message) {
mpq.track('incomplete request');
res.send({success:false, message:'Number and message parameters are required.'});
return;
}
if (banned_numbers.BLACKLIST[number]) {
mpq.track('banned number');
res.send({success:false,message:'Sorry, texts to this number are disabled.'});
return;
}
var ip = req.header('X-Real-IP') || req.connection.remoteAddress;
var message = req.body.message;
if (message.indexOf(':') > -1) {
// Handle problem with vtext where message would not get sent properly if it
// contains a colon
message = ' ' + message;
}
var tracking_details = {
number: number,
message: req.body.message,
ip: ip
};
var doSendText = function(response_obj) {
response_obj = response_obj || {};
// Time to actually send the message
sendText(number, message, region, function(err) {
if (err) {
mpq.track('sendText failed', tracking_details);
res.send(_.extend(response_obj,
{
success:false,
message:'Communication with SMS gateway failed.'
}));
}
else {
mpq.track('sendText success', tracking_details);
res.send(_.extend(response_obj, {success:true}));
}
});
};
// Do they have a valid access key?
if (key && key in access_keys) {
console.log('Got valid key', key, '... not applying limits.');
// Skip verification
mpq.track('sendText skipping verification', _.extend(tracking_details, {
key: key,
}));
doSendText({used_key: key});
return;
}
// If they don't have a special key, apply rate limiting and verification
var ipkey = 'textbelt:ip:' + ip + '_' + dateStr();
var phonekey = 'textbelt:phone:' + number;
redis.incr(phonekey, function(err, num) {
if (err) {
mpq.track('redis fail');
res.send({success:false, message:'Could not validate phone# quota.'});
return;
}
setTimeout(function() {
redis.decr(phonekey, function(err, num) {
if (err) {
mpq.track('failed to decr phone quota', {number: number});
console.log('*** WARNING failed to decr ' + number);
}
});
}, 1000*60*3);
if (num > 3) {
mpq.track('exceeded phone quota');
res.send({success:false, message:'Exceeded quota for this phone number. ' + number});
return;
}
// now check against ip quota
redis.incr(ipkey, function(err, num) {
if (err) {
mpq.track('redis fail');
res.send({success:false, message:'Could not validate IP quota.'});
return;
}
if (num > 75) {
mpq.track('exceeded ip quota');
res.send({success:false, message:'Exceeded quota for this IP address. ' + ip});
return;
}
setTimeout(function() {
redis.decr(ipkey, function(err, num) {
if (err) {
mpq.track('failed to decr ip key', {ipkey: ipkey});
console.log('*** WARNING failed to decr ' + ipkey);
}
});
}, 1000*60*60*24);
// Cleared to send now
doSendText();
}); // end redis ipkey incr
}); // end redis phonekey incr
} // end textRequestHandler
function dateStr() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
return mm + '/' + dd + '/' + yyyy;
}
function stripPhone(phone) {
return (phone+'').replace(/\D/g, '');
}
function sendText(phone, message, region, cb) {
console.log('txting phone', phone, ':', message);
region = region || 'us';
var providers_list = providers[region];
var done = _.after(providers_list.length, function() {
cb(false);
});
_.each(providers_list, function(provider) {
var email = provider.replace('%s', phone);
email = 'Subject: Text\r\n\r\n' + email;
var child = spawn('sendmail', ['-f', 'txt2@textbelt.com', email]);
child.stdout.on('data', console.log);
child.stderr.on('data', console.log);
child.on('error', function(data) {
mpq.track('sendmail failed', {email: email, data: data});
done();
});
child.on('exit', function(code, signal) {
done();
});
child.stdin.write(message + '\n.');
child.stdin.end();
});
}
// Start server
var port = process.env.PORT || 9090;
app.listen(port, function() {
console.log('Listening on', port);
});