forked from rapidpro/mailroom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
twiml.go
491 lines (406 loc) · 13.6 KB
/
twiml.go
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package twiml
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"github.com/gomodule/redigo/redis"
"github.com/jmoiron/sqlx"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/flows/events"
"github.com/nyaruka/goflow/flows/routers/waits"
"github.com/nyaruka/goflow/flows/routers/waits/hints"
"github.com/nyaruka/goflow/utils"
"github.com/nyaruka/mailroom/ivr"
"github.com/nyaruka/mailroom/models"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// BaseURL is our default base URL for TWIML channels (public for testing overriding)
var BaseURL = `https://api.twilio.com`
// IgnoreSignatures controls whether we ignore signatures (public for testing overriding)
var IgnoreSignatures = false
const (
twilioChannelType = models.ChannelType("T")
twimlChannelType = models.ChannelType("TW")
signalWireChannelType = models.ChannelType("SW")
callPath = `/2010-04-01/Accounts/{AccountSID}/Calls.json`
hangupPath = `/2010-04-01/Accounts/{AccountSID}/Calls/{SID}.json`
signatureHeader = "X-Twilio-Signature"
statusFailed = "failed"
gatherTimeout = 30
recordTimeout = 600
accountSIDConfig = "account_sid"
authTokenConfig = "auth_token"
sendURLConfig = "send_url"
baseURLConfig = "base_url"
errorBody = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>An error was encountered. Goodbye.</Say>
<Hangup></Hangup>
</Response>
`
)
var indentMarshal = true
type client struct {
channel *models.Channel
baseURL string
accountSID string
authToken string
validateSigs bool
}
func init() {
ivr.RegisterClientType(twimlChannelType, NewClientFromChannel)
ivr.RegisterClientType(twilioChannelType, NewClientFromChannel)
ivr.RegisterClientType(signalWireChannelType, NewClientFromChannel)
}
// NewClientFromChannel creates a new Twilio IVR client for the passed in account and and auth token
func NewClientFromChannel(channel *models.Channel) (ivr.Client, error) {
accountSID := channel.ConfigValue(accountSIDConfig, "")
authToken := channel.ConfigValue(authTokenConfig, "")
if accountSID == "" || authToken == "" {
return nil, errors.Errorf("missing auth_token or account_sid on channel config: %v for channel: %s", channel.Config(), channel.UUID())
}
baseURL := channel.ConfigValue(baseURLConfig, channel.ConfigValue(sendURLConfig, BaseURL))
return &client{
channel: channel,
baseURL: baseURL,
accountSID: accountSID,
authToken: authToken,
validateSigs: channel.Type() != signalWireChannelType,
}, nil
}
// NewClient creates a new Twilio IVR client for the passed in account and and auth token
func NewClient(accountSID string, authToken string) ivr.Client {
return &client{
baseURL: BaseURL,
accountSID: accountSID,
authToken: authToken,
}
}
func (c *client) DownloadMedia(url string) (*http.Response, error) {
return http.Get(url)
}
func (c *client) PreprocessResume(ctx context.Context, db *sqlx.DB, rp *redis.Pool, conn *models.ChannelConnection, r *http.Request) ([]byte, error) {
return nil, nil
}
func (c *client) CallIDForRequest(r *http.Request) (string, error) {
r.ParseForm()
callID := r.Form.Get("CallSid")
if callID == "" {
return "", errors.Errorf("no CallSid parameter found in URL: %s", r.URL)
}
return callID, nil
}
func (c *client) URNForRequest(r *http.Request) (urns.URN, error) {
r.ParseForm()
tel := r.Form.Get("Caller")
if tel == "" {
return "", errors.Errorf("no Caller parameter found in URL: %s", r.URL)
}
return urns.NewTelURNForCountry(tel, "")
}
// CallResponse is our struct for a Twilio call response
type CallResponse struct {
SID string `json:"sid"`
Status string `json:"status"`
}
// RequestCall causes this client to request a new outgoing call for this provider
func (c *client) RequestCall(client *http.Client, number urns.URN, callbackURL string, statusURL string) (ivr.CallID, error) {
form := url.Values{}
form.Set("To", number.Path())
form.Set("From", c.channel.Address())
form.Set("Url", callbackURL)
form.Set("StatusCallback", statusURL)
sendURL := c.baseURL + strings.Replace(callPath, "{AccountSID}", c.accountSID, -1)
resp, err := c.postRequest(client, sendURL, form)
if err != nil {
return ivr.NilCallID, errors.Wrapf(err, "error trying to start call")
}
if resp.StatusCode != 201 {
return ivr.NilCallID, errors.Errorf("received non 201 status for call start: %d", resp.StatusCode)
}
// read our body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ivr.NilCallID, errors.Wrapf(err, "error reading response body")
}
// parse out our call sid
call := &CallResponse{}
err = json.Unmarshal(body, call)
if err != nil || call.SID == "" {
return ivr.NilCallID, errors.Errorf("unable to read call id")
}
if call.Status == statusFailed {
return ivr.NilCallID, errors.Errorf("call status returned as failed")
}
return ivr.CallID(call.SID), nil
}
// HangupCall asks Twilio to hang up the call that is passed in
func (c *client) HangupCall(client *http.Client, callID string) error {
form := url.Values{}
form.Set("Status", "completed")
sendURL := c.baseURL + strings.Replace(hangupPath, "{AccountSID}", c.accountSID, -1)
sendURL = strings.Replace(sendURL, "{SID}", callID, -1)
resp, err := c.postRequest(client, sendURL, form)
if err != nil {
return errors.Wrapf(err, "error trying to hangup call")
}
if resp.StatusCode != 200 {
return errors.Errorf("received non 204 trying to hang up call: %d", resp.StatusCode)
}
return nil
}
// InputForRequest returns the input for the passed in request, if any
func (c *client) InputForRequest(r *http.Request) (string, utils.Attachment, error) {
// this could be a timeout, in which case we return nothing at all
timeout := r.Form.Get("timeout")
if timeout == "true" {
return "", ivr.NilAttachment, nil
}
// this could be empty, in which case we return nothing at all
empty := r.Form.Get("empty")
if empty == "true" {
return "", ivr.NilAttachment, nil
}
// otherwise grab the right field based on our wait type
waitType := r.Form.Get("wait_type")
switch waitType {
case "gather":
return r.Form.Get("Digits"), utils.Attachment(""), nil
case "record":
url := r.Form.Get("RecordingUrl")
if url == "" {
return "", ivr.NilAttachment, nil
}
return "", utils.Attachment("audio:" + r.Form.Get("RecordingUrl")), nil
default:
return "", ivr.NilAttachment, errors.Errorf("unknown wait_type: %s", waitType)
}
}
// StatusForRequest returns the current call status for the passed in status (and optional duration if known)
func (c *client) StatusForRequest(r *http.Request) (models.ConnectionStatus, int) {
status := r.Form.Get("CallStatus")
switch status {
case "queued", "ringing":
return models.ConnectionStatusWired, 0
case "in-progress", "initiated":
return models.ConnectionStatusInProgress, 0
case "completed":
duration, _ := strconv.Atoi(r.Form.Get("CallDuration"))
return models.ConnectionStatusCompleted, duration
case "busy", "no-answer", "canceled", "failed":
return models.ConnectionStatusErrored, 0
default:
logrus.WithField("call_status", status).Error("unknown call status in ivr callback")
return models.ConnectionStatusFailed, 0
}
}
// ValidateRequestSignature validates the signature on the passed in request, returning an error if it is invaled
func (c *client) ValidateRequestSignature(r *http.Request) error {
// shortcut for testing
if IgnoreSignatures || !c.validateSigs {
return nil
}
actual := r.Header.Get(signatureHeader)
if actual == "" {
return errors.Errorf("missing request signature header")
}
r.ParseForm()
path := r.URL.RequestURI()
proxyPath := r.Header.Get("X-Forwarded-Path")
if proxyPath != "" {
path = proxyPath
}
url := fmt.Sprintf("https://%s%s", r.Host, path)
expected, err := twCalculateSignature(url, r.PostForm, c.authToken)
if err != nil {
return errors.Wrapf(err, "error calculating signature")
}
// compare signatures in way that isn't sensitive to a timing attack
if !hmac.Equal(expected, []byte(actual)) {
return errors.Errorf("invalid request signature: %s", actual)
}
return nil
}
// WriteSessionResponse writes a TWIML response for the events in the passed in session
func (c *client) WriteSessionResponse(session *models.Session, resumeURL string, r *http.Request, w http.ResponseWriter) error {
// for errored sessions we should just output our error body
if session.Status() == models.SessionStatusErrored {
return errors.Errorf("cannot write IVR response for errored session")
}
// otherwise look for any say events
sprint := session.Sprint()
if sprint == nil {
return errors.Errorf("cannot write IVR response for session with no sprint")
}
// get our response
response, err := responseForSprint(resumeURL, session.Wait(), sprint.Events())
if err != nil {
return errors.Wrap(err, "unable to build response for IVR call")
}
_, err = w.Write([]byte(response))
if err != nil {
return errors.Wrap(err, "error writing IVR response")
}
return nil
}
// WriteErrorResponse writes an error / unavailable response
func (c *client) WriteErrorResponse(w http.ResponseWriter, err error) error {
r := &Response{Message: strings.Replace(err.Error(), "--", "__", -1)}
r.Commands = append(r.Commands, Say{Text: ivr.ErrorMessage})
r.Commands = append(r.Commands, Hangup{})
body, err := xml.Marshal(r)
if err != nil {
return err
}
_, err = w.Write([]byte(xml.Header + string(body)))
return err
}
// WriteEmptyResponse writes an empty (but valid) response
func (c *client) WriteEmptyResponse(w http.ResponseWriter, msg string) error {
r := &Response{Message: strings.Replace(msg, "--", "__", -1)}
body, err := xml.Marshal(r)
if err != nil {
return err
}
_, err = w.Write([]byte(xml.Header + string(body)))
return err
}
func (c *client) postRequest(client *http.Client, sendURL string, form url.Values) (*http.Response, error) {
req, _ := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
req.SetBasicAuth(c.accountSID, c.authToken)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
return client.Do(req)
}
// see https://www.twilio.com/docs/api/security
func twCalculateSignature(url string, form url.Values, authToken string) ([]byte, error) {
var buffer bytes.Buffer
buffer.WriteString(url)
keys := make(sort.StringSlice, 0, len(form))
for k := range form {
keys = append(keys, k)
}
keys.Sort()
for _, k := range keys {
buffer.WriteString(k)
for _, v := range form[k] {
buffer.WriteString(v)
}
}
// hash with SHA1
mac := hmac.New(sha1.New, []byte(authToken))
mac.Write(buffer.Bytes())
hash := mac.Sum(nil)
// encode with Base64
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(hash)))
base64.StdEncoding.Encode(encoded, hash)
return encoded, nil
}
// TWIML building utilities
type Say struct {
XMLName string `xml:"Say"`
Text string `xml:",chardata"`
}
type Play struct {
XMLName string `xml:"Play"`
URL string `xml:",chardata"`
}
type Hangup struct {
XMLName string `xml:"Hangup"`
}
type Redirect struct {
XMLName string `xml:"Redirect"`
URL string `xml:",chardata"`
}
type Gather struct {
XMLName string `xml:"Gather"`
NumDigits int `xml:"numDigits,attr,omitempty"`
FinishOnKey string `xml:"finishOnKey,attr,omitempty"`
Timeout int `xml:"timeout,attr,omitempty"`
Action string `xml:"action,attr,omitempty"`
Commands []interface{} `xml:",innerxml"`
}
type Record struct {
XMLName string `xml:"Record"`
Action string `xml:"action,attr,omitempty"`
MaxLength int `xml:"maxLength,attr,omitempty"`
}
type Response struct {
XMLName string `xml:"Response"`
Message string `xml:",comment"`
Gather *Gather `xml:"Gather"`
Commands []interface{} `xml:",innerxml"`
}
func responseForSprint(resumeURL string, w flows.ActivatedWait, es []flows.Event) (string, error) {
r := &Response{}
commands := make([]interface{}, 0)
for _, e := range es {
switch event := e.(type) {
case *events.IVRCreatedEvent:
if len(event.Msg.Attachments()) == 0 {
commands = append(commands, Say{Text: event.Msg.Text()})
} else {
for _, a := range event.Msg.Attachments() {
a = models.NormalizeAttachment(a)
commands = append(commands, Play{URL: a.URL()})
}
}
}
}
if w != nil {
msgWait, isMsgWait := w.(*waits.ActivatedMsgWait)
if !isMsgWait {
return "", errors.Errorf("unable to use wait of type: %s in IVR call", w.Type())
}
switch hint := msgWait.Hint().(type) {
case *hints.DigitsHint:
resumeURL = resumeURL + "&wait_type=gather"
gather := &Gather{
Action: resumeURL,
Commands: commands,
Timeout: gatherTimeout,
}
if hint.Count != nil {
gather.NumDigits = *hint.Count
}
gather.FinishOnKey = hint.TerminatedBy
r.Gather = gather
r.Commands = append(r.Commands, Redirect{URL: resumeURL + "&timeout=true"})
case *hints.AudioHint:
resumeURL = resumeURL + "&wait_type=record"
commands = append(commands, Record{Action: resumeURL, MaxLength: recordTimeout})
commands = append(commands, Redirect{URL: resumeURL + "&empty=true"})
r.Commands = commands
default:
return "", errors.Errorf("unable to use wait in IVR call, unknow type: %s", msgWait.Hint().Type())
}
} else {
// no wait? call is over, hang up
commands = append(commands, Hangup{})
r.Commands = commands
}
var body []byte
var err error
if indentMarshal {
body, err = xml.MarshalIndent(r, "", " ")
} else {
body, err = xml.Marshal(r)
}
if err != nil {
return "", errors.Wrap(err, "unable to marshal twiml body")
}
return xml.Header + string(body), nil
}