forked from abourget/ari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathari.go
254 lines (222 loc) · 6 KB
/
ari.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
package ari
// Package ari implements the Asterisk ARI interface. See: https://wiki.asterisk.org/wiki/display/AST/Asterisk+12+ARI
import (
"encoding/json"
"fmt"
"log"
"net/url"
"reflect"
"time"
"github.com/jmcvetta/napping"
"golang.org/x/net/websocket"
)
type Client struct {
Debug bool
ws *websocket.Conn
hostname string
username string
password string
port int
appName string
reconnections int
session *napping.Session
endpoint string
// Services
Channels *ChannelService
Bridges *BridgeService
Applications *ApplicationService
Asterisk *AsteriskService
DeviceStates *DeviceStateService
Endpoints *EndpointService
Events *EventService
Mailboxes *MailboxService
Playbacks *PlaybackService
Recordings *RecordingService
Sounds *SoundService
}
func NewClient(username, password, hostname string, port int, appName string) *Client {
userinfo := url.UserPassword(username, password)
endpoint := fmt.Sprintf("http://%s:%d", hostname, port)
c := &Client{
hostname: hostname,
port: port,
username: username,
password: password,
appName: appName,
session: &napping.Session{
Userinfo: userinfo,
},
endpoint: endpoint,
}
c.Channels = &ChannelService{client: c}
c.Bridges = &BridgeService{client: c}
c.Sounds = &SoundService{client: c}
c.Playbacks = &PlaybackService{client: c}
c.Asterisk = &AsteriskService{client: c}
c.Mailboxes = &MailboxService{client: c}
c.Recordings = &RecordingService{client: c}
c.Events = &EventService{client: c}
c.Applications = &ApplicationService{client: c}
c.DeviceStates = &DeviceStateService{client: c}
c.Endpoints = &EndpointService{client: c}
return c
}
func (c *Client) LaunchListener() <-chan Eventer {
ch := make(chan Eventer, 100)
go c.handleReceive(ch)
return ch
}
func (c *Client) handleReceive(ch chan<- Eventer) {
for {
c.reconnect(ch)
c.listenForMessages(ch)
}
}
func (c *Client) reconnect(ch chan<- Eventer) {
for {
err := c.connect()
if err == nil {
// Connected successfully
fmt.Println("Connected to websocket successfully, registered", c.appName)
ch <- &AriConnected{
Reconnections: c.reconnections,
Event: Event{Message: Message{Type: "AriConnected"}},
}
c.reconnections += 1
return
}
fmt.Println("Error connecting, trying in 3 seconds:", err)
time.Sleep(3 * time.Second)
continue
}
}
func (c *Client) connect() error {
url := fmt.Sprintf("ws://%s:%d/ari/events?api_key=%s:%s&app=%s", c.hostname, c.port, c.username, c.password, c.appName)
ws, err := websocket.Dial(url, "", "http://localhost")
c.ws = ws
return err
}
func (c *Client) listenForMessages(ch chan<- Eventer) {
for {
var msg string
err := websocket.Message.Receive(c.ws, &msg)
if err != nil {
fmt.Println("Whoops, error reading from Socket, resetting connection")
ch <- &AriDisconnected{Event: Event{Message: Message{Type: "AriDisconnected"}}}
return
}
var data Event
rawMsg := []byte(msg)
err = json.Unmarshal(rawMsg, &data)
if err != nil {
fmt.Printf("Error decoding incoming '%#v': %s", msg, err)
continue
}
//fmt.Printf(" -> %s", msg)
msgType := data.Type
var recvMsg Eventer
switch msgType {
case "ChannelVarset":
recvMsg = &ChannelVarset{}
case "ChannelDtmfReceived":
recvMsg = &ChannelDtmfReceived{}
case "ChannelHangupRequest":
recvMsg = &ChannelHangupRequest{}
case "StasisStart":
recvMsg = &StasisStart{}
case "PlaybackStarted":
recvMsg = &PlaybackStarted{}
case "PlaybackFinished":
recvMsg = &PlaybackFinished{}
case "ChannelTalkingStarted":
recvMsg = &ChannelTalkingStarted{}
case "ChannelTalkingFinished":
recvMsg = &ChannelTalkingFinished{}
case "ChannelDialplan":
recvMsg = &ChannelDialplan{}
case "ChannelCallerId":
recvMsg = &ChannelCallerId{}
case "ChannelStateChange":
recvMsg = &ChannelStateChange{}
case "ChannelEnteredBridge":
recvMsg = &ChannelEnteredBridge{}
case "ChannelLeftBridge":
recvMsg = &ChannelLeftBridge{}
case "ChannelCreated":
recvMsg = &ChannelCreated{}
case "ChannelDestroyed":
recvMsg = &ChannelDestroyed{}
case "BridgeCreated":
recvMsg = &BridgeCreated{}
case "BridgeDestroyed":
recvMsg = &BridgeDestroyed{}
case "BridgeMerged":
recvMsg = &BridgeMerged{}
case "BridgeBlindTransfer":
recvMsg = &BridgeBlindTransfer{}
case "BridgeAttendedTransfer":
recvMsg = &BridgeAttendedTransfer{}
case "StasisEnd":
recvMsg = &StasisEnd{}
default:
recvMsg = &data
}
err = json.Unmarshal(rawMsg, recvMsg)
if err != nil {
fmt.Println("Error decoding structured message: %#v", err)
continue
}
c.setClientRecurse(recvMsg)
ch <- recvMsg
}
}
func (c *Client) Log(format string, v ...interface{}) {
if c.Debug {
log.Printf(fmt.Sprintf("%s: %s\n", c.appName, format), v...)
}
}
func (c *Client) setClientRecurse(recvMsg interface{}) {
original := reflect.ValueOf(recvMsg)
doAssignClient(c, original, 0)
}
func doAssignClient(c *Client, original reflect.Value, depth int) {
// based off: https://gist.github.com/hvoecking/10772475
pkgPath := original.Type().PkgPath()
if pkgPath == "time" {
return
}
//fmt.Println("Ok, got something as a value, has PkgPath:", depth, original.Type().PkgPath(), original)
if original.CanInterface() {
iface := original.Interface()
setter, ok := iface.(clientSetter)
if ok {
setter.setClient(c)
return
}
}
switch original.Kind() {
case reflect.Ptr:
originalVal := original.Elem()
if !originalVal.IsValid() {
return
}
doAssignClient(c, originalVal, depth+1)
//case reflect.Interface:
// originalVal := original.Interface()
// doAssignClient(c, originalVal)
case reflect.Struct:
for i := 0; i < original.NumField(); i += 1 {
doAssignClient(c, original.Field(i), depth+1)
}
case reflect.Slice:
for i := 0; i < original.Len(); i += 1 {
doAssignClient(c, original.Index(i), depth+1)
}
//case reflect.Map:
// we don't have that case in our model
//default:
}
}
type clientSetter interface {
setClient(*Client)
}