-
Notifications
You must be signed in to change notification settings - Fork 74
/
record.go
512 lines (397 loc) · 10.9 KB
/
record.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package record
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/CyCoreSystems/ari/v5"
"github.com/CyCoreSystems/ari/v5/rid"
"github.com/rotisserie/eris"
)
var (
// RecordingStartTimeout is the amount of time to wait for a recording to start
// before declaring the recording to have failed.
RecordingStartTimeout = 1 * time.Second
// DefaultMaximumDuration is the default maximum amount of time a recording
// should be allowed to continue before being terminated.
DefaultMaximumDuration = 24 * time.Hour
// DefaultMaximumSilence is the default maximum amount of time silence may be
// detected before terminating the recording.
DefaultMaximumSilence = 5 * time.Minute
// ShutdownGracePeriod is the amount of time to allow a Stop transaction to
// complete before shutting down the session anyway.
ShutdownGracePeriod = 3 * time.Second
)
// Options describes a set of recording options for a recording Session
type Options struct {
// name is the name for the live recording
name string
format string
maxDuration time.Duration
maxSilence time.Duration
ifExists string
beep bool
terminateOn string
}
func defaultOptions() *Options {
return &Options{
beep: false,
format: "wav",
ifExists: "fail",
maxDuration: DefaultMaximumDuration,
maxSilence: DefaultMaximumSilence,
name: rid.New(rid.Recording),
terminateOn: "none",
}
}
func (o *Options) toRecordingOptions() *ari.RecordingOptions {
return &ari.RecordingOptions{
Beep: o.beep,
Format: o.format,
Exists: o.ifExists,
MaxDuration: o.maxDuration,
MaxSilence: o.maxSilence,
Terminate: o.terminateOn,
}
}
// Apply applies a set of options for the recording Session
func (o *Options) Apply(opts ...OptionFunc) {
for _, f := range opts {
f(o)
}
}
// OptionFunc is a function which applies changes to an Options set
type OptionFunc func(*Options)
// Beep indicates that a beep should be played to signal the start of recording
func Beep() OptionFunc {
return func(o *Options) {
o.beep = true
}
}
// Format configures the file format to be used to store the recording
func Format(format string) OptionFunc {
return func(o *Options) {
o.format = format
}
}
// IfExists configures the behaviour of the recording if the file to be
// recorded already exists.
//
// Valid options are: "fail" (default), "overwrite", and "append".
func IfExists(action string) OptionFunc {
return func(o *Options) {
o.ifExists = action
}
}
// MaxDuration sets the maximum duration to allow for the recording. After
// this amount of time, the recording will be automatically Finished.
//
// A setting of 0 disables the limit.
func MaxDuration(max time.Duration) OptionFunc {
return func(o *Options) {
o.maxDuration = max
}
}
// MaxSilence sets the amount of time a block of silence is allowed to become
// before the recording should be declared Finished.
//
// A setting of 0 disables silence detection.
func MaxSilence(max time.Duration) OptionFunc {
return func(o *Options) {
o.maxSilence = max
}
}
// Name configures the recording to use the provided name
func Name(name string) OptionFunc {
return func(o *Options) {
o.name = name
}
}
// TerminateOn configures the DTMF which, if received, will terminate the
// recording.
//
// Valid values are "none" (default), "any", "*", and "#".
func TerminateOn(dtmf string) OptionFunc {
return func(o *Options) {
o.terminateOn = dtmf
}
}
// Session desribes the interface to a generic recording session
type Session interface {
// Done returns a channel which is closed when the session is complete
Done() <-chan struct{}
// Err waits for the session to complete, then returns any error encountered
// during its execution
Err() error
// Key returns the ari.Key for the LiveRecording of this session, if one exists.
Key() *ari.Key
// Pause temporarily stops the recording session without ending the session
Pause() error
// Result waits for the session to complete, then returns the Result
Result() (*Result, error)
// Resume restarts a paused recording session
Resume() error
// Scrap terminates the recording session and throws away the recording.
Scrap() error
// Stop stops the recording session
Stop() *Result
}
// Result represents the result of a recording Session. It provides an
// interface to disposition the recording.
type Result struct {
h *ari.StoredRecordingHandle
// Data holds the final data for the LiveRecording, if it was successful
Data *ari.LiveRecordingData
// DTMF holds any DTMF digits which are received during the recording session
DTMF string
// Duration indicates the duration of the recording
Duration time.Duration
// Error holds any error encountered during the recording session
Error error
// Hangup indicates that the Recorder disappeared (due to hangup or
// destruction) during or after the recording.
Hangup bool
overwrite bool
}
// Delete discards the recording
func (r *Result) Delete() error {
if r.h == nil {
return eris.New("no stored recording handle available")
}
return r.h.Delete()
}
// Key returns the ari.Key of the StoredRecording, if one exists.
func (r *Result) Key() *ari.Key {
if r == nil || r.h == nil {
return nil
}
return r.h.Key()
}
// Save stores the recording to the given name
func (r *Result) Save(name string) error {
if name == "" {
// no name indicates the default, which is where it already is
return nil
}
if r.h == nil {
return eris.New("no stored recording handle available")
}
// Copy the recording to the desired name
destH, err := r.h.Copy(name)
if err != nil {
if !strings.Contains(err.Error(), "409 Conflict") || !r.overwrite {
return eris.Wrapf(err, "failed to copy recording (%s)", r.h.ID())
}
// we are set to overwrite, so delete the previous recording
Logger.Debug("overwriting previous recording")
err = destH.Delete()
if err != nil {
return eris.Wrap(err, "failed to remove previous destination recording")
}
_, err = r.h.Copy(name)
if err != nil {
return eris.Wrap(err, "failed to copy recording")
}
}
// Delete the original
err = r.h.Delete()
if err != nil {
return eris.Wrap(err, "failed to remove temporary recording after copy")
}
return nil
}
// URI returns the AudioURI to play the recording
func (r *Result) URI() string {
return "recording:" + r.h.ID()
}
// Record starts a new recording Session
func Record(ctx context.Context, r ari.Recorder, opts ...OptionFunc) Session {
s := newRecordingSession(opts...)
var wg sync.WaitGroup
wg.Add(1)
go s.record(ctx, r, &wg)
wg.Wait()
Logger.Debug("returned from internal recording start")
return s
}
// New creates a new recording Session
func newRecordingSession(opts ...OptionFunc) *recordingSession {
o := defaultOptions()
o.Apply(opts...)
s := &recordingSession{
cancel: func() {},
options: o,
doneCh: make(chan struct{}),
res: new(Result),
}
// If the recording options declare that we should overwrite,
// carry that over to the copy destination.
if o.ifExists == "overwrite" {
s.res.overwrite = true
}
return s
}
type recordingSession struct {
h *ari.LiveRecordingHandle
cancel context.CancelFunc
doneCh chan struct{}
options *Options
res *Result
}
func (s *recordingSession) Done() <-chan struct{} {
return s.doneCh
}
func (s *recordingSession) Err() error {
<-s.Done()
return s.res.Error
}
func (s *recordingSession) Key() *ari.Key {
if s == nil || s.h == nil {
return nil
}
return s.h.Key()
}
func (s *recordingSession) Result() (*Result, error) {
<-s.Done()
return s.res, s.res.Error
}
func (s *recordingSession) Pause() error {
return s.h.Pause()
}
func (s *recordingSession) Resume() error {
return s.h.Resume()
}
func (s *recordingSession) Scrap() error {
return s.h.Scrap()
}
func (s *recordingSession) Stop() *Result {
// Signal stop
s.res.Error = s.h.Stop()
// If we successfully signaled a stop, Wait for the stop to complete
if s.res.Error == nil {
select {
case <-s.Done():
case <-time.After(ShutdownGracePeriod):
}
}
// Shut down the session
if s.cancel != nil {
s.cancel()
}
// Return the result
return s.res
}
// nolint: gocyclo
func (s *recordingSession) record(ctx context.Context, r ari.Recorder, wg *sync.WaitGroup) {
defer close(s.doneCh)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
s.cancel = cancel
var err error
s.h, err = r.StageRecord(s.options.name, s.options.toRecordingOptions())
if err != nil {
s.res.Error = eris.Wrap(err, "failed to stage recording")
wg.Done()
return
}
// Store the eventual StoredRecording handle to the Result
s.res.h = s.h.Stored()
dtmfSub := r.Subscribe(ari.Events.ChannelDtmfReceived)
hangupSub := r.Subscribe(ari.Events.ChannelDestroyed, ari.Events.ChannelHangupRequest, ari.Events.BridgeDestroyed)
startSub := s.h.Subscribe(ari.Events.RecordingStarted)
failedSub := s.h.Subscribe(ari.Events.RecordingFailed)
finishedSub := s.h.Subscribe(ari.Events.RecordingFinished)
defer func() {
hangupSub.Cancel()
failedSub.Cancel()
startSub.Cancel()
finishedSub.Cancel()
dtmfSub.Cancel()
}()
wg.Done()
// Record the duration of the recording
started := time.Now()
defer func() {
s.res.Duration = time.Since(started)
Logger.Debug("recording duration", "duration", s.res.Duration)
}()
// Record any DTMF received during the recording
go s.collectDtmf(ctx, dtmfSub)
// Record hangup or destruction of our Recorder
go s.watchHangup(ctx, hangupSub)
// Start recording
Logger.Debug("starting recording")
if err := s.h.Exec(); err != nil {
s.res.Error = err
return
}
// Time the recording
startTimer := time.NewTimer(RecordingStartTimeout)
for {
select {
case <-ctx.Done():
s.Stop()
return
case <-startTimer.C:
Logger.Debug("timeout waiting to start recording")
s.res.Error = timeoutErr{"Timeout waiting for recording to start"}
return
case _, ok := <-startSub.Events():
if !ok {
return
}
Logger.Debug("recording started")
startTimer.Stop()
case e, ok := <-failedSub.Events():
if !ok {
return
}
Logger.Debug("recording failed")
r := e.(*ari.RecordingFailed).Recording
s.res.Data = &r
s.res.Error = fmt.Errorf("Recording failed: %s", r.Cause)
return
case e, ok := <-finishedSub.Events():
if !ok {
return
}
Logger.Debug("recording finished")
r := e.(*ari.RecordingFinished).Recording
s.res.Data = &r
return
}
}
}
func (s *recordingSession) collectDtmf(ctx context.Context, dtmfSub ari.Subscription) {
for {
select {
case e, ok := <-dtmfSub.Events():
if !ok {
return
}
v := e.(*ari.ChannelDtmfReceived)
s.res.DTMF += v.Digit
case <-ctx.Done():
return
}
}
}
func (s *recordingSession) watchHangup(ctx context.Context, hangupSub ari.Subscription) {
select {
case e := <-hangupSub.Events():
if e != nil {
s.res.Hangup = true
}
case <-ctx.Done():
}
}
type timeoutErr struct {
msg string
}
func (err timeoutErr) Error() string {
return err.msg
}
func (err timeoutErr) Timeout() bool {
return true
}