File size: 8,083 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package mocktwilio

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"net/http"
	"net/url"
	"path"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"github.com/target/goalert/notification/twilio"
	"github.com/target/goalert/validation/validate"
)

// VoiceCall represents a voice call session.
type VoiceCall struct {
	s *Server

	mx sync.Mutex

	call twilio.Call

	acceptCh chan struct{}
	rejectCh chan struct{}

	messageCh chan string
	pressCh   chan string
	hangupCh  chan struct{}
	doneCh    chan struct{}

	// start is used to track when the call was created (entered queue)
	start time.Time

	// callStart tracks when the call was accepted
	// and is used to calculate call.CallDuration when completed.
	callStart      time.Time
	url            string
	callbackURL    string
	lastMessage    string
	callbackEvents []string
	hangup         bool
}

func (vc *VoiceCall) process() {
	defer vc.s.workers.Done()
	defer close(vc.doneCh)

	if vc.s.wait(vc.s.cfg.MinQueueTime) {
		return
	}

	vc.updateStatus(twilio.CallStatusInitiated)

	if vc.s.wait(vc.s.cfg.MinQueueTime) {
		return
	}

	vc.updateStatus(twilio.CallStatusRinging)

	var err error
	vc.lastMessage, err = vc.fetchMessage("")
	if err != nil {
		vc.s.errs <- fmt.Errorf("fetch message: %w", err)
		return
	}
	select {
	case vc.s.callCh <- vc:
	case <-vc.s.shutdown:
		return
	}

waitForAccept:
	for {
		select {
		case vc.messageCh <- vc.lastMessage:
		case <-vc.acceptCh:
			break waitForAccept
		case <-vc.rejectCh:
			vc.updateStatus(twilio.CallStatusFailed)
			return
		case <-vc.s.shutdown:
			return
		}
	}

	vc.updateStatus(twilio.CallStatusInProgress)
	vc.callStart = time.Now()

	for {
		select {
		case <-vc.rejectCh:
			vc.updateStatus(twilio.CallStatusFailed)
			return
		case <-vc.s.shutdown:
			return
		case <-vc.hangupCh:
			vc.updateStatus(twilio.CallStatusCompleted)
			return
		case vc.messageCh <- vc.lastMessage:
		case digits := <-vc.pressCh:
			vc.lastMessage, err = vc.fetchMessage(digits)
			if err != nil {
				vc.s.errs <- fmt.Errorf("fetch message: %w", err)
				return
			}
			if vc.hangup {
				vc.updateStatus(twilio.CallStatusCompleted)
				return
			}
		}
	}
}

func (s *Server) serveCallStatus(w http.ResponseWriter, req *http.Request) {
	id := strings.TrimSuffix(path.Base(req.URL.Path), ".json")
	vc := s.call(id)

	if vc == nil {
		http.NotFound(w, req)
		return
	}
	err := json.NewEncoder(w).Encode(vc.cloneCall())
	if err != nil {
		panic(err)
	}
}

func (s *Server) call(id string) *VoiceCall {
	s.mx.RLock()
	defer s.mx.RUnlock()

	return s.calls[id]
}

func (s *Server) serveNewCall(w http.ResponseWriter, req *http.Request) {
	if req.Method != "POST" {
		http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
		return
	}

	vc := VoiceCall{
		acceptCh:  make(chan struct{}),
		doneCh:    make(chan struct{}),
		rejectCh:  make(chan struct{}),
		messageCh: make(chan string),
		pressCh:   make(chan string),
		hangupCh:  make(chan struct{}),
	}

	fromValue := req.FormValue("From")
	s.mx.RLock()
	_, hasCallback := s.callbacks["VOICE:"+fromValue]
	s.mx.RUnlock()
	if !hasCallback {
		apiError(400, w, &twilio.Exception{
			Message: "Wrong from number.",
		})
		return
	}

	vc.s = s
	vc.call.To = req.FormValue("To")
	vc.call.From = fromValue
	vc.call.SID = s.id("CA")
	vc.call.SequenceNumber = new(int)
	vc.callbackURL = req.FormValue("StatusCallback")

	err := validate.URL("StatusCallback", vc.callbackURL)
	if err != nil {
		apiError(400, w, &twilio.Exception{
			Code:    11100,
			Message: err.Error(),
		})
		return
	}
	vc.url = req.FormValue("Url")
	err = validate.URL("StatusCallback", vc.url)
	if err != nil {
		apiError(400, w, &twilio.Exception{
			Code:    11100,
			Message: err.Error(),
		})
		return
	}

	vc.callbackEvents = map[string][]string(req.Form)["StatusCallbackEvent"]
	vc.callbackEvents = append(vc.callbackEvents, "completed", "failed") // always send completed and failed
	vc.start = time.Now()

	vc.call.Status = twilio.CallStatusQueued

	s.mx.Lock()
	s.calls[vc.call.SID] = &vc
	s.mx.Unlock()
	s.callInCh <- &vc

	data, err := json.Marshal(vc.cloneCall())
	if err != nil {
		panic(err)
	}

	w.WriteHeader(201)
	_, err = w.Write(data)
	if err != nil {
		panic(err)
	}
}

func (vc *VoiceCall) updateStatus(stat twilio.CallStatus) {
	// move to queued
	vc.mx.Lock()
	vc.call.Status = stat

	switch stat {
	case twilio.CallStatusInProgress:
		vc.callStart = time.Now()
	case twilio.CallStatusCompleted:
		vc.call.CallDuration = time.Since(vc.callStart)
	}
	*vc.call.SequenceNumber++
	vc.mx.Unlock()

	var sendEvent bool
	evtName := string(stat)
	if evtName == "in-progres" {
		evtName = "answered"
	}
	for _, e := range vc.callbackEvents {
		if e == evtName {
			sendEvent = true
			break
		}
	}

	if !sendEvent {
		return
	}

	// attempt post to status callback
	_, err := vc.s.post(vc.callbackURL, vc.values(""))
	if err != nil {
		vc.s.errs <- errors.Wrap(err, "post to call status callback")
	}
}

func (vc *VoiceCall) values(digits string) url.Values {
	call := vc.cloneCall()

	v := make(url.Values)
	v.Set("CallSid", call.SID)
	v.Set("CallStatus", string(call.Status))
	v.Set("To", call.To)
	v.Set("From", call.From)
	v.Set("Direction", "outbound-api")
	v.Set("SequenceNumber", strconv.Itoa(*call.SequenceNumber))
	if call.Status == twilio.CallStatusCompleted {
		v.Set("CallDuration", strconv.FormatFloat(call.CallDuration.Seconds(), 'f', 1, 64))
	}

	if digits != "" {
		v.Set("Digits", digits)
	}

	return v
}

// VoiceCalls will return a channel that will be fed VoiceCalls as they arrive.
func (s *Server) VoiceCalls() chan *VoiceCall {
	return s.callCh
}

func (vc *VoiceCall) cloneCall() *twilio.Call {
	vc.mx.Lock()
	defer vc.mx.Unlock()

	call := vc.call
	return &call
}

// Accept will allow a call to move from initiated to "in-progress".
func (vc *VoiceCall) Accept() { close(vc.acceptCh) }

// Reject will reject a call, moving it to a "failed" state.
func (vc *VoiceCall) Reject() { close(vc.rejectCh); <-vc.doneCh }

// Hangup will end the call, setting it's state to "completed".
func (vc *VoiceCall) Hangup() { close(vc.hangupCh); <-vc.doneCh }

func (vc *VoiceCall) fetchMessage(digits string) (string, error) {
	data, err := vc.s.post(vc.url, vc.values(digits))
	if err != nil {
		return "", fmt.Errorf("post voice endpoint: %w", err)
	}
	type resp struct {
		XMLName xml.Name `xml:"Response"`
		Say     []string `xml:"Say>prosody"`
		Gather  struct {
			Action string   `xml:"action,attr"`
			Say    []string `xml:"Say>prosody"`
		}
		RedirectURL string    `xml:"Redirect"`
		Hangup      *struct{} `xml:"Hangup"`
	}
	var r resp
	err = xml.Unmarshal(data, &r)
	if err != nil {
		return "", fmt.Errorf("unmarshal XML voice response: %w", err)
	}

	s := append(r.Say, r.Gather.Say...)
	if r.Gather.Action != "" {
		vc.url = r.Gather.Action
	}
	if r.RedirectURL != "" {
		// Twilio's own implementation is totally broken with relative URLs, so we assume absolute (since that's all we use as a consequence)
		vc.url = r.RedirectURL
	}
	if r.Hangup != nil {
		vc.hangup = true
	}

	if r.RedirectURL != "" {
		// redirect and get new message
		return vc.fetchMessage("")
	}

	return strings.Join(s, "\n"), nil
}

// Status will return the current status of the call.
func (vc *VoiceCall) Status() twilio.CallStatus {
	return vc.cloneCall().Status
}

// PressDigits will re-query for a spoken message with the given digits.
func (vc *VoiceCall) PressDigits(digits string) { vc.pressCh <- digits }

// ID returns the unique ID of this phone call.
// It is analogous to the Twilio SID of a call.
func (vc *VoiceCall) ID() string {
	return vc.call.SID
}

// To returns the destination phone number.
func (vc *VoiceCall) To() string {
	return vc.call.To
}

// From return the source phone number.
func (vc *VoiceCall) From() string {
	return vc.call.From
}

// Body will return the last spoken message of the call.
func (vc *VoiceCall) Body() string {
	select {
	case <-vc.doneCh:
		return vc.lastMessage
	case msg := <-vc.messageCh:
		return msg
	case <-vc.s.shutdown:
		return ""
	}
}