-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtwilio.js
95 lines (83 loc) · 2.22 KB
/
twilio.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
/*jslint node: true */
'use strict';
var util = require('util');
// Make sure to escape the message appropriately for XML
var xmlSkeleton = '<?xml version="1.0" encoding="UTF-8"?><Response>%s</Response>';
var xmlSMS = '<Sms>%s</Sms>';
var escapeMap = {
'<': '<',
'>': '>',
'&': '&',
'\'': ''',
'"': '"'
}
var escapeRE = /[<>&'"]/gm;
function escape(str) {
if (!str) {
return str;
}
return str.replace(escapeRE, function (match) {
return escapeMap[match];
});
}
module.exports = {
sendTwiML: function sendTwiML(res, xml) {
res.setHeader('Content-Type', 'text/xml');
res.send(xml);
},
sms: function sms(message) {
if (util.isArray(message)) {
var multiSms = message.map(function (m) {
return util.format(xmlSMS, escape(m));
}).join('');
return util.format(xmlSkeleton, multiSms);
}
if (message.length <= 160) {
return util.format(xmlSkeleton, util.format(xmlSMS, escape(message)));
}
var done = false;
var arr = [];
var index;
var remainder = message;
while (!done) {
if (remainder.length <= 160) {
arr.push(remainder);
done = true;
break;
}
// TODO: look for newlines, not just spaces.
index = remainder.lastIndexOf(' ', 159);
if (index !== -1) {
// Split at the last space.
arr.push(remainder.substring(0, index));
if (index + 2 < remainder.length) {
remainder = remainder.substring(index + 1);
} else {
done = true;
}
} else {
if (remainder.length <= 160) {
// We didn't find a space, but the rest of the message is under 160
// characters.
arr.push(remainder);
done = true;
} else {
// We didn't find a space, so we'll just split at the 160-character
// mark.
arr.push(remainder.substring(0, 159));
remainder = remainder.substring(160);
}
}
}
return sms(arr);
},
// Count the number of outbound messages in the TwiML response.
countMessages: function (xml) {
var re = /<Sms>/g;
var arr = xml.match(re);
if (arr === null) {
return 0;
}
return arr.length;
}
}