-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathTwilioController.cs
More file actions
945 lines (815 loc) · 38.3 KB
/
TwilioController.cs
File metadata and controls
945 lines (815 loc) · 38.3 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
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
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 Twilio.AspNet.Common;
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;
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)
{
_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;
}
#endregion Private Readonly Properties and Constructors
[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 = "";
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)
{
var department = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value);
//var textToCallEnabled = await _departmentSettingsService.GetDepartmentIsTextCallImportEnabledAsync(departmentId.Value);
//var textCommandEnabled = await _departmentSettingsService.GetDepartmentIsTextCommandEnabledAsync(departmentId.Value);
var dispatchNumbers = await _departmentSettingsService.GetTextToCallSourceNumbersForDepartmentAsync(departmentId.Value);
var authroized = await _limitsService.CanDepartmentProvisionNumberAsync(departmentId.Value);
var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(departmentId.Value);
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)
{
var profile = 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")]
public async Task<ActionResult> VoiceCall(string userId, int callId)
{
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)
{
response.Say("This call has been closed. Goodbye.").Hangup();
return Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml"));
}
if (call.State == (int)CallStates.Cancelled || call.State == (int)CallStates.Closed || call.IsDeleted)
{
response.Say(string.Format("This call, Id {0} has been closed. Goodbye.", call.Number)).Hangup();
return Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml"));
}
var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(call.DepartmentId);
if (call.Attachments != null &&
call.Attachments.Count(x => x.CallAttachmentType == (int)CallAttachmentTypes.DispatchAudio) > 0)
{
var audio = call.Attachments.FirstOrDefault(x =>
x.CallAttachmentType == (int)CallAttachmentTypes.DispatchAudio);
if (audio != null)
{
var url = await _callsService.GetShortenedAudioUrlAsync(call.CallId, audio.CallAttachmentId);
Play playResponse = new Play();
playResponse.Url = new Uri(url);
StringBuilder sb1 = new StringBuilder();
sb1.Append("Press 0 to repeat, Press 1 to respond to the scene");
for (int i = 0; i < stations.Count; i++)
{
if (i >= 8)
break;
sb1.Append(string.Format(", press {0} to respond to {1}", i + 2, stations[i].Name));
}
for (int repeat = 0; repeat < 2; repeat++)
{
var gatherResponse1 = new Gather(numDigits: 1, action: new Uri(string.Format("{0}/api/Twilio/VoiceCallAction?userId={1}&callId={2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId)), method: "GET")
{
BargeIn = true
};
gatherResponse1.Append(new Say(sb1.ToString()));
gatherResponse1.Append(playResponse);
response.Append(gatherResponse1);
}
response.Hangup();
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
}
string address = call.Address;
if (String.IsNullOrWhiteSpace(address) && !string.IsNullOrWhiteSpace(call.GeoLocationData) && call.GeoLocationData.Length > 1)
{
try
{
string[] points = call.GeoLocationData.Split(char.Parse(","));
if (points != null && points.Length == 2)
{
address = await _geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1]));
}
}
catch
{
}
}
if (String.IsNullOrWhiteSpace(address) && !String.IsNullOrWhiteSpace(call.Address))
address = call.Address;
StringBuilder sb = new StringBuilder();
if (!String.IsNullOrWhiteSpace(address))
sb.Append(string.Format("{0}, Priority {1} Address {2} Nature {3}", call.Name, call.GetPriorityText(), call.Address, StringHelpers.StripHtmlTagsCharArray(call.NatureOfCall)));
else
sb.Append(string.Format("{0}, Priority {1} Nature {2}", call.Name, call.GetPriorityText(), call.NatureOfCall));
sb.Append(", Press 0 to repeat, Press 1 to respond to the scene");
for (int i = 0; i < stations.Count; i++)
{
if (i >= 8)
break;
sb.Append(string.Format(", press {0} to respond to {1}", i + 2, stations[i].Name));
}
for (int repeat = 0; repeat < 2; repeat++)
{
var gatherResponse = new Gather(numDigits: 1, action: new Uri(string.Format("{0}/api/Twilio/VoiceCallAction?userId={1}&callId={2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId)), method: "GET")
{
BargeIn = true
};
gatherResponse.Append(new Say(sb.ToString()));
response.Append(gatherResponse);
}
response.Hangup();
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[HttpGet("VoiceCallAction")]
[Produces("application/xml")]
public async Task<ActionResult> VoiceCallAction(string userId, int callId, [FromQuery] VoiceRequest twilioRequest)
{
var response = new VoiceResponse();
if (twilioRequest.Digits == "0")
{
response.Redirect(new Uri(string.Format("{0}/api/Twilio/VoiceCall?userId={1}&callId={2}", Config.SystemBehaviorConfig.ResgridApiBaseUrl, userId, callId)), "GET");
}
else if (twilioRequest.Digits == "1")
{
var call = await _callsService.GetCallByIdAsync(callId);
await _actionLogsService.SetUserActionAsync(userId, call.DepartmentId, (int)ActionTypes.RespondingToScene, null, call.CallId);
response.Say("You have been marked responding to the scene, goodbye.").Hangup();
}
else
{
var call = await _callsService.GetCallByIdAsync(callId);
var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(call.DepartmentId);
int index = int.Parse(twilioRequest.Digits) - 2;
if (index >= 0 && index < 8)
{
var station = stations[index];
if (station != null)
{
await _actionLogsService.SetUserActionAsync(userId, call.DepartmentId, (int)ActionTypes.RespondingToStation, null,
station.DepartmentGroupId);
response.Say(string.Format("You have been marked responding to {0}, goodbye.", station.Name)).Hangup();
}
}
}
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[HttpGet("InboundVoice")]
[Produces("application/xml")]
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)
{
StringBuilder sb = new StringBuilder();
sb.Append($@"Hello {profile.FirstName}, this is the Resgrid automated voice system for {department.Name}. Please select from the following options.
To list current active calls, press 1.
To list current user statuses, press 2.
To list current unit statuses, press 3.
To list upcoming calendar events, press 4.
To list upcoming shifts, press 5.
To set your current status, press 6.
To set your current staffing level, press 7.");
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
};
gatherResponse.Append(new Say(sb.ToString()));
response.Append(gatherResponse);
}
response.Hangup();
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
else
{
response.Say("Thank you for calling Resgrid, automated personnel system. The number you called is not tied to an active department or the department doesn't have this feature enabled. Goodbye.").Hangup();
}
}
else
{
response.Say("Thank you for calling Resgrid, automated personnel system. The number you called is not tied to an active department or the department doesn't have this feature enabled. Goodbye.").Hangup();
}
}
else
{
response.Say("Thank you for calling Resgrid, automated personnel system. The number you called is not tied to an active department or the department doesn't have this feature enabled. Goodbye.").Hangup();
}
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[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);
StringBuilder sb = new StringBuilder();
Gather gatherResponse = null;
if (twilioRequest.Digits == "0")
{
sb.Append($@"Hello {profile.FirstName}, this is the Resgrid automated voice system for {department.Name}. Please select from the following options.
To list current active calls, press 1.
To list current user statuses, press 2.
To list current unit statuses, press 3.
To list upcoming calendar events, press 4.
To list upcoming shifts, press 5.
To set your current status, press 6.
To set your current staffing level, press 7.");
}
else if (twilioRequest.Digits == "1")
{
var calls = await _callsService.GetActiveCallsByDepartmentAsync(department.DepartmentId);
if (calls != null && calls.Any())
{
sb.Append($"There are {calls.Count()} active calls for department {department.Name}.");
foreach (var call in calls)
{
sb.Append($"{call.Name}, Priority {call.GetPriorityText()} Address {call.Address} Nature {StringHelpers.StripHtmlTagsCharArray(call.NatureOfCall)}.");
}
}
else
{
sb.Append($"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);
sb.Append($"{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);
sb.Append($"{unit.Name}, Status {unitStatus.ButtonText}.");
}
}
else
{
sb.Append($"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)
{
sb.Append($"{item.Title}, {item.Start.TimeConverter(department).ToShortDateString()}, {item.Start.TimeConverter(department).ToShortTimeString()}, {item.Location}");
}
}
else
{
sb.Append($"There are no upcoming Calendar events for department {department.Name}.");
}
}
else if (twilioRequest.Digits == "5")
{
sb.Append($"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;
sb.Append($"To set your Current Status please select from the following options.");
foreach (var option in options)
{
if (option.CustomStateDetailId == 0 || option.IsDeleted)
continue;
sb.Append($"Press {index} for {option.ButtonText}.");
index++;
}
gatherResponse = new Gather(numDigits: 1, action: new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceActionStatus?userId={userId}"), method: "GET")
{
BargeIn = true
};
}
else if (twilioRequest.Digits == "7") // Set current staffing
{
var options = await _customStateService.GetCustomPersonnelStaffingsOrDefaultsAsync(department.DepartmentId);
int index = 1;
sb.Append($"To set your Current Staffing please select from the following options.");
foreach (var option in options)
{
if (option.CustomStateDetailId == 0 || option.IsDeleted)
continue;
sb.Append($"Press {index} for {option.ButtonText}.");
index++;
}
gatherResponse = new Gather(numDigits: 1, action: new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceActionStaffing?userId={userId}"), method: "GET")
{
BargeIn = true
};
}
if (gatherResponse == null)
{
gatherResponse = new Gather(numDigits: 1, action: new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}"), method: "GET")
{
BargeIn = true
};
}
for (int repeat = 0; repeat < 2; repeat++)
{
var gather = new Gather(numDigits: 1, action: gatherResponse.Action, method: gatherResponse.Method)
{
BargeIn = true
};
gather.Append(new Say(sb.ToString() + " Press 0 to go back to the main menu."));
response.Append(gather);
}
response.Hangup();
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[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();
if (!String.IsNullOrWhiteSpace(twilioRequest.Digits))
{
if (twilioRequest.Digits == "0")
{
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}"), "GET");
}
else if (int.TryParse(twilioRequest.Digits, out int digit) && digit > 0 && digit <= activeOptions.Count)
{
var selectedOption = activeOptions[digit - 1];
if (selectedOption != null && selectedOption.CustomStateDetailId > 0 && !selectedOption.IsDeleted)
{
await _actionLogsService.SetUserActionAsync(userId, department.DepartmentId, selectedOption.CustomStateDetailId);
response.Say($"You have been marked as {selectedOption.ButtonText}, goodbye.").Hangup();
}
}
else
{
response.Say("Invalid status selection, goodbye.").Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoice"), "GET");
}
}
else
{
response.Say("No status selection made, goodbye.").Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoice"), "GET");
}
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
[HttpGet("InboundVoiceActionStaffing")]
[Produces("application/xml")]
public async Task<ActionResult> InboundVoiceActionStaffing(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.GetCustomPersonnelStaffingsOrDefaultsAsync(department.DepartmentId);
var activeOptions = options.Where(o => o.CustomStateDetailId > 0 && !o.IsDeleted).ToList();
if (!String.IsNullOrWhiteSpace(twilioRequest.Digits))
{
if (twilioRequest.Digits == "0")
{
response.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}"), "GET");
}
else if (int.TryParse(twilioRequest.Digits, out int digit) && digit > 0 && digit <= activeOptions.Count)
{
var selectedOption = activeOptions[digit - 1];
await _userStateService.CreateUserState(userId, department.DepartmentId, selectedOption.CustomStateDetailId);
response.Say($"You have been marked as {selectedOption.ButtonText}. Goodbye.").Hangup();
}
else
{
response.Say("Invalid staffing selection. Returning to the main menu.")
.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}"), "GET");
}
}
else
{
response.Say("No staffing selection made. Returning to the main menu.")
.Redirect(new Uri($"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/Twilio/InboundVoiceAction?userId={userId}"), "GET");
}
return new ContentResult
{
Content = response.ToString(),
ContentType = "application/xml",
StatusCode = 200
};
}
}
[Serializable]
public class TwilioMessage : TwilioRequest
{
public string MessageSid { get; set; }
public string SmsMessageSid { get; set; }
public string Body { get; set; }
}
}