/
DialPlanContext.cs
415 lines (374 loc) · 16.8 KB
/
DialPlanContext.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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using log4net;
namespace SIPSorcery.AppServer.DialPlan
{
public delegate void CallCancelledDelegate(CallCancelCause cancelCause);
public delegate void CallProgressDelegate(SIPResponseStatusCodesEnum progressStatus, string reasonPhrase, string[] customHeaders, string progressContentType, string progressBody, ISIPClientUserAgent uac);
public delegate void CallFailedDelegate(SIPResponseStatusCodesEnum failureStatus, string reasonPhrase, string[] customHeaders);
public delegate void CallAnsweredDelegate(SIPResponseStatusCodesEnum answeredStatus, string reasonPhrase, string toTag, string[] customHeaders, string answeredContentType, string answeredBody, SIPDialogue answeredDialogue, SIPDialogueTransferModesEnum uasTransferMode);
public enum DialPlanAppResult
{
Unknown = 0,
Answered = 1, // The application answered the call.
NoAnswer = 2, // The application had at least one call provide a ringing response.
Failed = 3, // The application failed to get any calls to the progressing stage.
ClientCancelled = 4, // Call cancelled by client user agent.
AdminCancelled = 5, // Call cancelled by a an external administrative action or dial plan rule.
TimedOut = 6, // No response from any forward within the time limit.
Error = 7,
AlreadyAnswered = 8, // Was answered prior to the Dial command.
}
public enum DialPlanContextsEnum
{
None = 0,
Line = 1,
Script = 2,
}
public enum CallCancelCause
{
Unknown = 0,
TimedOut = 1, // The call was automatically cancelled by the Dial application after a timeout.
Administrative = 2, // Call was cancelled by an administrative action such as clicking cancel on the Call Manager UI.
ClientCancelled = 3,
NormalClearing = 4,
Error = 5,
}
public class DialPlanContext
{
private const string TRACE_FROM_ADDRESS = "admin@sipsorcery.com";
private const string TRACE_SUBJECT = "SIP Sorcery Trace";
protected static ILog logger = AppState.GetLogger("dialplan");
private SIPMonitorLogDelegate Log_External;
public DialogueBridgeCreatedDelegate CreateBridge_External;
private SIPTransport m_sipTransport;
private ISIPServerUserAgent m_sipServerUserAgent;
private SIPEndPoint m_outboundProxy; // If this app forwards calls via an outbound proxy this value will be set.
private string m_traceDirectory;
protected List<SIPProvider> m_sipProviders;
protected StringBuilder m_traceLog = new StringBuilder();
protected SIPDialPlan m_dialPlan;
public SIPDialPlan SIPDialPlan
{
get { return m_dialPlan; }
}
public bool SendTrace = true; // True means the trace should be sent, false it shouldn't.
public DialPlanContextsEnum ContextType;
public string Owner
{
get { return m_dialPlan.Owner; }
}
public string AdminMemberId
{
get { return m_dialPlan.AdminMemberId; }
}
public string TraceEmailAddress
{
get { return m_dialPlan.TraceEmailAddress; }
}
public List<SIPProvider> SIPProviders
{
get { return m_sipProviders; }
}
public string DialPlanScript
{
get { return m_dialPlan.DialPlanScript; }
}
public StringBuilder TraceLog
{
get { return m_traceLog; }
}
public string CallersNetworkId; // If the caller was a locally administered SIP account this will hold it's network id. Used so calls between two accounts on the same local network can be identified.
public Guid CustomerId; // The id of the customer that owns this dialplan.
private bool m_isAnswered;
public bool IsAnswered
{
get { return m_isAnswered; }
}
public SIPAccount SIPAccount
{
get { return m_sipServerUserAgent.SIPAccount; }
}
public CRMHeaders CallerCRMDetails = null; // Can be populated asynchronously by looking up the caller's details in a CRM system.
private List<ISIPClientUserAgent> m_uacWaitingForCallDetails = new List<ISIPClientUserAgent>(); // UACs can indicate they would like the call details when available.
private List<ISIPClientUserAgent> m_uacCallDetailsSent = new List<ISIPClientUserAgent>(); // List of UAC's that the caller details have already been sent to.
internal event CallCancelledDelegate CallCancelledByClient;
private bool m_dialPlanComplete;
public event Action DialPlanComplete;
public DialPlanContext(
SIPMonitorLogDelegate monitorLogDelegate,
SIPTransport sipTransport,
DialogueBridgeCreatedDelegate createBridge,
SIPEndPoint outboundProxy,
ISIPServerUserAgent sipServerUserAgent,
SIPDialPlan dialPlan,
List<SIPProvider> sipProviders,
string traceDirectory,
string callersNetworkId,
Guid customerId)
{
Log_External = monitorLogDelegate;
CreateBridge_External = createBridge;
m_sipTransport = sipTransport;
m_outboundProxy = outboundProxy;
m_sipServerUserAgent = sipServerUserAgent;
m_dialPlan = dialPlan;
m_sipProviders = sipProviders;
m_traceDirectory = traceDirectory;
CallersNetworkId = callersNetworkId;
CustomerId = customerId;
m_sipServerUserAgent.CallCancelled += ClientCallCancelled;
m_sipServerUserAgent.NoRingTimeout += ClientCallNoRingTimeout;
m_sipServerUserAgent.TransactionComplete += ClientTransactionRemoved;
m_sipServerUserAgent.SetTraceDelegate(TransactionTraceMessage);
}
public void CallProgress(SIPResponseStatusCodesEnum progressStatus, string reasonPhrase, string[] customHeaders, string progressContentType, string progressBody, ISIPClientUserAgent uac)
{
if (!m_isAnswered)
{
m_sipServerUserAgent.Progress(progressStatus, reasonPhrase, customHeaders, progressContentType, progressBody);
if (uac != null && uac.CallDescriptor.RequestCallerDetails && CallerCRMDetails != null)
{
if (CallerCRMDetails.Pending && !m_uacWaitingForCallDetails.Contains(uac) && !m_uacCallDetailsSent.Contains(uac))
{
m_uacWaitingForCallDetails.Add(uac);
}
else if (!CallerCRMDetails.Pending && !m_uacCallDetailsSent.Contains(uac))
{
// Send the call details to the client user agent.
uac.Update(CallerCRMDetails);
}
}
}
}
public void CallFailed(SIPResponseStatusCodesEnum failureStatus, string reasonPhrase, string[] customHeaders)
{
try
{
if (!m_isAnswered)
{
m_isAnswered = true;
if ((int)failureStatus >= 300 && (int)failureStatus <= 399)
{
SIPURI redirectURI = SIPURI.ParseSIPURIRelaxed(customHeaders[0]);
m_sipServerUserAgent.Redirect(failureStatus, redirectURI);
}
else
{
m_sipServerUserAgent.Reject(failureStatus, reasonPhrase, customHeaders);
}
}
}
catch (Exception excp)
{
logger.Error("Exception DialPlanContext CallFailed. " + excp.Message);
}
finally
{
DialPlanExecutionFinished();
}
}
public void CallAnswered(SIPResponseStatusCodesEnum answeredStatus, string reasonPhrase, string toTag, string[] customHeaders, string answeredContentType, string answeredBody, SIPDialogue answeredDialogue, SIPDialogueTransferModesEnum uasTransferMode)
{
try
{
if (!m_isAnswered)
{
m_isAnswered = true;
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Answering client call with a response status of " + (int)answeredStatus + ".", Owner));
SIPDialogue uasDialogue = m_sipServerUserAgent.Answer(answeredContentType, answeredBody, toTag, answeredDialogue, uasTransferMode);
if (!m_sipServerUserAgent.IsB2B && answeredDialogue != null)
{
if (uasDialogue != null)
{
// Duplicate switchboard dialogue settings.
uasDialogue.SwitchboardDescription = answeredDialogue.SwitchboardDescription;
uasDialogue.SwitchboardCallerDescription = answeredDialogue.SwitchboardCallerDescription;
uasDialogue.SwitchboardOwner = answeredDialogue.SwitchboardOwner;
// Record the now established call with the call manager for in dialogue management and hangups.
CreateBridge_External(uasDialogue, answeredDialogue, m_dialPlan.Owner);
}
else
{
logger.Warn("Failed to get a SIPDialogue from UAS.Answer.");
}
}
}
else
{
logger.Warn("DialPlanContext CallAnswered fired on already answered call.");
}
}
catch (Exception excp)
{
logger.Error("Exception DialPlanContext CallAnswered. " + excp.Message);
}
finally
{
DialPlanExecutionFinished();
}
}
public void DialPlanExecutionFinished()
{
if (!m_dialPlanComplete)
{
m_dialPlanComplete = true;
if (DialPlanComplete != null)
{
DialPlanComplete();
}
}
}
public void SetCallerDetails(CRMHeaders crmHeaders)
{
try
{
CallerCRMDetails = crmHeaders;
if (!CallerCRMDetails.Pending)
{
lock (m_uacWaitingForCallDetails)
{
if (m_uacWaitingForCallDetails.Count > 0)
{
foreach (var waitingUAC in m_uacWaitingForCallDetails)
{
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Sending CRM caller details to " + waitingUAC.CallDescriptor.Uri + ".", Owner));
waitingUAC.Update(crmHeaders);
m_uacCallDetailsSent.Add(waitingUAC);
}
m_uacWaitingForCallDetails.Clear();
}
}
}
}
catch (Exception excp)
{
logger.Error("Exception SetCallerDetails. " + excp.Message);
}
}
/// <summary>
/// The client transaction will time out after ringing for the maximum allowed time for an INVITE transaction (probably 10 minutes) or less
/// if the invite transaction timeout value has been adjusted.
/// </summary>
/// <param name="sipTransaction"></param>
private void ClientCallNoRingTimeout(ISIPServerUserAgent sipServerUserAgent)
{
try
{
m_isAnswered = true;
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Client call timed out, no ringing response was receved within the allowed time.", Owner));
if (CallCancelledByClient != null)
{
CallCancelledByClient(CallCancelCause.TimedOut);
}
}
catch (Exception excp)
{
logger.Error("Exception ClientCallNoRingTimeout. " + excp.Message);
}
finally
{
DialPlanExecutionFinished();
}
}
private void ClientCallCancelled(ISIPServerUserAgent uas)
{
try
{
if (!m_isAnswered)
{
m_isAnswered = true;
Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Client call cancelled halting dial plan.", Owner));
if (CallCancelledByClient != null)
{
CallCancelledByClient(CallCancelCause.ClientCancelled);
}
}
else
{
logger.Warn("DialPlanContext ClientCallCancelled fired on already answered call.");
}
}
catch (Exception excp)
{
logger.Error("Exception DialPlanContext ClientCallCancelled. " + excp.Message);
}
finally
{
DialPlanExecutionFinished();
}
}
private void ClientTransactionRemoved(ISIPServerUserAgent uas)
{
try
{
if (!TraceEmailAddress.IsNullOrBlank() && TraceLog != null && TraceLog.Length > 0 && SendTrace)
{
ThreadPool.QueueUserWorkItem(delegate { CompleteTrace(); });
}
}
catch (Exception excp)
{
logger.Error("Exception DialPlanContext ClientTransactionRemoved. " + excp.Message);
}
}
private void CompleteTrace()
{
try
{
SIPMonitorConsoleEvent traceCompleteEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dialplan trace completed at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff") + ".", Owner);
TraceLog.AppendLine(traceCompleteEvent.EventType + "=> " + traceCompleteEvent.Message);
if (!m_traceDirectory.IsNullOrBlank() && Directory.Exists(m_traceDirectory))
{
string traceFilename = m_traceDirectory + Owner + "-" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".txt";
StreamWriter traceSW = new StreamWriter(traceFilename);
traceSW.Write(TraceLog.ToString());
traceSW.Close();
}
if (TraceEmailAddress != null)
{
logger.Debug("Emailing trace to " + TraceEmailAddress + ".");
SIPSorcerySMTP.SendEmail(TraceEmailAddress, TRACE_FROM_ADDRESS, TRACE_SUBJECT, TraceLog.ToString());
}
}
catch (Exception traceExcp)
{
logger.Error("Exception DialPlanContext CompleteTrace. " + traceExcp.Message);
}
}
private void TransactionTraceMessage(SIPTransaction sipTransaction, string message)
{
FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.SIPTransaction, message, Owner));
}
private void FireProxyLogEvent(SIPMonitorEvent monitorEvent)
{
try
{
if (monitorEvent is SIPMonitorConsoleEvent)
{
SIPMonitorConsoleEvent consoleEvent = monitorEvent as SIPMonitorConsoleEvent;
if (TraceLog != null)
{
TraceLog.AppendLine(consoleEvent.EventType + "=> " + monitorEvent.Message);
}
}
if (Log_External != null)
{
Log_External(monitorEvent);
}
}
catch (Exception excp)
{
logger.Error("Exception FireProxyLogEvent DialPlanContext. " + excp.Message);
}
}
}
}