github.com/CyCoreSystems/ari@v4.8.4+incompatible/_examples/record/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/inconshreveable/log15"
     7  
     8  	"github.com/CyCoreSystems/ari"
     9  	"github.com/CyCoreSystems/ari/client/native"
    10  	"github.com/CyCoreSystems/ari/ext/record"
    11  )
    12  
    13  var log = log15.New()
    14  
    15  func main() {
    16  	ctx, cancel := context.WithCancel(context.Background())
    17  	defer cancel()
    18  
    19  	native.Logger = log
    20  	record.Logger = log
    21  
    22  	// connect
    23  	log.Info("Connecting to ARI")
    24  	cl, err := native.Connect(&native.Options{
    25  		Application:  "test",
    26  		Username:     "admin",
    27  		Password:     "admin",
    28  		URL:          "http://localhost:8088/ari",
    29  		WebsocketURL: "ws://localhost:8088/ari/events",
    30  	})
    31  	if err != nil {
    32  		log.Error("Failed to build ARI client", "error", err)
    33  		return
    34  	}
    35  
    36  	// setup app
    37  
    38  	log.Info("Listening for new calls")
    39  	sub := cl.Bus().Subscribe(nil, "StasisStart")
    40  
    41  	for {
    42  		select {
    43  		case e := <-sub.Events():
    44  			v := e.(*ari.StasisStart)
    45  			log.Info("Got stasis start", "channel", v.Channel.ID)
    46  			go app(ctx, cl.Channel().Get(v.Key(ari.ChannelKey, v.Channel.ID)))
    47  		case <-ctx.Done():
    48  			return
    49  		}
    50  	}
    51  }
    52  
    53  func app(ctx context.Context, h *ari.ChannelHandle) {
    54  	defer h.Hangup()
    55  
    56  	ctx, cancel := context.WithCancel(ctx)
    57  	defer cancel()
    58  
    59  	log.Info("Running app", "channel", h.ID())
    60  
    61  	end := h.Subscribe(ari.Events.StasisEnd)
    62  	defer end.Cancel()
    63  
    64  	// End the app when the channel goes away
    65  	go func() {
    66  		<-end.Events()
    67  		cancel()
    68  	}()
    69  
    70  	if err := h.Answer(); err != nil {
    71  		log.Error("failed to answer call", "error", err)
    72  		return
    73  	}
    74  
    75  	res, err := record.Record(ctx, h,
    76  		record.TerminateOn("any"),
    77  		record.IfExists("overwrite"),
    78  	).Result()
    79  	if err != nil {
    80  		log.Error("failed to record", "error", err)
    81  		return
    82  	}
    83  
    84  	if err = res.Save("test-recording"); err != nil {
    85  		log.Error("failed to save recording", "error", err)
    86  	}
    87  
    88  	log.Info("completed recording")
    89  
    90  	h.Hangup()
    91  	return
    92  }