コード例 #1
0
        public HttpResponseMessage IncomingMessage([FromUri] TwilioMessage request)
        {
            if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            var response = new TwilioResponse();

            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
            {
                var departmentId = _departmentSettingsService.GetDepartmentIdByTextToCallNumber(textMessage.To);

                if (departmentId.HasValue)
                {
                    var department         = _departmentsService.GetDepartmentById(departmentId.Value);
                    var textToCallEnabled  = _departmentSettingsService.GetDepartmentIsTextCallImportEnabled(departmentId.Value);
                    var textCommandEnabled = _departmentSettingsService.GetDepartmentIsTextCommandEnabled(departmentId.Value);
                    var dispatchNumbers    = _departmentSettingsService.GetTextToCallSourceNumbersForDepartment(departmentId.Value);
                    var authroized         = _limitsService.CanDepartmentProvisionNumber(departmentId.Value);
                    var customStates       = _customStateService.GetAllActiveCustomStatesForDepartment(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 we don't have dispatchNumbers and Text Command isn't enabled it's a dispatch text
                        if (!isDispatchSource && !textCommandEnabled)
                        {
                            isDispatchSource = true;
                        }

                        if (isDispatchSource && textToCallEnabled)
                        {
                            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 = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);
                            foreach (var u in users)
                            {
                                var cd = new CallDispatch();
                                cd.UserId = u.UserId;

                                c.Dispatches.Add(cd);
                            }

                            var savedCall = _callsService.SaveCall(c);

                            var cqi = new CallQueueItem();
                            cqi.Call                 = savedCall;
                            cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(users.Select(x => x.UserId).ToList());
                            cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                            _queueService.EnqueueCallBroadcast(cqi);

                            messageEvent.Processed = true;
                        }

                        if (!isDispatchSource && textCommandEnabled)
                        {
                            var profile = _userProfileService.FindProfileByMobileNumber(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;
                                    _actionLogsService.SetUserAction(profile.UserId, department.DepartmentId, (int)payload.GetActionType());
                                    response.Message(string.Format("Resgrid recieved 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;
                                    _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType());
                                    response.Message(string.Format("Resgrid recieved 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;
                                    _userProfileService.DisableTextMessagesForUser(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;
                                    _actionLogsService.SetUserAction(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 recieved your text command. Status changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid recieved your text command and updated your status");
                                    }
                                    break;

                                case TextCommandTypes.CustomStaffing:
                                    messageEvent.Processed = true;
                                    _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 recieved your text command. Staffing changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid recieved your text command and updated your staffing");
                                    }
                                    break;

                                case TextCommandTypes.MyStatus:
                                    messageEvent.Processed = true;


                                    var userStatus   = _actionLogsService.GetLastActionLogForUser(profile.UserId);
                                    var userStaffing = _userStateService.GetLastUserStateByUserId(profile.UserId);

                                    var customStatusLevel   = _customStateService.GetCustomPersonnelStatus(department.DepartmentId, userStatus);
                                    var customStaffingLevel = _customStateService.GetCustomPersonnelStaffing(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 = _callsService.GetActiveCallsByDepartment(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:{activeCall.NatureOfCall}" + Environment.NewLine);
                                    }


                                    response.Message(activeCallText.ToString());
                                    break;

                                case TextCommandTypes.Units:
                                    messageEvent.Processed = true;

                                    var unitStatus = _unitsService.GetAllLatestStatusForUnitsByDepartmentId(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 = _customStateService.GetCustomUnitState(unit);
                                        unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine);
                                    }

                                    response.Message(unitStatusesText.ToString());
                                    break;

                                case TextCommandTypes.CallDetail:
                                    messageEvent.Processed = true;

                                    var call = _callsService.GetCallById(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))
                                    {
                                        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 == "17753765253")                 // Resgrid master text number
                {
                    var profile = _userProfileService.FindProfileByMobileNumber(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;
                        _userProfileService.DisableTextMessagesForUser(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
            {
                _numbersService.SaveInboundMessageEvent(messageEvent);
            }

            //return Request.CreateResponse(HttpStatusCode.OK);

            //var response = new TwilioResponse();

            return(Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter()));
        }
コード例 #2
0
        public HttpResponseMessage SaveCall([FromBody] NewCallInput newCallInput)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            var call = new Call
            {
                DepartmentId    = DepartmentId,
                ReportingUserId = UserId,
                Priority        = (int)Enum.Parse(typeof(CallPriority), newCallInput.Pri),
                Name            = newCallInput.Nme,
                NatureOfCall    = newCallInput.Noc
            };

            if (!string.IsNullOrWhiteSpace(newCallInput.CNme))
            {
                call.ContactName = newCallInput.CNme;
            }

            if (!string.IsNullOrWhiteSpace(newCallInput.CNum))
            {
                call.ContactName = newCallInput.CNum;
            }

            if (!string.IsNullOrWhiteSpace(newCallInput.Cid))
            {
                call.IncidentNumber = newCallInput.Cid;
            }

            if (!string.IsNullOrWhiteSpace(newCallInput.Add))
            {
                call.Address = newCallInput.Add;
            }

            if (!string.IsNullOrWhiteSpace(newCallInput.W3W))
            {
                call.W3W = newCallInput.W3W;
            }

            //if (call.Address.Equals("Current Coordinates", StringComparison.InvariantCultureIgnoreCase))
            //	call.Address = "";

            if (!string.IsNullOrWhiteSpace(newCallInput.Not))
            {
                call.Notes = newCallInput.Not;
            }

            if (!string.IsNullOrWhiteSpace(newCallInput.Geo))
            {
                call.GeoLocationData = newCallInput.Geo;
            }

            if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.Address))
            {
                call.GeoLocationData = _geoLocationProvider.GetLatLonFromAddress(call.Address);
            }

            if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.W3W))
            {
                var coords = _geoLocationProvider.GetCoordinatesFromW3W(call.W3W);

                if (coords != null)
                {
                    call.GeoLocationData = $"{coords.Latitude},{coords.Longitude}";
                }
            }

            call.LoggedOn = DateTime.UtcNow;

            if (!String.IsNullOrWhiteSpace(newCallInput.Typ) && newCallInput.Typ != "No Type")
            {
                var callTypes = _callsService.GetCallTypesForDepartment(DepartmentId);
                var type      = callTypes.FirstOrDefault(x => x.Type == newCallInput.Typ);

                if (type != null)
                {
                    call.Type = type.Type;
                }
            }
            var users = _departmentsService.GetAllUsersForDepartment(DepartmentId);

            call.Dispatches      = new Collection <CallDispatch>();
            call.GroupDispatches = new List <CallDispatchGroup>();
            call.RoleDispatches  = new List <CallDispatchRole>();

            if (string.IsNullOrWhiteSpace(newCallInput.Dis) || newCallInput.Dis == "0")
            {
                // Use case, existing clients and non-ionic2 app this will be null dispatch all users. Or we've specified everyone (0).
                foreach (var u in users)
                {
                    var cd = new CallDispatch {
                        UserId = u.UserId
                    };

                    call.Dispatches.Add(cd);
                }
            }
            else
            {
                var dispatch = newCallInput.Dis.Split(char.Parse("|"));

                try
                {
                    var usersToDispatch = dispatch.Where(x => x.StartsWith("P:")).Select(y => y.Replace("P:", ""));
                    foreach (var user in usersToDispatch)
                    {
                        var cd = new CallDispatch {
                            UserId = user
                        };
                        call.Dispatches.Add(cd);
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }

                try
                {
                    var groupsToDispatch = dispatch.Where(x => x.StartsWith("G:")).Select(y => int.Parse(y.Replace("G:", "")));
                    foreach (var group in groupsToDispatch)
                    {
                        var cd = new CallDispatchGroup {
                            DepartmentGroupId = group
                        };
                        call.GroupDispatches.Add(cd);
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }

                try
                {
                    var rolesToDispatch = dispatch.Where(x => x.StartsWith("R:")).Select(y => int.Parse(y.Replace("R:", "")));
                    foreach (var role in rolesToDispatch)
                    {
                        var cd = new CallDispatchRole {
                            RoleId = role
                        };
                        call.RoleDispatches.Add(cd);
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                }
            }


            var savedCall = _callsService.SaveCall(call);

            OutboundEventProvider.CallAddedTopicHandler handler = new OutboundEventProvider.CallAddedTopicHandler();
            handler.Handle(new CallAddedEvent()
            {
                DepartmentId = DepartmentId, Call = savedCall
            });

            var profiles = new List <string>();

            if (call.Dispatches != null && call.Dispatches.Any())
            {
                profiles.AddRange(call.Dispatches.Select(x => x.UserId).ToList());
            }

            if (call.GroupDispatches != null && call.GroupDispatches.Any())
            {
                foreach (var groupDispatch in call.GroupDispatches)
                {
                    var group = _departmentGroupsService.GetGroupById(groupDispatch.DepartmentGroupId);

                    if (group != null && group.Members != null)
                    {
                        profiles.AddRange(group.Members.Select(x => x.UserId));
                    }
                }
            }

            if (call.RoleDispatches != null && call.RoleDispatches.Any())
            {
                foreach (var roleDispatch in call.RoleDispatches)
                {
                    var members = _personnelRolesService.GetAllMembersOfRole(roleDispatch.RoleId);

                    if (members != null)
                    {
                        profiles.AddRange(members.Select(x => x.UserId).ToList());
                    }
                }
            }

            var cqi = new CallQueueItem();

            cqi.Call     = savedCall;
            cqi.Profiles = _userProfileService.GetSelectedUserProfiles(profiles);

            _queueService.EnqueueCallBroadcast(cqi);

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
コード例 #3
0
        public HttpResponseMessage Receive(PostmarkInboundMessage message)
        {
            if (message != null)
            {
                try
                {
                    var mailMessage = new MimeMessage();

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && message.FromFull.Email.Trim() == "*****@*****.**")
                    {
                        return(new HttpResponseMessage(HttpStatusCode.Created));
                    }

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                    {
                        mailMessage.From.Add(new MailboxAddress(message.FromFull.Name.Trim(), message.FromFull.Email.Trim()));
                    }
                    else
                    {
                        mailMessage.From.Add(new MailboxAddress("Inbound Email Dispatch", "*****@*****.**"));
                    }

                    if (!String.IsNullOrWhiteSpace(message.Subject))
                    {
                        mailMessage.Subject = message.Subject;
                    }
                    else
                    {
                        mailMessage.Subject = "Dispatch Email";
                    }

                    var builder = new BodyBuilder();

                    if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                    {
                        builder.HtmlBody = HttpUtility.HtmlDecode(message.HtmlBody);
                    }

                    if (!String.IsNullOrWhiteSpace(message.TextBody))
                    {
                        builder.TextBody = message.TextBody;
                    }

                    int    type         = 0;          // 1 = dispatch // 2 = email list // 3 = group dispatch // 4 = group message
                    string emailAddress = String.Empty;
                    string bounceEmail  = String.Empty;
                    string name         = String.Empty;

                    #region Trying to Find What type of email this is
                    foreach (var email in message.ToFull)
                    {
                        if (StringHelpers.ValidateEmail(email.Email))
                        {
                            if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.DispatchTestDomain}"))
                            {
                                type = 1;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchTestDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.ListsTestDomain}"))
                            {
                                type = 2;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsTestDomain}", "");
                                }

                                if (emailAddress.Contains("+") && emailAddress.Contains("="))
                                {
                                    var tempBounceEmail = emailAddress.Substring(emailAddress.IndexOf("+") + 1);
                                    bounceEmail = tempBounceEmail.Replace("=", "@");

                                    emailAddress = emailAddress.Replace(tempBounceEmail, "");
                                    emailAddress = emailAddress.Replace("+", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupsTestDomain}"))
                            {
                                type = 3;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsTestDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                            else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupTestMessageDomain}"))
                            {
                                type = 4;

                                if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}"))
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupMessageDomain}", "");
                                }
                                else
                                {
                                    emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupTestMessageDomain}", "");
                                }

                                name = email.Name;
                                mailMessage.To.Clear();
                                mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                break;
                            }
                        }
                    }

                    // Some providers aren't putting email address in the To line, process the CC line
                    if (type == 0)
                    {
                        foreach (var email in message.CcFull)
                        {
                            if (StringHelpers.ValidateEmail(email.Email))
                            {
                                var proccedEmailInfo = ProcessEmailAddress(email.Email);

                                if (proccedEmailInfo.Item1 > 0)
                                {
                                    type         = proccedEmailInfo.Item1;
                                    emailAddress = proccedEmailInfo.Item2;

                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));
                                }
                            }
                        }
                    }

                    // If To and CC didn't work, try the header.
                    if (type == 0)
                    {
                        try
                        {
                            if (message.Headers != null && message.Headers.Count > 0)
                            {
                                var header = message.Headers.FirstOrDefault(x => x.Name == "Received-SPF");

                                if (header != null)
                                {
                                    var lastValue = header.Value.LastIndexOf(char.Parse("="));
                                    var newEmail  = header.Value.Substring(lastValue + 1, (header.Value.Length - (lastValue + 1)));

                                    newEmail = newEmail.Trim();

                                    if (StringHelpers.ValidateEmail(newEmail))
                                    {
                                        emailAddress = newEmail;
                                        var proccedEmailInfo = ProcessEmailAddress(newEmail);

                                        type         = proccedEmailInfo.Item1;
                                        emailAddress = proccedEmailInfo.Item2;

                                        mailMessage.To.Clear();
                                        mailMessage.To.Add(new MailboxAddress("Email Importer", newEmail));
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }
                    #endregion Trying to Find What type of email this is

                    if (type == 1)                      // Dispatch
                    {
                        #region Dispatch Email
                        var departmentId = _departmentSettingsService.GetDepartmentIdForDispatchEmail(emailAddress);

                        if (departmentId.HasValue)
                        {
                            try
                            {
                                var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentId.Value);
                                List <IdentityUser> departmentUsers = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);

                                var callEmail = new CallEmail();

                                if (!String.IsNullOrWhiteSpace(message.Subject))
                                {
                                    callEmail.Subject = message.Subject;
                                }

                                else
                                {
                                    callEmail.Subject = "Dispatch Email";
                                }

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                callEmail.TextBody = message.TextBody;

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentId.Value;
                                    emailSettings.Department   = _departmentsService.GetDepartmentById(departmentId.Value, false);
                                }
                                else if (emailSettings.Department == null)
                                {
                                    emailSettings.Department = _departmentsService.GetDepartmentById(departmentId.Value);
                                }

                                var activeCalls     = _callsService.GetLatest10ActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                                var units           = _unitsService.GetUnitsForDepartment(emailSettings.Department.DepartmentId);
                                var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentUsers, emailSettings.Department, activeCalls, units, defaultPriority);

                                if (call != null)
                                {
                                    call.DepartmentId = departmentId.Value;

                                    var savedCall = _callsService.SaveCall(call);

                                    var cqi = new CallQueueItem();
                                    cqi.Call                 = savedCall;
                                    cqi.Profiles             = _userProfileService.GetAllProfilesForDepartment(call.DepartmentId).Select(x => x.Value).ToList();
                                    cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                    _queueService.EnqueueCallBroadcast(cqi);

                                    return(new HttpResponseMessage(HttpStatusCode.Created));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }
                        #endregion Dispatch
                    }
                    else if (type == 2)                     // Email List
                    {
                        #region Distribution Email
                        var list = _distributionListsService.GetDistributionListByAddress(emailAddress);

                        if (list != null)
                        {
                            if (String.IsNullOrWhiteSpace(bounceEmail))
                            {
                                try
                                {
                                    List <Model.File> files = new List <Model.File>();

                                    try
                                    {
                                        if (message.Attachments != null && message.Attachments.Any())
                                        {
                                            foreach (var attachment in message.Attachments)
                                            {
                                                if (Convert.ToInt32(attachment.ContentLength) > 0)
                                                {
                                                    Model.File file = new Model.File();

                                                    byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                    file.Data         = filebytes;
                                                    file.FileName     = attachment.Name;
                                                    file.DepartmentId = list.DepartmentId;
                                                    file.ContentId    = attachment.ContentID;
                                                    file.FileType     = attachment.ContentType;
                                                    file.Timestamp    = DateTime.UtcNow;

                                                    files.Add(_fileService.SaveFile(file));
                                                }
                                            }
                                        }
                                    }
                                    catch { }

                                    var dlqi = new DistributionListQueueItem();
                                    dlqi.List  = list;
                                    dlqi.Users = _departmentsService.GetAllUsersForDepartment(list.DepartmentId);

                                    if (files != null && files.Any())
                                    {
                                        dlqi.FileIds = new List <int>();
                                        dlqi.FileIds.AddRange(files.Select(x => x.FileId).ToList());
                                    }

                                    dlqi.Message             = new InboundMessage();
                                    dlqi.Message.Attachments = new List <InboundMessageAttachment>();

                                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                                    {
                                        dlqi.Message.FromEmail = message.FromFull.Email.Trim();
                                        dlqi.Message.FromName  = message.FromFull.Name.Trim();
                                    }

                                    dlqi.Message.Subject   = message.Subject;
                                    dlqi.Message.HtmlBody  = message.HtmlBody;
                                    dlqi.Message.TextBody  = message.TextBody;
                                    dlqi.Message.MessageID = message.MessageID;

                                    _queueService.EnqueueDistributionListBroadcast(dlqi);
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogException(ex);
                                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                                }
                            }
                            else
                            {
                                return(new HttpResponseMessage(HttpStatusCode.Created));
                            }
                        }

                        return(new HttpResponseMessage(HttpStatusCode.Created));

                        #endregion Distribution Email
                    }
                    if (type == 3)                      // Group Dispatch
                    {
                        #region Group Dispatch Email
                        var departmentGroup = _departmentGroupsService.GetGroupByDispatchEmailCode(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                var emailSettings = _departmentsService.GetDepartmentEmailSettings(departmentGroup.DepartmentId);
                                //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var callEmail = new CallEmail();
                                callEmail.Subject = message.Subject;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentGroup.DepartmentId;

                                    if (departmentGroup.Department != null)
                                    {
                                        emailSettings.Department = departmentGroup.Department;
                                    }
                                    else
                                    {
                                        emailSettings.Department = _departmentsService.GetDepartmentById(departmentGroup.DepartmentId);
                                    }
                                }

                                var activeCalls = _callsService.GetActiveCallsByDepartment(emailSettings.Department.DepartmentId);
                                var units       = _unitsService.GetAllUnitsForGroup(departmentGroup.DepartmentGroupId);

                                var priorities      = _callsService.GetActiveCallPrioritesForDepartment(emailSettings.Department.DepartmentId);
                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentGroupUsers.Select(x => x.User).ToList(), emailSettings.Department, activeCalls, units, defaultPriority);

                                if (call != null)
                                {
                                    call.DepartmentId = departmentGroup.DepartmentId;

                                    var savedCall = _callsService.SaveCall(call);

                                    var cqi = new CallQueueItem();
                                    cqi.Call                 = savedCall;
                                    cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(departmentGroupUsers.Select(x => x.UserId).ToList());
                                    cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                                    _queueService.EnqueueCallBroadcast(cqi);

                                    return(new HttpResponseMessage(HttpStatusCode.Created));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }
                        #endregion Group Dispatch Email
                    }
                    if (type == 4)                      // Group Message
                    {
                        #region Group Message
                        var departmentGroup = _departmentGroupsService.GetGroupByMessageEmailCode(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                //var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroup(departmentGroup.DepartmentGroupId);
                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var newMessage = new Message();
                                newMessage.SentOn          = DateTime.UtcNow;
                                newMessage.SendingUserId   = departmentGroup.Department.ManagingUserId;
                                newMessage.IsBroadcast     = true;
                                newMessage.Subject         = message.Subject;
                                newMessage.SystemGenerated = true;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    newMessage.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    newMessage.Body = message.TextBody;
                                }

                                foreach (var member in departmentGroupUsers)
                                {
                                    if (newMessage.GetRecipients().All(x => x != member.UserId))
                                    {
                                        newMessage.AddRecipient(member.UserId);
                                    }
                                }

                                var savedMessage = _messageService.SaveMessage(newMessage);
                                _messageService.SendMessage(savedMessage, "", departmentGroup.DepartmentId, false);

                                return(new HttpResponseMessage(HttpStatusCode.Created));
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                            }
                        }

                        #endregion Group Message
                    }

                    return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                }
                catch (Exception ex)
                {
                    Framework.Logging.LogException(ex);
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.ToString())
                    });
                }
            }
            else
            {
                // If our message was null, we throw an exception
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("Error parsing Inbound Message, message is null.")
                });
            }
        }
コード例 #4
0
ファイル: LogsController.cs プロジェクト: mrpastewart/Core
        public IActionResult NewLog(NewLogView model, IFormCollection form, ICollection <IFormFile> files)
        {
            PopulateLogViewModel(model);

            if (model.LogType == LogTypes.Work && String.IsNullOrWhiteSpace(form["nonUnitPersonnel"]))
            {
                model.ErrorMessage = "You need to specify at least 1 person to be part of the work log.";
                return(View(model));
            }

            try
            {
                try
                {
                    if (files != null && files.Any())
                    {
                        foreach (var file in files)
                        {
                            if (file != null && !String.IsNullOrWhiteSpace(file.FileName))
                            {
                                string extension = Path.GetExtension(file.FileName);

                                if (!String.IsNullOrWhiteSpace(extension))
                                {
                                    extension = extension.ToLower();
                                }

                                if (extension != ".jpg" && extension != ".jpeg" && extension != ".png" && extension != ".gif" && extension != ".pdf" &&
                                    extension != ".doc" && extension != ".docx" && extension != ".ppt" && extension != ".pptx" && extension != ".pps" &&
                                    extension != ".ppsx" && extension != ".odt" && extension != ".xls" && extension != ".xlsx" && extension != ".txt" && extension != ".rtf")
                                {
                                    model.ErrorMessage = string.Format("File type ({0}) is not importable.", extension);
                                }

                                if (file.Length > 10000000)
                                {
                                    model.ErrorMessage = "Document is too large, must be smaller then 10MB.";
                                }
                            }
                        }
                    }
                }
                catch { }

                if (!String.IsNullOrWhiteSpace(model.ErrorMessage))
                {
                    return(View(model));
                }

                // Get all unit blocks in the report
                List <int> unitsInReport = (from object key in form.Keys where key.ToString().StartsWith("unit_personnel_") select int.Parse(key.ToString().Replace("unit_personnel_", ""))).ToList();

                model.Log.LoggedByUserId = UserId;
                model.Log.DepartmentId   = model.Department.DepartmentId;
                model.Log.Narrative      = System.Net.WebUtility.HtmlDecode(model.Log.Narrative);
                model.Log.Cause          = System.Net.WebUtility.HtmlDecode(model.Log.Cause);
                model.Log.InitialReport  = System.Net.WebUtility.HtmlDecode(model.Log.InitialReport);
                model.Log.LogType        = (int)model.LogType;

                if (model.Log.StationGroupId == 0)
                {
                    model.Log.StationGroupId = null;
                }

                model.Log.Units = new Collection <LogUnit>();
                model.Log.Users = new Collection <LogUser>();

                if (String.IsNullOrWhiteSpace(model.Log.InvestigatedByUserId))
                {
                    model.Log.InvestigatedByUserId = null;
                }

                if (model.Log.StationGroupId.HasValue && model.Log.StationGroupId.Value == 0)
                {
                    model.Log.StationGroupId = null;
                }

                if (model.LogType == LogTypes.Run)
                {
                    if (model.CallId == 0)
                    {
                        model.Call.DepartmentId    = DepartmentId;
                        model.Call.ReportingUserId = UserId;
                        model.Call.Priority        = (int)model.CallPriority;

                        if (model.Call.Type == "No Type")
                        {
                            model.Call.Type = null;
                        }

                        model.Call          = _callsService.SaveCall(model.Call);
                        model.Log.CallId    = model.Call.CallId;
                        model.Log.StartedOn = model.Call.LoggedOn;
                    }
                    else
                    {
                        var call = _callsService.GetCallById(model.CallId);
                        call.Priority     = (int)model.CallPriority;
                        call.NatureOfCall = model.Call.NatureOfCall;
                        call.Address      = model.Call.Address;
                        call.LoggedOn     = model.Call.LoggedOn;
                        call.Name         = model.Call.Name;

                        model.Call       = _callsService.SaveCall(call);
                        model.Log.CallId = model.Call.CallId;
                    }
                }

                if (model.LogType == LogTypes.Work)
                {
                    var startedOn = form["Log.StartedOn"];
                    var endedOn   = form["Log.EndedOn"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(endedOn))
                    {
                        model.Log.EndedOn = DateTime.Parse(endedOn);
                    }
                }

                if (model.LogType == LogTypes.Meeting)
                {
                    var startedOn = form["Log.StartedOn"];
                    var endedOn   = form["Log.EndedOn"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(endedOn))
                    {
                        model.Log.EndedOn = DateTime.Parse(endedOn);
                    }
                }

                if (model.LogType == LogTypes.Coroner)
                {
                    var startedOn          = form["coronerDate"];
                    var caseNumber         = form["caseNumber"];
                    var coronerInstructors = form["coronerInstructors"];
                    var coronerDestination = form["coronerDestination"];
                    var coronerOthers      = form["coronerOthers"];

                    if (!String.IsNullOrWhiteSpace(startedOn))
                    {
                        model.Log.StartedOn = DateTime.Parse(startedOn);
                    }

                    if (!String.IsNullOrWhiteSpace(caseNumber))
                    {
                        model.Log.ExternalId = caseNumber;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerInstructors))
                    {
                        model.Log.Instructors = coronerInstructors;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerDestination))
                    {
                        model.Log.Location = coronerDestination;
                    }

                    if (!String.IsNullOrWhiteSpace(coronerOthers))
                    {
                        model.Log.OtherPersonnel = coronerOthers;
                    }
                }

                foreach (var i in unitsInReport)
                {
                    var unit = new LogUnit();
                    unit.UnitId = i;

                    if (!string.IsNullOrWhiteSpace(form["unit_dispatchtime_" + i]))
                    {
                        unit.Dispatched = DateTime.Parse(form["unit_dispatchtime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_enroutetime_" + i]))
                    {
                        unit.Enroute = DateTime.Parse(form["unit_enroutetime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_onscenetime_" + i]))
                    {
                        unit.OnScene = DateTime.Parse(form["unit_onscenetime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_releasedtime_" + i]))
                    {
                        unit.Released = DateTime.Parse(form["unit_releasedtime_" + i]);
                    }

                    if (!string.IsNullOrWhiteSpace(form["unit_inquarterstime_" + i]))
                    {
                        unit.InQuarters = DateTime.Parse(form["unit_inquarterstime_" + i]);
                    }

                    model.Log.Units.Add(unit);

                    if (!string.IsNullOrWhiteSpace(form["unit_personnel_" + i]))
                    {
                        var personnelIds = form["unit_personnel_" + i].ToString().Split(char.Parse(","));

                        foreach (var personnelId in personnelIds)
                        {
                            var logUser = new LogUser();
                            logUser.UserId = personnelId;
                            logUser.UnitId = i;

                            model.Log.Users.Add(logUser);
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(form["nonUnitPersonnel"]))
                {
                    var personnelIds = form["nonUnitPersonnel"].ToString().Split(char.Parse(","));

                    foreach (var personnelId in personnelIds)
                    {
                        var logUser = new LogUser();
                        logUser.UserId = personnelId;

                        model.Log.Users.Add(logUser);
                    }
                }

                var savedLog = _workLogsService.SaveLog(model.Log);

                try
                {
                    if (files != null)
                    {
                        foreach (var file in files)
                        {
                            if (file != null && file.Length > 0)
                            {
                                LogAttachment attachment = new LogAttachment();
                                attachment.LogId    = savedLog.LogId;
                                attachment.Type     = file.ContentType;
                                attachment.FileName = file.FileName;

                                byte[] uploadedFile = new byte[file.OpenReadStream().Length];
                                file.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                                attachment.Data      = uploadedFile;
                                attachment.UserId    = UserId;
                                attachment.Timestamp = DateTime.UtcNow;

                                _workLogsService.SaveLogAttachment(attachment);
                            }
                        }
                    }
                }
                catch { }

                _eventAggregator.SendMessage <LogAddedEvent>(new LogAddedEvent()
                {
                    DepartmentId = DepartmentId, Log = model.Log
                });
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);

                model.ErrorMessage = "We encountered an error trying to save your log. Please check your form to ensure it's properly filled out and try again.";
                return(View(model));
            }

            return(RedirectToAction("Index"));
        }
コード例 #5
0
        //[AcceptVerbs("POST")]
        public HttpResponseMessage Process()        //([FromBody]TextMessage textMessage2)
        {
            var queryValues = Request.RequestUri.ParseQueryString();

            var textMessage = new TextMessage();

            textMessage.Type        = queryValues["type"];
            textMessage.To          = queryValues["to"];
            textMessage.Msisdn      = queryValues["msisdn"];
            textMessage.NetworkCode = queryValues["network-code"];
            textMessage.MessageId   = queryValues["messageId"];
            textMessage.Timestamp   = queryValues["message-timestamp"];
            textMessage.Concat      = queryValues["concat"];
            textMessage.ConcatRef   = queryValues["concat-ref"];
            textMessage.ConcatTotal = queryValues["concat-total"];
            textMessage.ConcatPart  = queryValues["concat-part"];
            textMessage.Data        = queryValues["data"];
            textMessage.Udh         = queryValues["udh"];
            textMessage.Text        = queryValues["text"];

            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
            {
                var departmentId = _departmentSettingsService.GetDepartmentIdByTextToCallNumber(textMessage.To);

                if (departmentId.HasValue)
                {
                    var department         = _departmentsService.GetDepartmentById(departmentId.Value);
                    var textToCallEnabled  = _departmentSettingsService.GetDepartmentIsTextCallImportEnabled(departmentId.Value);
                    var textCommandEnabled = _departmentSettingsService.GetDepartmentIsTextCommandEnabled(departmentId.Value);
                    var dispatchNumbers    = _departmentSettingsService.GetTextToCallSourceNumbersForDepartment(departmentId.Value);
                    var authroized         = _limitsService.CanDepartmentProvisionNumber(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 we don't have dispatchNumbers and Text Command isn't
                        // enabled it's a dispatch text
                        if (!isDispatchSource && !textCommandEnabled)
                        {
                            isDispatchSource = true;
                        }

                        if (isDispatchSource && textToCallEnabled)
                        {
                            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 = _departmentsService.GetAllUsersForDepartment(departmentId.Value, true);
                            foreach (var u in users)
                            {
                                var cd = new CallDispatch();
                                cd.UserId = u.UserId;

                                c.Dispatches.Add(cd);
                            }

                            var savedCall = _callsService.SaveCall(c);

                            var cqi = new CallQueueItem();
                            cqi.Call                 = savedCall;
                            cqi.Profiles             = _userProfileService.GetSelectedUserProfiles(users.Select(x => x.UserId).ToList());
                            cqi.DepartmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(cqi.Call.DepartmentId);

                            _queueService.EnqueueCallBroadcast(cqi);

                            messageEvent.Processed = true;
                        }

                        if (!isDispatchSource && textCommandEnabled)
                        {
                            var profile = _userProfileService.FindProfileByMobileNumber(textMessage.Msisdn);

                            if (profile != null)
                            {
                                var payload = _textCommandService.DetermineType(textMessage.Text);

                                switch (payload.Type)
                                {
                                case TextCommandTypes.None:
                                    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("Status Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    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("Staffing Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("normal 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);

                                    _communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Help", help.ToString(), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Action:
                                    messageEvent.Processed = true;
                                    _actionLogsService.SetUserAction(profile.UserId, department.DepartmentId, (int)payload.GetActionType());
                                    _communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Status", string.Format("Resgrid received your text command. Status changed to: {0}", payload.GetActionType()), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Staffing:
                                    messageEvent.Processed = true;
                                    _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType());
                                    _communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Staffing", string.Format("Resgrid received your text command. Staffing level changed to: {0}", payload.GetStaffingType()), department.DepartmentId, textMessage.To, profile);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Framework.Logging.LogException(ex);
            }
            finally
            {
                _numbersService.SaveInboundMessageEvent(messageEvent);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
コード例 #6
0
        public Tuple <bool, string> Process(CallPruneQueueItem item)
        {
            bool   success = true;
            string result  = "";

            if (item != null && item.PruneSettings != null)
            {
                try
                {
                    var calls = _callsService.GetActiveCallsByDepartmentForUpdate(item.PruneSettings.DepartmentId);

                    if (calls != null && calls.Count > 0)
                    {
                        var emailImportCalls = calls.Where(x => x.CallSource == (int)CallSources.EmailImport || x.CallSource == (int)CallSources.AudioImport);
                        var userCalls        = calls.Where(x => x.CallSource == (int)CallSources.User);

                        if (item.PruneSettings.PruneEmailImportedCalls.HasValue &&
                            item.PruneSettings.PruneEmailImportedCalls.Value & item.PruneSettings.EmailImportCallPruneInterval.HasValue)
                        {
                            if (emailImportCalls.Any())
                            {
                                foreach (var call in emailImportCalls)
                                {
                                    if (call.LoggedOn.AddMinutes(item.PruneSettings.EmailImportCallPruneInterval.Value) < DateTime.UtcNow)
                                    {
                                        call.State          = (int)CallStates.Closed;
                                        call.ClosedOn       = DateTime.UtcNow;
                                        call.CompletedNotes = "Call automatically closed by the system.";
                                        call.ClosedByUserId = item.PruneSettings.Department.ManagingUserId;

                                        _callsService.SaveCall(call);
                                    }
                                }
                            }
                        }

                        if (item.PruneSettings.PruneUserEnteredCalls.HasValue &&
                            item.PruneSettings.PruneUserEnteredCalls.Value & item.PruneSettings.UserCallPruneInterval.HasValue)
                        {
                            if (userCalls.Any())
                            {
                                foreach (var call in userCalls)
                                {
                                    if (call.LoggedOn.AddMinutes(item.PruneSettings.UserCallPruneInterval.Value) < DateTime.UtcNow)
                                    {
                                        call.State          = (int)CallStates.Closed;
                                        call.ClosedOn       = DateTime.UtcNow;
                                        call.CompletedNotes = "Call automatically closed by the system.";
                                        call.ClosedByUserId = item.PruneSettings.Department.ManagingUserId;

                                        _callsService.SaveCall(call);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    result  = ex.ToString();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
コード例 #7
0
        public Tuple <bool, string> Process(CallEmailQueueItem item)
        {
            bool   success = true;
            string result  = "";

            _callEmailProvider = Bootstrapper.GetKernel().Resolve <ICallEmailProvider>();

            if (!String.IsNullOrWhiteSpace(item?.EmailSettings?.Hostname))
            {
                CallEmailsResult emailResult = _callEmailProvider.GetAllCallEmailsFromServer(item.EmailSettings);

                if (emailResult?.Emails != null && emailResult.Emails.Count > 0)
                {
                    var calls = new List <Call>();

                    _callsService              = Bootstrapper.GetKernel().Resolve <ICallsService>();
                    _queueService              = Bootstrapper.GetKernel().Resolve <IQueueService>();
                    _departmentsService        = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                    _userProfileService        = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                    _departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
                    _unitsService              = Bootstrapper.GetKernel().Resolve <IUnitsService>();

                    // Ran into an issue where the department users didn't come back. We can't put the email back in the POP
                    // email box so just added some simple retry logic here.
                    List <IdentityUser> departmentUsers = _departmentsService.GetAllUsersForDepartment(item.EmailSettings.DepartmentId, true);
                    var profiles = _userProfileService.GetAllProfilesForDepartment(item.EmailSettings.DepartmentId);

                    int retry = 0;
                    while (retry < 3 && departmentUsers == null)
                    {
                        Thread.Sleep(150);
                        departmentUsers = _departmentsService.GetAllUsersForDepartment(item.EmailSettings.DepartmentId, true);
                        retry++;
                    }

                    foreach (var email in emailResult.Emails)
                    {
                        var activeCalls = _callsService.GetActiveCallsByDepartment(item.EmailSettings.Department.DepartmentId);
                        var units       = _unitsService.GetUnitsForDepartment(item.EmailSettings.Department.DepartmentId);

                        var priorities      = _callsService.GetActiveCallPrioritesForDepartment(item.EmailSettings.Department.DepartmentId);
                        int defaultPriority = (int)CallPriority.High;

                        if (priorities != null && priorities.Any())
                        {
                            var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                            if (defaultPrio != null)
                            {
                                defaultPriority = defaultPrio.DepartmentCallPriorityId;
                            }
                        }

                        var call = _callsService.GenerateCallFromEmail(item.EmailSettings.FormatType, email,
                                                                       item.EmailSettings.Department.ManagingUserId, departmentUsers, item.EmailSettings.Department, activeCalls, units, defaultPriority);

                        if (call != null)
                        {
                            call.DepartmentId = item.EmailSettings.DepartmentId;

                            if (!calls.Any(x => x.Name == call.Name && x.NatureOfCall == call.NatureOfCall))
                            {
                                calls.Add(call);
                            }
                        }
                    }

                    if (calls.Any())
                    {
                        var departmentTextNumber = _departmentSettingsService.GetTextToCallNumberForDepartment(item.EmailSettings.DepartmentId);
                        foreach (var call in calls)
                        {
                            try
                            {
                                // Adding this in here to try and fix the error below with ObjectContext issues.
                                var newCall = CreateNewCallFromCall(call);

                                if (newCall.Dispatches != null && newCall.Dispatches.Any())
                                {
                                    // We've been having this error here:
                                    //      The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
                                    // So I'm wrapping this in a try catch to prevent all calls form being dropped.
                                    var savedCall = _callsService.SaveCall(newCall);
                                    var cqi       = new CallQueueItem();
                                    cqi.Call = savedCall;

                                    cqi.Profiles             = profiles.Values.ToList();
                                    cqi.DepartmentTextNumber = departmentTextNumber;

                                    _queueService.EnqueueCallBroadcast(cqi);
                                }
                            }
                            catch (Exception ex)
                            {
                                result = ex.ToString();
                                Logging.LogException(ex);
                            }
                        }
                    }

                    _departmentsService.SaveDepartmentEmailSettings(emailResult.EmailSettings);

                    _callsService              = null;
                    _queueService              = null;
                    _departmentsService        = null;
                    _callEmailProvider         = null;
                    _userProfileService        = null;
                    _departmentSettingsService = null;
                }
            }

            return(new Tuple <bool, string>(success, result));
        }