forked from rapidpro/mailroom
/
ivr.go
489 lines (411 loc) · 15 KB
/
ivr.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
package ivr
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/mailroom/config"
"github.com/nyaruka/mailroom/handler"
"github.com/nyaruka/mailroom/ivr"
"github.com/nyaruka/mailroom/models"
"github.com/nyaruka/mailroom/web"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
func init() {
web.RegisterRoute(http.MethodPost, "/mr/ivr/c/{uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}/handle", handleFlow)
web.RegisterRoute(http.MethodPost, "/mr/ivr/c/{uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}/status", handleStatus)
web.RegisterRoute(http.MethodPost, "/mr/ivr/c/{uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}/incoming", handleIncomingCall)
}
// TODO: creation of requests is awkward, would be nice to figure out how to unify how all that works
func handleIncomingCall(ctx context.Context, s *web.Server, r *http.Request, rawW http.ResponseWriter) error {
start := time.Now()
// dump our request
requestTrace, err := httputil.DumpRequest(r, true)
if err != nil {
return errors.Wrapf(err, "error creating request trace")
}
// wrap our writer
responseTrace := &bytes.Buffer{}
w := middleware.NewWrapResponseWriter(rawW, r.ProtoMajor)
w.Tee(responseTrace)
channelUUID := assets.ChannelUUID(chi.URLParam(r, "uuid"))
// load the org id for this UUID (we could load the entire channel here but we want to take the same paths through everything else)
orgID, err := models.OrgIDForChannelUUID(ctx, s.DB, channelUUID)
if err != nil {
return writeClientError(w, err)
}
// load our org
org, err := models.GetOrgAssets(ctx, s.DB, orgID)
if err != nil {
return writeClientError(w, errors.Wrapf(err, "error loading org assets"))
}
// and our channel
channel := org.ChannelByUUID(channelUUID)
if channel == nil {
return writeClientError(w, errors.Wrapf(err, "no active channel with uuid: %s", channelUUID))
}
var conn *models.ChannelConnection
// create a channel log for this request and connection
defer func() {
desc := "IVR event handled"
isError := false
if w.Status() != http.StatusOK {
desc = "IVR Error"
isError = true
}
path := r.URL.RequestURI()
proxyPath := r.Header.Get("X-Forwarded-Path")
if proxyPath != "" {
path = proxyPath
}
url := fmt.Sprintf("https://%s%s", r.Host, path)
_, err := models.InsertChannelLog(
ctx, s.DB, desc, isError,
r.Method, url, requestTrace, w.Status(), responseTrace.Bytes(),
start, time.Since(start),
channel, conn,
)
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error writing ivr channel log")
}
}()
// get the right kind of client
client, err := ivr.GetClient(channel)
if client == nil {
return writeClientError(w, errors.Wrapf(err, "unable to load client for channel: %s", channelUUID))
}
// validate this request's signature
err = client.ValidateRequestSignature(r)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "request failed signature validation"))
}
// build our session assets
sa, err := models.GetSessionAssets(org)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to load assets"))
}
// lookup the URN of the caller
urn, err := client.URNForRequest(r)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to find URN in request"))
}
// get the contact id for this URN
ids, err := models.ContactIDsFromURNs(ctx, s.DB, org, sa, []urns.URN{urn})
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to load contact by urn"))
}
contactID, found := ids[urn]
if !found {
return client.WriteErrorResponse(w, errors.Errorf("no contact for urn: %s", urn))
}
urn, err = models.URNForURN(ctx, s.DB, org, urn)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to load urn"))
}
// urn ID
urnID := models.GetURNID(urn)
if urnID == models.NilURNID {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to get id for URN"))
}
// we first create an incoming call channel event and see if that matches
event := models.NewChannelEvent(models.MOCallEventType, org.OrgID(), channel.ID(), contactID, urnID, nil, false)
externalID, err := client.CallIDForRequest(r)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to get external id from request"))
}
// create our connection
conn, err = models.InsertIVRConnection(
ctx, s.DB, org.OrgID(), channel.ID(), models.NilStartID, contactID, urnID,
models.ConnectionDirectionIn, models.ConnectionStatusInProgress, externalID,
)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "error creating ivr connection"))
}
// try to handle this event
session, err := handler.HandleChannelEvent(ctx, s.DB, s.RP, models.MOCallEventType, event, conn)
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error handling incoming call")
return client.WriteErrorResponse(w, errors.Wrapf(err, "error handling incoming call"))
}
// we got a session back so we have an active call trigger
if session != nil {
// build our resume URL
resumeURL := buildResumeURL(channel, conn, urn)
// have our client output our session status
err = client.WriteSessionResponse(session, resumeURL, r, w)
if err != nil {
return errors.Wrapf(err, "error writing ivr response for start")
}
return nil
}
// no session means no trigger, create a missed call event instead
// we first create an incoming call channel event and see if that matches
event = models.NewChannelEvent(models.MOMissEventType, org.OrgID(), channel.ID(), contactID, urnID, nil, false)
err = event.Insert(ctx, s.DB)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "error inserting channel event"))
}
// try to handle it, this time looking for a missed call event
session, err = handler.HandleChannelEvent(ctx, s.DB, s.RP, models.MOMissEventType, event, nil)
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error handling missed call")
return client.WriteErrorResponse(w, errors.Wrapf(err, "error handling missed call"))
}
// write our empty response
return client.WriteEmptyResponse(w, "missed call handled")
}
const (
actionStart = "start"
actionResume = "resume"
actionStatus = "status"
)
// IVRRequest is our form for what fields we expect in IVR callbacks
type IVRRequest struct {
ConnectionID models.ConnectionID `form:"connection" validate:"required"`
Action string `form:"action" validate:"required"`
}
// writeClientError is just a small utility method to write out a simple JSON error when we don't have a client yet
// to do it on our behalf
func writeClientError(w http.ResponseWriter, err error) error {
w.Header().Set("Content-type", "application/json")
w.WriteHeader(http.StatusBadRequest)
response := map[string]string{
"error": err.Error(),
}
serialized, err := json.Marshal(response)
if err != nil {
return errors.Wrapf(err, "error serializing error")
}
_, err = w.Write([]byte(serialized))
return errors.Wrapf(err, "error writing error")
}
func buildResumeURL(channel *models.Channel, conn *models.ChannelConnection, urn urns.URN) string {
domain := channel.ConfigValue(models.ChannelConfigCallbackDomain, config.Mailroom.Domain)
form := url.Values{
"action": []string{actionResume},
"connection": []string{fmt.Sprintf("%d", conn.ID())},
"urn": []string{urn.String()},
}
return fmt.Sprintf("https://%s/mr/ivr/c/%s/handle?%s", domain, channel.UUID(), form.Encode())
}
// handleFlow handles all incoming IVR requests related to a flow (status is handled elsewhere)
func handleFlow(ctx context.Context, s *web.Server, r *http.Request, rawW http.ResponseWriter) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*55)
defer cancel()
// dump our request
requestTrace, err := httputil.DumpRequest(r, true)
if err != nil {
return errors.Wrapf(err, "error creating request trace")
}
// wrap our writer
responseTrace := &bytes.Buffer{}
w := middleware.NewWrapResponseWriter(rawW, r.ProtoMajor)
w.Tee(responseTrace)
start := time.Now()
request := &IVRRequest{}
if err := web.DecodeAndValidateForm(request, r); err != nil {
return errors.Wrapf(err, "request failed validation")
}
// load our connection
conn, err := models.SelectChannelConnection(ctx, s.DB, request.ConnectionID)
if err != nil {
return errors.Wrapf(err, "unable to load channel connection with id: %d", request.ConnectionID)
}
// load our org
org, err := models.GetOrgAssets(ctx, s.DB, conn.OrgID())
if err != nil {
return writeClientError(w, errors.Wrapf(err, "error loading org assets"))
}
// and our channel
channel := org.ChannelByID(conn.ChannelID())
if channel == nil {
return writeClientError(w, errors.Wrapf(err, "no active channel with id: %d", conn.ChannelID()))
}
// create a channel log for this request and connection
defer func() {
desc := "IVR event handled"
isError := false
if w.Status() != http.StatusOK {
desc = "IVR Error"
isError = true
}
path := r.URL.RequestURI()
proxyPath := r.Header.Get("X-Forwarded-Path")
if proxyPath != "" {
path = proxyPath
}
url := fmt.Sprintf("https://%s%s", r.Host, path)
_, err := models.InsertChannelLog(
ctx, s.DB, desc, isError,
r.Method, url, requestTrace, w.Status(), responseTrace.Bytes(),
start, time.Since(start),
channel, conn,
)
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error writing ivr channel log")
}
}()
// get the right kind of client
client, err := ivr.GetClient(channel)
if client == nil {
return writeClientError(w, errors.Wrapf(err, "unable to load client for channel: %d", conn.ChannelID()))
}
// validate this request's signature if relevant
err = client.ValidateRequestSignature(r)
if err != nil {
return writeClientError(w, errors.Wrapf(err, "request failed signature validation"))
}
// load our contact
contacts, err := models.LoadContacts(ctx, s.DB, org, []models.ContactID{conn.ContactID()})
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "no such contact"))
}
if len(contacts) == 0 {
return client.WriteErrorResponse(w, errors.Errorf("no contact width id: %d", conn.ContactID()))
}
if contacts[0].IsStopped() || contacts[0].IsBlocked() {
return client.WriteErrorResponse(w, errors.Errorf("no contact width id: %d", conn.ContactID()))
}
// load the URN for this connection
urn, err := models.URNForID(ctx, s.DB, org, conn.ContactURNID())
if err != nil {
return client.WriteErrorResponse(w, errors.Errorf("unable to find connection urn: %d", conn.ContactURNID()))
}
// make sure our URN is indeed present on our contact, no funny business
found := false
for _, u := range contacts[0].URNs() {
if u.Identity() == urn.Identity() {
found = true
}
}
if !found {
return client.WriteErrorResponse(w, errors.Errorf("unable to find URN: %s on contact: %d", urn, conn.ContactID()))
}
resumeURL := buildResumeURL(channel, conn, urn)
// if this a start, start our contact
switch request.Action {
case actionStart:
err = ivr.StartIVRFlow(
ctx, s.DB, s.RP, client, resumeURL,
org, channel, conn, contacts[0], urn, conn.StartID(),
r, w,
)
case actionResume:
err = ivr.ResumeIVRFlow(
ctx, s.Config, s.DB, s.RP, s.S3Client, resumeURL, client,
org, channel, conn, contacts[0], urn,
r, w,
)
case actionStatus:
err = ivr.HandleIVRStatus(
ctx, s.DB, s.RP, org, client, conn,
r, w,
)
default:
err = client.WriteErrorResponse(w, errors.Errorf("unknown action: %s", request.Action))
}
// had an error? mark our connection as errored and log it
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error while handling IVR")
return ivr.WriteErrorResponse(ctx, s.DB, client, conn, w, err)
}
return nil
}
// handleStatus handles all incoming IVR events / status updates
func handleStatus(ctx context.Context, s *web.Server, r *http.Request, rawW http.ResponseWriter) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*55)
defer cancel()
// dump our request
requestTrace, err := httputil.DumpRequest(r, true)
if err != nil {
return errors.Wrapf(err, "error creating request trace")
}
// wrap our writer
responseTrace := &bytes.Buffer{}
w := middleware.NewWrapResponseWriter(rawW, r.ProtoMajor)
w.Tee(responseTrace)
start := time.Now()
channelUUID := assets.ChannelUUID(chi.URLParam(r, "uuid"))
// load the org id for this UUID (we could load the entire channel here but we want to take the same paths through everything else)
orgID, err := models.OrgIDForChannelUUID(ctx, s.DB, channelUUID)
if err != nil {
return writeClientError(w, err)
}
// load our org
org, err := models.GetOrgAssets(ctx, s.DB, orgID)
if err != nil {
return writeClientError(w, errors.Wrapf(err, "error loading org assets"))
}
// and our channel
channel := org.ChannelByUUID(channelUUID)
if channel == nil {
return writeClientError(w, errors.Wrapf(err, "no active channel with uuid: %s", channelUUID))
}
// get the right kind of client
client, err := ivr.GetClient(channel)
if client == nil {
return writeClientError(w, errors.Wrapf(err, "unable to load client for channel: %s", channelUUID))
}
// validate this request's signature if relevant
err = client.ValidateRequestSignature(r)
if err != nil {
return writeClientError(w, errors.Wrapf(err, "request failed signature validation"))
}
// get our external id
externalID, err := client.CallIDForRequest(r)
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to get call id for request"))
}
// load our connection
conn, err := models.SelectChannelConnectionByExternalID(ctx, s.DB, channel.ID(), models.ConnectionTypeIVR, externalID)
if errors.Cause(err) == sql.ErrNoRows {
return client.WriteEmptyResponse(w, "unknown connection, ignoring")
}
if err != nil {
return client.WriteErrorResponse(w, errors.Wrapf(err, "unable to load channel connection with id: %s", externalID))
}
// create a channel log for this request and connection
defer func() {
desc := "IVR event handled"
isError := false
if w.Status() != http.StatusOK {
desc = "IVR Error"
isError = true
}
path := r.URL.RequestURI()
proxyPath := r.Header.Get("X-Forwarded-Path")
if proxyPath != "" {
path = proxyPath
}
url := fmt.Sprintf("https://%s%s", r.Host, path)
_, err := models.InsertChannelLog(
ctx, s.DB, desc, isError,
r.Method, url, requestTrace, w.Status(), responseTrace.Bytes(),
start, time.Since(start),
channel, conn,
)
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error writing ivr channel log")
}
}()
err = ivr.HandleIVRStatus(
ctx, s.DB, s.RP, org, client, conn,
r, w,
)
// had an error? mark our connection as errored and log it
if err != nil {
logrus.WithError(err).WithField("http_request", r).Error("error while handling status")
return ivr.WriteErrorResponse(ctx, s.DB, client, conn, w, err)
}
return nil
}