-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathTwilioController.cs
More file actions
1253 lines (1075 loc) · 51.2 KB
/
Copy pathTwilioController.cs
File metadata and controls
1253 lines (1075 loc) · 51.2 KB
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Resgrid.Framework;
using Resgrid.Model;
using Resgrid.Model.Helpers;
using Resgrid.Model.Providers;
using Resgrid.Model.Queue;
using Resgrid.Model.Services;
using Resgrid.Web.Services.Models;
using Resgrid.Web.Services.Twilio;
using Twilio.AspNet.Common;
using Twilio.AspNet.Core;
using Twilio.TwiML;
using Twilio.TwiML.Voice;
namespace Resgrid.Web.Services.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Produces("application/xml")]
[ApiExplorerSettings(IgnoreApi = true)]
public class TwilioController : ControllerBase
{
#region Private Readonly Properties and Constructors
private readonly IDepartmentSettingsService _departmentSettingsService;
private readonly INumbersService _numbersService;
private readonly ILimitsService _limitsService;
private readonly ICallsService _callsService;
private readonly IQueueService _queueService;
private readonly IDepartmentsService _departmentsService;
private readonly IUserProfileService _userProfileService;
private readonly ITextCommandService _textCommandService;
private readonly IActionLogsService _actionLogsService;
private readonly IUserStateService _userStateService;
private readonly ICommunicationService _communicationService;
private readonly IGeoLocationProvider _geoLocationProvider;
private readonly IDepartmentGroupsService _departmentGroupsService;
private readonly ICustomStateService _customStateService;
private readonly IUnitsService _unitsService;
private readonly IUsersService _usersService;
private readonly ICalendarService _calendarService;
private readonly ICommunicationTestService _communicationTestService;
private readonly IEncryptionService _encryptionService;
private readonly ITwilioVoiceResponseService _twilioVoiceResponseService;
public TwilioController(IDepartmentSettingsService departmentSettingsService, INumbersService numbersService,
ILimitsService limitsService, ICallsService callsService, IQueueService queueService, IDepartmentsService departmentsService,
IUserProfileService userProfileService, ITextCommandService textCommandService, IActionLogsService actionLogsService,
IUserStateService userStateService, ICommunicationService communicationService, IGeoLocationProvider geoLocationProvider,
IDepartmentGroupsService departmentGroupsService, ICustomStateService customStateService, IUnitsService unitsService,
IUsersService usersService, ICalendarService calendarService, ICommunicationTestService communicationTestService,
IEncryptionService encryptionService, ITwilioVoiceResponseService twilioVoiceResponseService)
{
_departmentSettingsService = departmentSettingsService;
_numbersService = numbersService;
_limitsService = limitsService;
_callsService = callsService;
_queueService = queueService;
_departmentsService = departmentsService;
_userProfileService = userProfileService;
_textCommandService = textCommandService;
_actionLogsService = actionLogsService;
_userStateService = userStateService;
_communicationService = communicationService;
_geoLocationProvider = geoLocationProvider;
_departmentGroupsService = departmentGroupsService;
_customStateService = customStateService;
_unitsService = unitsService;
_usersService = usersService;
_calendarService = calendarService;
_communicationTestService = communicationTestService;
_encryptionService = encryptionService;
_twilioVoiceResponseService = twilioVoiceResponseService;
}
#endregion Private Readonly Properties and Constructors
private const int MAX_DISPATCH_RETRY = 3;
[HttpGet("IncomingMessage")]
[Produces("application/xml")]
public async Task<ActionResult> IncomingMessage([FromQuery] TwilioMessage request)
{
if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body))
return BadRequest();
var response = new MessagingResponse();
var textMessage = new TextMessage();
textMessage.To = request.To.Replace("+", "");
textMessage.Msisdn = request.From.Replace("+", "");
textMessage.MessageId = request.MessageSid;
textMessage.Timestamp = DateTime.UtcNow.ToLongDateString();
textMessage.Data = request.Body;
textMessage.Text = request.Body;
var messageEvent = new InboundMessageEvent();
messageEvent.MessageType = (int)InboundMessageTypes.TextMessage;
messageEvent.RecievedOn = DateTime.UtcNow;
messageEvent.Type = typeof(InboundMessageEvent).FullName;
messageEvent.Data = JsonConvert.SerializeObject(textMessage);
messageEvent.Processed = false;
messageEvent.CustomerId = "";
// Check for Communication Test response (CT- prefix)
if (!string.IsNullOrWhiteSpace(textMessage.Text) && textMessage.Text.Trim().StartsWith("CT-", StringComparison.OrdinalIgnoreCase))
{
var runCode = textMessage.Text.Trim().Split(' ')[0].ToUpperInvariant();
await _communicationTestService.RecordSmsResponseAsync(runCode, textMessage.Msisdn);
messageEvent.Processed = true;
response.Message("Resgrid received your communication test response. Thank you.");
await _numbersService.SaveInboundMessageEventAsync(messageEvent);
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
try
{
UserProfile userProfile = null;
var departmentId = await _departmentSettingsService.GetDepartmentIdByTextToCallNumberAsync(textMessage.To);
if (!departmentId.HasValue)
{
userProfile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn);
if (userProfile != null)
{
var department = await _departmentsService.GetDepartmentByUserIdAsync(userProfile.UserId);
if (department != null)
departmentId = department.DepartmentId;
}
}
if (departmentId.HasValue)
{
// Run all department-level lookups in parallel — they are independent of each other.
var departmentTask = _departmentsService.GetDepartmentByIdAsync(departmentId.Value);
var dispatchNumbersTask = _departmentSettingsService.GetTextToCallSourceNumbersForDepartmentAsync(departmentId.Value);
var authorizedTask = _limitsService.CanDepartmentProvisionNumberAsync(departmentId.Value);
var customStatesTask = _customStateService.GetAllActiveCustomStatesForDepartmentAsync(departmentId.Value);
await System.Threading.Tasks.Task.WhenAll(departmentTask, dispatchNumbersTask, authorizedTask, customStatesTask);
var department = departmentTask.Result;
var dispatchNumbers = dispatchNumbersTask.Result;
var authroized = authorizedTask.Result;
var customStates = customStatesTask.Result;
messageEvent.CustomerId = departmentId.Value.ToString();
if (authroized)
{
bool isDispatchSource = false;
if (!String.IsNullOrWhiteSpace(dispatchNumbers))
isDispatchSource = _numbersService.DoesNumberMatchAnyPattern(dispatchNumbers.Split(Char.Parse(",")).ToList(), textMessage.Msisdn);
if (isDispatchSource)
{
var c = new Call();
c.Notes = textMessage.Text;
c.NatureOfCall = textMessage.Text;
c.LoggedOn = DateTime.UtcNow;
c.Name = string.Format("TTC {0}", c.LoggedOn.TimeConverter(department).ToString("g"));
c.Priority = (int)CallPriority.High;
c.ReportingUserId = department.ManagingUserId;
c.Dispatches = new Collection<CallDispatch>();
c.CallSource = (int)CallSources.EmailImport;
c.SourceIdentifier = textMessage.MessageId;
c.DepartmentId = departmentId.Value;
var users = await _departmentsService.GetAllUsersForDepartmentAsync(departmentId.Value, true);
foreach (var u in users)
{
var cd = new CallDispatch();
cd.UserId = u.UserId;
c.Dispatches.Add(cd);
}
var savedCall = await _callsService.SaveCallAsync(c);
var cqi = new CallQueueItem();
cqi.Call = savedCall;
cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(users.Select(x => x.UserId).ToList());
cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);
await _queueService.EnqueueCallBroadcastAsync(cqi);
messageEvent.Processed = true;
}
if (!isDispatchSource)
{
// Reuse the profile fetched above when the department was resolved via mobile number;
// only hit the DB again if the department came from the phone-number lookup path.
var profile = userProfile ?? await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn);
if (profile != null)
{
var payload = _textCommandService.DetermineType(textMessage.Text);
var customActions = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Personnel);
var customStaffing = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Staffing);
switch (payload.Type)
{
case TextCommandTypes.None:
response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
break;
case TextCommandTypes.Help:
messageEvent.Processed = true;
var help = new StringBuilder();
help.Append("Resgrid Text Commands" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("These are the commands you can text to alter your status and staffing. Text help for help." + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("Core Commands" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("STOP: To turn off all text messages" + Environment.NewLine);
help.Append("HELP: This help text" + Environment.NewLine);
help.Append("CALLS: List active calls" + Environment.NewLine);
help.Append("C[CallId]: Get Call Detail i.e. C1445" + Environment.NewLine);
help.Append("UNITS: List unit statuses" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("Status or Action Commands" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any())
{
var activeDetails = customActions.GetActiveDetails();
for (int i = 0; i < activeDetails.Count; i++)
{
help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or {i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
}
}
else
{
help.Append("responding or 1: Responding" + Environment.NewLine);
help.Append("notresponding or 2: Not Responding" + Environment.NewLine);
help.Append("onscene or 3: On Scene" + Environment.NewLine);
help.Append("available or 4: Available" + Environment.NewLine);
}
help.Append("---------------------" + Environment.NewLine);
help.Append("Staffing Commands" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any())
{
var activeDetails = customStaffing.GetActiveDetails();
for (int i = 0; i < activeDetails.Count; i++)
{
help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or S{i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
}
}
else
{
help.Append("available or s1: Available Staffing" + Environment.NewLine);
help.Append("delayed or s2: Delayed Staffing" + Environment.NewLine);
help.Append("unavailable or s3: Unavailable Staffing" + Environment.NewLine);
help.Append("committed or s4: Committed Staffing" + Environment.NewLine);
help.Append("onshift or s4: On Shift Staffing" + Environment.NewLine);
}
response.Message(help.ToString());
//_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Help", help.ToString(), department.DepartmentId, textMessage.To, profile);
break;
case TextCommandTypes.Action:
messageEvent.Processed = true;
await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, (int)payload.GetActionType());
response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", payload.GetActionType()));
//_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Status", string.Format("Resgrid recieved your text command. Status changed to: {0}", payload.GetActionType()), department.DepartmentId, textMessage.To, profile);
break;
case TextCommandTypes.Staffing:
messageEvent.Processed = true;
await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType());
response.Message(string.Format("Resgrid received your text command. Staffing level changed to: {0}", payload.GetStaffingType()));
//_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Staffing", string.Format("Resgrid recieved your text command. Staffing level changed to: {0}", payload.GetStaffingType()), department.DepartmentId, textMessage.To, profile);
break;
case TextCommandTypes.Stop:
messageEvent.Processed = true;
await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId);
response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
break;
case TextCommandTypes.CustomAction:
messageEvent.Processed = true;
await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, payload.GetCustomActionType());
if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any() &&
customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType()) != null)
{
var detail = customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType());
response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", detail.ButtonText));
}
else
{
response.Message("Resgrid received your text command and updated your status");
}
break;
case TextCommandTypes.CustomStaffing:
messageEvent.Processed = true;
await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, payload.GetCustomStaffingType());
if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any() &&
customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType()) != null)
{
var detail = customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType());
response.Message(string.Format("Resgrid received your text command. Staffing changed to: {0}", detail.ButtonText));
}
else
{
response.Message("Resgrid received your text command and updated your staffing");
}
break;
case TextCommandTypes.MyStatus:
messageEvent.Processed = true;
var userStatus = await _actionLogsService.GetLastActionLogForUserAsync(profile.UserId);
var userStaffing = await _userStateService.GetLastUserStateByUserIdAsync(profile.UserId);
var customStatusLevel = await _customStateService.GetCustomPersonnelStatusAsync(department.DepartmentId, userStatus);
var customStaffingLevel = await _customStateService.GetCustomPersonnelStaffingAsync(department.DepartmentId, userStaffing);
response.Message(
$"Hello {profile.FullName.AsFirstNameLastName} at {DateTime.UtcNow.TimeConverterToString(department)} your current status is {customStatusLevel.ButtonText} and your current staffing is {customStaffingLevel.ButtonText}.");
break;
case TextCommandTypes.Calls:
messageEvent.Processed = true;
var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(department.DepartmentId);
var activeCallText = new StringBuilder();
activeCallText.Append($"Active Calls for {department.Name}" + Environment.NewLine);
activeCallText.Append("---------------------" + Environment.NewLine);
foreach (var activeCall in activeCalls)
{
activeCallText.Append($"CallId: {activeCall.CallId} Name: {activeCall.Name} Nature:{StringHelpers.StripHtmlTagsCharArray(activeCall.NatureOfCall)}" + Environment.NewLine);
}
response.Message(activeCallText.ToString().Truncate(1200));
break;
case TextCommandTypes.Units:
messageEvent.Processed = true;
var unitStatus = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(department.DepartmentId);
var unitStatusesText = new StringBuilder();
unitStatusesText.Append($"Unit Statuses for {department.Name}" + Environment.NewLine);
unitStatusesText.Append("---------------------" + Environment.NewLine);
foreach (var unit in unitStatus)
{
var unitState = await _customStateService.GetCustomUnitStateAsync(unit);
unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine);
}
response.Message(unitStatusesText.ToString().Truncate(1200));
break;
case TextCommandTypes.CallDetail:
messageEvent.Processed = true;
var call = await _callsService.GetCallByIdAsync(int.Parse(payload.Data));
var callText = new StringBuilder();
callText.Append($"Call Information for {call.Name}" + Environment.NewLine);
callText.Append("---------------------" + Environment.NewLine);
callText.Append($"Id: {call.CallId}" + Environment.NewLine);
callText.Append($"Number: {call.Number}" + Environment.NewLine);
callText.Append($"Logged: {call.LoggedOn.TimeConverterToString(department)}" + Environment.NewLine);
callText.Append("-----Nature-----" + Environment.NewLine);
callText.Append(call.NatureOfCall + Environment.NewLine);
callText.Append("-----Address-----" + Environment.NewLine);
if (!String.IsNullOrWhiteSpace(call.Address))
callText.Append(call.Address + Environment.NewLine);
else if (!string.IsNullOrEmpty(call.GeoLocationData) && call.GeoLocationData.Length > 1)
{
try
{
string[] points = call.GeoLocationData.Split(char.Parse(","));
if (points != null && points.Length == 2)
{
callText.Append(_geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1])) + Environment.NewLine);
}
}
catch
{
}
}
response.Message(callText.ToString());
break;
}
}
}
}
}
else if (textMessage.To == Config.NumberProviderConfig.TwilioResgridNumber) // Resgrid master text number
{
var profile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn);
var payload = _textCommandService.DetermineType(textMessage.Text);
switch (payload.Type)
{
case TextCommandTypes.None:
response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
break;
case TextCommandTypes.Help:
messageEvent.Processed = true;
var help = new StringBuilder();
help.Append("Resgrid Text Commands" + Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("This is the Resgrid system for first responders (https://resgrid.com) automated text system. Your department isn't signed up for inbound text messages, but you can send the following commands." +
Environment.NewLine);
help.Append("---------------------" + Environment.NewLine);
help.Append("STOP: To turn off all text messages" + Environment.NewLine);
help.Append("HELP: This help text" + Environment.NewLine);
response.Message(help.ToString());
break;
case TextCommandTypes.Stop:
messageEvent.Processed = true;
await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId);
response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
break;
}
}
}
catch (Exception ex)
{
Framework.Logging.LogException(ex);
}
finally
{
await _numbersService.SaveInboundMessageEventAsync(messageEvent);
}
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[HttpGet("VoiceCall")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> VoiceCall(string userId, int callId, [FromQuery] string retry = null)
{
var response = new VoiceResponse();
var call = await _callsService.GetCallByIdAsync(callId);
call = await _callsService.PopulateCallData(call, true, true, false, false, false, false, false, false, false);
if (call == null)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosed);
response.Hangup();
return CreateVoiceContentResult(response);
}
if (call.State == (int)CallStates.Cancelled || call.State == (int)CallStates.Closed || call.IsDeleted)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosedByNumber(call.Number), call.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
// For outbound calls, allow a brief pause for the audio bridge to
// stabilize after the callee answers before attempting playback.
response.Pause(length: 1);
// For dispatch playback, attempt to fetch (or pre-warm) the TTS URL
// within a short timeout so that the TwiML response is returned before
// Twilio's 15-second webhook timeout expires. If the dispatch text is
// not yet cached, we play a brief "please wait" prompt and redirect
// back to this endpoint, giving the TTS service time to complete
// generation in the background.
var dispatchReady = await TryAppendDispatchPlaybackAsync(response, call);
if (!dispatchReady)
{
// Parse and increment the retry counter from the incoming request.
if (!int.TryParse(retry, out var retryCount))
retryCount = 0;
if (retryCount >= MAX_DISPATCH_RETRY)
{
// Exceeded retry cap — fall back to a static error prompt.
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosed);
response.Hangup();
return CreateVoiceContentResult(response);
}
// Dispatch audio isn't ready yet. Pre-warm it in the background
// and redirect back — by the time Twilio re-fetches this endpoint
// the audio should be cached.
var address = await ResolveCallAddressAsync(call);
var dispatchText = BuildDispatchPrompt(call, address);
var ttsLanguage = await GetDepartmentTtsLanguageAsync(call.DepartmentId);
// Fire off TTS generation in the background. The TTS microservice
// caches the result, so the redirect will find it once ready.
_twilioVoiceResponseService.PreWarmPromptAsync(dispatchText, ttsLanguage)
.ContinueWith(t =>
{
if (t.IsFaulted && t.Exception != null)
Logging.LogException(t.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.PleaseWaitForDispatch);
var nextRetry = retryCount + 1;
response.Redirect(
new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCall?userId={userId}&callId={callId}&retry={nextRetry}"),
"GET");
return CreateVoiceContentResult(response);
}
// Dispatch is ready (fast path or retry with cached audio).
var gather = new Gather(numDigits: 1, action: new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCallAction?userId={userId}&callId={callId}"), method: "GET")
{
BargeIn = true
};
await AppendVoicePromptAsync(gather, TwilioVoicePromptCatalog.OutboundDispatchMenu, call.DepartmentId);
response.Append(gather);
response.Hangup();
return CreateVoiceContentResult(response);
}
[HttpGet("VoiceCallAction")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> VoiceCallAction(string userId, int callId, [FromQuery] VoiceRequest twilioRequest)
{
var response = new VoiceResponse();
if (twilioRequest?.Digits == "1")
{
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCall?userId={userId}&callId={callId}"), "GET");
return CreateVoiceContentResult(response);
}
if (twilioRequest?.Digits == "2")
{
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCallResponseOptions?userId={userId}&callId={callId}"), "GET");
return CreateVoiceContentResult(response);
}
if (!string.IsNullOrWhiteSpace(twilioRequest?.Digits))
{
var call = await _callsService.GetCallByIdAsync(callId);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.InvalidSelection, call?.DepartmentId);
}
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCall?userId={userId}&callId={callId}"), "GET");
return CreateVoiceContentResult(response);
}
[HttpGet("VoiceCallResponseOptions")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> VoiceCallResponseOptions(string userId, int callId)
{
var response = new VoiceResponse();
var call = await _callsService.GetCallByIdAsync(callId);
if (call == null)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosed);
response.Hangup();
return CreateVoiceContentResult(response);
}
if (call.State == (int)CallStates.Cancelled || call.State == (int)CallStates.Closed || call.IsDeleted)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosedByNumber(call.Number), call.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(call.DepartmentId);
for (int repeat = 0; repeat < 2; repeat++)
{
var gatherResponse = new Gather(action: new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCallRespond?userId={userId}&callId={callId}"), method: "GET", finishOnKey: "#")
{
BargeIn = true
};
await AppendVoicePromptsAsync(gatherResponse, BuildVoiceCallResponseOptionPrompts(stations), call.DepartmentId);
response.Append(gatherResponse);
}
response.Hangup();
return CreateVoiceContentResult(response);
}
[HttpGet("VoiceCallRespond")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> VoiceCallRespond(string userId, int callId, [FromQuery] VoiceRequest twilioRequest)
{
var response = new VoiceResponse();
var call = await _callsService.GetCallByIdAsync(callId);
if (call == null)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosed);
response.Hangup();
return CreateVoiceContentResult(response);
}
if (call.State == (int)CallStates.Cancelled || call.State == (int)CallStates.Closed || call.IsDeleted)
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.CallClosedByNumber(call.Number), call.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
if (twilioRequest?.Digits == "0")
{
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCall?userId={userId}&callId={callId}"), "GET");
return CreateVoiceContentResult(response);
}
if (twilioRequest?.Digits == "1")
{
await _actionLogsService.SetUserActionAsync(userId, call.DepartmentId, (int)ActionTypes.RespondingToScene, null, call.CallId);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.RespondingToScene, call.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
if (int.TryParse(twilioRequest?.Digits, out var digit))
{
var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(call.DepartmentId);
var index = digit - 2;
if (index >= 0 && index < stations.Count)
{
var station = stations[index];
if (station != null)
{
await _actionLogsService.SetUserActionAsync(userId, call.DepartmentId, (int)ActionTypes.RespondingToStation, null, station.DepartmentGroupId);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.RespondingToStation(station.Name), call.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
}
}
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.InvalidSelection, call.DepartmentId);
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/VoiceCallResponseOptions?userId={userId}&callId={callId}"), "GET");
return CreateVoiceContentResult(response);
}
[HttpGet("VoiceVerification")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> VoiceVerification(string userId, int contactType)
{
if (string.IsNullOrWhiteSpace(userId))
return await GetVoiceVerificationErrorResult();
var profile = await _userProfileService.GetProfileByUserIdAsync(userId, bypassCache: true);
if (profile == null)
return await GetVoiceVerificationErrorResult();
string encryptedCode;
DateTime? expiry;
bool alreadyConsumed;
switch ((ContactVerificationType)contactType)
{
case ContactVerificationType.MobileNumber:
encryptedCode = profile.MobileVerificationCode;
expiry = profile.MobileVerificationCodeExpiry;
alreadyConsumed = profile.MobileVerificationVoiceCodeConsumed;
break;
case ContactVerificationType.HomeNumber:
encryptedCode = profile.HomeVerificationCode;
expiry = profile.HomeVerificationCodeExpiry;
alreadyConsumed = profile.HomeVerificationVoiceCodeConsumed;
break;
default:
return await GetVoiceVerificationErrorResult();
}
if (alreadyConsumed || string.IsNullOrWhiteSpace(encryptedCode) || !expiry.HasValue || DateTime.UtcNow > expiry.Value)
return await GetVoiceVerificationErrorResult();
string code;
try
{
code = _encryptionService.Decrypt(encryptedCode);
}
catch (CryptographicException ex)
{
Framework.Logging.LogException(ex);
return await GetVoiceVerificationErrorResult();
}
if (string.IsNullOrWhiteSpace(code))
return await GetVoiceVerificationErrorResult();
var department = await _departmentsService.GetDepartmentByUserIdAsync(profile.UserId, false);
if (department == null)
return await GetVoiceVerificationErrorResult();
switch ((ContactVerificationType)contactType)
{
case ContactVerificationType.MobileNumber:
profile.MobileVerificationVoiceCodeConsumed = true;
break;
case ContactVerificationType.HomeNumber:
profile.HomeVerificationVoiceCodeConsumed = true;
break;
}
await _userProfileService.SaveProfileAsync(department.DepartmentId, profile);
var response = new VoiceResponse();
var spokenCode = string.Join(", ", code.ToCharArray());
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.VerificationGreeting, department.DepartmentId);
for (int i = 0; i < 3; i++)
{
response.Pause(length: 1);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.VerificationCode(spokenCode), department.DepartmentId);
}
response.Pause(length: 1);
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.VerificationClosing, department.DepartmentId);
response.Hangup();
return CreateVoiceContentResult(response);
}
[HttpGet("InboundVoice")]
[Produces("application/xml")]
[ValidateRequest]
public async Task<ActionResult> InboundVoice([FromQuery] TwilioGatherRequest request)
{
if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From))
return BadRequest();
var response = new VoiceResponse();
UserProfile profile = null;
profile = await _userProfileService.GetProfileByMobileNumberAsync(request.From.Replace("+", ""));
if (profile == null)
profile = await _userProfileService.GetProfileByHomeNumberAsync(request.From.Replace("+", ""));
if (profile != null)
{
var department = await _departmentsService.GetDepartmentByUserIdAsync(profile.UserId, false);
if (department != null)
{
var authroized = await _limitsService.CanDepartmentProvisionNumberAsync(department.DepartmentId);
request.From.Replace("+", "");
if (authroized)
{
for (int repeat = 0; repeat < 2; repeat++)
{
var gatherResponse = new Gather(numDigits: 1, action: new Uri(string.Format("{0}/api/Twilio/InboundVoiceAction?userId={1}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, profile.UserId)), method: "GET")
{
BargeIn = true
};
await AppendVoicePromptsAsync(gatherResponse, BuildMainMenuPrompts(profile.FirstName, department.Name), department.DepartmentId);
response.Append(gatherResponse);
}
response.Hangup();
return CreateVoiceContentResult(response);
}
else
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.InboundVoiceUnavailable, department.DepartmentId);
response.Hangup();
}
}
else
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.InboundVoiceUnavailable);
response.Hangup();
}
}
else
{
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.InboundVoiceUnavailable);
response.Hangup();
}
return CreateVoiceContentResult(response);
}
private async Task<ContentResult> GetVoiceVerificationErrorResult()
{
var response = new VoiceResponse();
await AppendVoicePromptAsync(response, TwilioVoicePromptCatalog.VoiceVerificationFailure);
response.Hangup();
return CreateVoiceContentResult(response);
}
[HttpGet("InboundVoiceAction")]
[Produces("application/xml")]
public async Task<ActionResult> InboundVoiceAction(string userId, [FromQuery] VoiceRequest twilioRequest)
{
var response = new VoiceResponse();
var department = await _departmentsService.GetDepartmentByUserIdAsync(userId);
var profile = await _userProfileService.GetProfileByUserIdAsync(userId);
var prompts = new List<string>();
Uri gatherAction = new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}");
string gatherFinishOnKey = null;
int? gatherNumDigits = 1;
string goBackPrompt = TwilioVoicePromptCatalog.GoBackToMainMenu;
if (twilioRequest.Digits == "0")
{
prompts.AddRange(BuildMainMenuPrompts(profile.FirstName, department.Name));
}
else if (twilioRequest.Digits == "1")
{
var calls = await _callsService.GetActiveCallsByDepartmentAsync(department.DepartmentId);
if (calls != null && calls.Any())
{
prompts.Add($"There are {calls.Count()} active calls for department {department.Name}.");
foreach (var call in calls)
{
prompts.Add($"{call.Name}, Priority {call.GetPriorityText()} Address {call.Address} Nature {StringHelpers.StripHtmlTagsCharArray(call.NatureOfCall)}.");
}
}
else
{
prompts.Add($"There are no active calls for department {department.Name}.");
}
}
else if (twilioRequest.Digits == "2")
{
var allUsers = await _usersService.GetUserGroupAndRolesByDepartmentIdInLimitAsync(department.DepartmentId, false, false, false);
var lastUserActionlogs = await _actionLogsService.GetLastActionLogsForDepartmentAsync(department.DepartmentId);
var userStates = await _userStateService.GetLatestStatesForDepartmentAsync(department.DepartmentId);
if (allUsers != null && allUsers.Any())
{
foreach (var user in allUsers)
{
var lastActionLog = lastUserActionlogs.FirstOrDefault(x => x.UserId == user.UserId);
var userState = userStates.FirstOrDefault(x => x.UserId == user.UserId);
var staffingLevel = await _customStateService.GetCustomPersonnelStaffingAsync(department.DepartmentId, userState);
var status = await _customStateService.GetCustomPersonnelStatusAsync(department.DepartmentId, lastActionLog);
prompts.Add($"{user.LastName}, {user.FirstName}, Status {status.ButtonText} Staffing Level {staffingLevel.ButtonText}.");
}
}
}
else if (twilioRequest.Digits == "3")
{
var units = await _unitsService.GetUnitsForDepartmentUnlimitedAsync(department.DepartmentId);
var states = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(department.DepartmentId);
var unitStatuses = await _customStateService.GetAllActiveUnitStatesForDepartmentAsync(department.DepartmentId);
if (units != null && units.Any())
{
foreach (var unit in units)
{
var unitState = states.FirstOrDefault(x => x.UnitId == unit.UnitId);
var unitStatus = await _customStateService.GetCustomUnitStateAsync(unitState);
prompts.Add($"{unit.Name}, Status {unitStatus.ButtonText}.");
}
}
else
{
prompts.Add($"There are no units for department {department.Name}.");
}
}
else if (twilioRequest.Digits == "4")
{
var upcomingItems = await _calendarService.GetUpcomingCalendarItemsAsync(department.DepartmentId, DateTime.UtcNow);
if (upcomingItems != null && upcomingItems.Any())
{
foreach (var item in upcomingItems)
{
prompts.Add($"{item.Title}, {item.Start.TimeConverter(department).ToShortDateString()}, {item.Start.TimeConverter(department).ToShortTimeString()}, {item.Location}");
}
}
else
{
prompts.Add($"There are no upcoming Calendar events for department {department.Name}.");
}
}
else if (twilioRequest.Digits == "5")
{
prompts.Add($"There are no upcoming shifts for department {department.Name}.");
}
else if (twilioRequest.Digits == "6") // Set current status
{
var options = await _customStateService.GetCustomPersonnelStatusesOrDefaultsAsync(department.DepartmentId);
int index = 1;
prompts.Add(TwilioVoicePromptCatalog.StatusSelectionIntro);
foreach (var option in options)
{
if (option.CustomStateDetailId == 0 || option.IsDeleted)
continue;
prompts.Add(TwilioVoicePromptCatalog.StatusOption(index, option.ButtonText));
index++;
}
gatherAction = new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceActionStatus?userId={userId}");
gatherFinishOnKey = "#";
gatherNumDigits = null;
goBackPrompt = TwilioVoicePromptCatalog.GoBackToMainMenuWithPound;
}
else if (twilioRequest.Digits == "7") // Set current staffing
{
var options = await _customStateService.GetCustomPersonnelStaffingsOrDefaultsAsync(department.DepartmentId);
int index = 1;
prompts.Add(TwilioVoicePromptCatalog.StaffingSelectionIntro);
foreach (var option in options)
{
if (option.CustomStateDetailId == 0 || option.IsDeleted)
continue;
prompts.Add(TwilioVoicePromptCatalog.StaffingOption(index, option.ButtonText));
index++;
}
gatherAction = new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceActionStaffing?userId={userId}");
gatherFinishOnKey = "#";
gatherNumDigits = null;
goBackPrompt = TwilioVoicePromptCatalog.GoBackToMainMenuWithPound;
}
for (int repeat = 0; repeat < 2; repeat++)
{
var gather = new Gather(action: gatherAction, method: "GET", finishOnKey: gatherFinishOnKey, numDigits: gatherNumDigits)
{
BargeIn = true
};
await AppendVoicePromptsAsync(gather, prompts, department.DepartmentId);
await AppendVoicePromptAsync(gather, goBackPrompt, department.DepartmentId);
response.Append(gather);
}
response.Hangup();
return CreateVoiceContentResult(response);
}
[HttpGet("InboundVoiceActionStatus")]
[Produces("application/xml")]
public async Task<ActionResult> InboundVoiceActionStatus(string userId, [FromQuery] VoiceRequest twilioRequest)
{
var response = new VoiceResponse();
var department = await _departmentsService.GetDepartmentByUserIdAsync(userId);
var profile = await _userProfileService.GetProfileByUserIdAsync(userId);
var options = await _customStateService.GetCustomPersonnelStatusesOrDefaultsAsync(department.DepartmentId);
var activeOptions = options.Where(o => o.CustomStateDetailId > 0 && !o.IsDeleted).ToList();