-
Notifications
You must be signed in to change notification settings - Fork 51
/
ARIClient.cs
256 lines (209 loc) · 8.53 KB
/
ARIClient.cs
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
using System;
using System.Diagnostics;
using System.Threading;
using AsterNET.ARI.Actions;
using AsterNET.ARI.Dispatchers;
using AsterNET.ARI.Middleware;
using AsterNET.ARI.Middleware.Default;
using AsterNET.ARI.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AsterNET.ARI
{
public enum EventDispatchingStrategy
{
// Note that dispatching events on the thread pool implies that events might be processed out of order.
ThreadPool,
DedicatedThread,
AsyncTask
}
/// <summary>
/// </summary>
public class AriClient : BaseAriClient, IDisposable, IAriClient
{
public const EventDispatchingStrategy DefaultEventDispatchingStrategy = EventDispatchingStrategy.ThreadPool;
public delegate void ConnectionStateChangedHandler(object sender);
#region Events
public event ConnectionStateChangedHandler OnConnectionStateChanged;
#endregion
#region Private Fields
private readonly IActionConsumer _actionConsumer;
private readonly IEventProducer _eventProducer;
private readonly object _syncRoot = new object();
private readonly bool _subscribeAllEvents;
private readonly bool _ssl;
private bool _autoReconnect;
private TimeSpan _autoReconnectDelay;
private IAriDispatcher _dispatcher;
#endregion
#region Public Properties
public IAsteriskActions Asterisk { get; set; }
public IApplicationsActions Applications { get; set; }
public IBridgesActions Bridges { get; set; }
public IChannelsActions Channels { get; set; }
public IDeviceStatesActions DeviceStates { get; set; }
public IEndpointsActions Endpoints { get; set; }
public IEventsActions Events { get; set; }
public IMailboxesActions Mailboxes { get; set; }
public IPlaybacksActions Playbacks { get; set; }
public IRecordingsActions Recordings { get; set; }
public ISoundsActions Sounds { get; set; }
public ConnectionState ConnectionState
{
get { return _eventProducer.State; }
}
public EventDispatchingStrategy EventDispatchingStrategy { get; set; }
#endregion
#region Constructor
/// <summary>
/// </summary>
/// <param name="endPoint"></param>
/// <param name="application"></param>
/// <param name="subscribeAllEvents">Subscribe to all Asterisk events. If provided, the applications listed will be subscribed to all events, effectively disabling the application specific subscriptions.</param>
/// <param name="ssl">Enable SSL/TLS support for ARI connection</param>
public AriClient(
StasisEndpoint endPoint,
string application,
bool subscribeAllEvents = false,
bool ssl = false)
// Use Default Middleware
: this(new RestActionConsumer(endPoint), new WebSocketEventProducer(endPoint, application), application, subscribeAllEvents, ssl)
{
}
public AriClient(
IActionConsumer actionConsumer,
IEventProducer eventProducer,
string application,
bool subscribeAllEvents = false,
bool ssl = false)
{
_actionConsumer = actionConsumer;
_eventProducer = eventProducer;
EventDispatchingStrategy = DefaultEventDispatchingStrategy;
// Setup Action Properties
Asterisk = new AsteriskActions(_actionConsumer);
Applications = new ApplicationsActions(_actionConsumer);
Bridges = new BridgesActions(_actionConsumer);
Channels = new ChannelsActions(_actionConsumer);
DeviceStates = new DeviceStatesActions(_actionConsumer);
Endpoints = new EndpointsActions(_actionConsumer);
Events = new EventsActions(_actionConsumer);
Mailboxes = new MailboxesActions(_actionConsumer);
Playbacks = new PlaybacksActions(_actionConsumer);
Recordings = new RecordingsActions(_actionConsumer);
Sounds = new SoundsActions(_actionConsumer);
// Setup Event Handlers
_eventProducer.OnMessageReceived += _eventProducer_OnMessageReceived;
_eventProducer.OnConnectionStateChanged += _eventProducer_OnConnectionStateChanged;
_subscribeAllEvents = subscribeAllEvents;
_ssl = ssl;
}
public void Dispose()
{
_eventProducer.OnConnectionStateChanged -= _eventProducer_OnConnectionStateChanged;
_eventProducer.OnMessageReceived -= _eventProducer_OnMessageReceived;
Disconnect();
}
#endregion
#region Private and Protected Methods
private void _eventProducer_OnConnectionStateChanged(object sender, EventArgs e)
{
if (_eventProducer.State != ConnectionState.Open)
Reconnect();
if (OnConnectionStateChanged != null)
OnConnectionStateChanged(sender);
}
private void _eventProducer_OnMessageReceived(object sender, MessageEventArgs e)
{
#if DEBUG
Debug.WriteLine(e.Message);
#endif
// load the message
var jsonMsg = (JObject)JToken.Parse(e.Message);
var eventName = jsonMsg.SelectToken("type").Value<string>();
var type = Type.GetType("AsterNET.ARI.Models." + eventName + "Event");
var evnt =
(type != null)
? (Event)JsonConvert.DeserializeObject(e.Message, type)
: (Event)JsonConvert.DeserializeObject(e.Message, typeof(Event));
lock (_syncRoot)
{
if (_dispatcher == null)
return;
_dispatcher.QueueAction(() =>
{
try
{
FireEvent(evnt.Type, evnt, this);
}
catch(Exception ex)
{
// Handle any exceptions that were thrown by the invoked event handler
Debug.WriteLine(e.Message);
//if (!UnhandledException(this, ex))
//{
// Console.WriteLine("The event listener " + evnt.Type.ToString() + " cause an exeption: " + ex.Message);
//}
}
});
}
}
private void Reconnect()
{
TimeSpan reconnectDelay;
lock (_syncRoot)
{
var shouldReconnect = _autoReconnect
&& _eventProducer.State != ConnectionState.Open
&& _eventProducer.State != ConnectionState.Connecting;
if (!shouldReconnect)
return;
reconnectDelay = _autoReconnectDelay;
}
if (reconnectDelay != TimeSpan.Zero)
Thread.Sleep(reconnectDelay);
_eventProducer.Connect(_subscribeAllEvents, _ssl);
}
IAriDispatcher CreateDispatcher()
{
switch (EventDispatchingStrategy)
{
case EventDispatchingStrategy.DedicatedThread: return new DedicatedThreadDispatcher();
case EventDispatchingStrategy.ThreadPool: return new ThreadPoolDispatcher();
case EventDispatchingStrategy.AsyncTask: return new AsyncDispatcher();
}
throw new AriException(EventDispatchingStrategy.ToString());
}
#endregion
#region Public Methods
public bool Connected
{
get { return _eventProducer.State == ConnectionState.Open; }
}
public void Connect(bool autoReconnect = true, int autoReconnectDelay = 5)
{
lock (_syncRoot)
{
_autoReconnect = autoReconnect;
_autoReconnectDelay = TimeSpan.FromSeconds(autoReconnectDelay);
if (_dispatcher == null)
_dispatcher = CreateDispatcher();
}
_eventProducer.Connect(_subscribeAllEvents, _ssl);
}
public void Disconnect()
{
lock (_syncRoot)
{
_autoReconnect = false;
if (_dispatcher != null)
{
_dispatcher.Dispose();
_dispatcher = null;
}
}
_eventProducer.Disconnect();
}
#endregion
}
}