Beispiel #1
0
        public async Task <IActionResult> New()
        {
            var model = new NewTemplateModel();

            model.Template = new CallQuickTemplate();

            var priorites = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(DepartmentId);

            model.CallPriorities = new SelectList(priorites, "DepartmentCallPriorityId", "Name", priorites.FirstOrDefault(x => x.IsDefault));


            List <CallType> types = new List <CallType>();

            types.Add(new CallType {
                CallTypeId = 0, Type = "No Type"
            });
            types.AddRange(await _callsService.GetCallTypesForDepartmentAsync(DepartmentId));
            model.CallTypes = new SelectList(types, "Type", "Type");

            return(View(model));
        }
Beispiel #2
0
        public async Task <IActionResult> New()
        {
            var model = new NewProtocolModel();

            model.Protocol = new DispatchProtocol();

            var priorites = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(DepartmentId);

            model.CallPriorities = new SelectList(priorites, "DepartmentCallPriorityId", "Name", priorites.FirstOrDefault(x => x.IsDefault));

            List <CallType> types = new List <CallType>();

            types.Add(new CallType {
                CallTypeId = 0, Type = "No Type"
            });
            types.AddRange(await _callsService.GetCallTypesForDepartmentAsync(DepartmentId));
            model.CallTypes = new SelectList(types, "Type", "Type");

            model.TriggerTypes             = model.TriggerTypesEnum.ToSelectList();
            model.Protocol.CreatedByUserId = UserId;
            model.Protocol.UpdatedByUserId = UserId;

            return(View(model));
        }
Beispiel #3
0
        public async Task <IActionResult> NewCallPriority(NewCallPriorityView model, IFormFile pushfileToUpload, IFormFile iOSPushfileToUpload, IFormFile alertfileToUpload, CancellationToken cancellationToken)
        {
            var priotiries = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(DepartmentId, true);

            if (model.CallPriority.IsDefault && priotiries.Any(x => x.IsDefault && x.DepartmentId == DepartmentId && x.IsDeleted == false))
            {
                model.Message = "ERROR: Can only have 1 default call priorty and there already is a call priority marked as default for your department.";
                return(View(model));
            }

            if (priotiries.Any(x => x.Name == model.CallPriority.Name && x.IsDeleted == false))
            {
                model.Message = "ERROR: Cannot have duplicate Call Priority names.";
                return(View(model));
            }

            if (pushfileToUpload != null && pushfileToUpload.Length > 0)
            {
                var extenion = Path.GetExtension(pushfileToUpload.FileName);

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

                if (extenion != ".mp3")
                {
                    ModelState.AddModelError("pushfileToUpload", string.Format("Audio file type ({0}) is not supported for Push Notifications.", extenion));
                }

                if (pushfileToUpload.Length > 1000000)
                {
                    ModelState.AddModelError("pushfileToUpload", "Android Push Audio file is too large, must be smaller then 1MB.");
                }

                var fileAudioLength = _audioValidatorProvider.GetMp3FileDuration(pushfileToUpload.OpenReadStream());
                if (fileAudioLength == null)
                {
                    ModelState.AddModelError("pushfileToUpload", string.Format("Audio file type ({0}) is not supported for Android Push Notifications. MP3 Files are required.", extenion));
                }
                else if (fileAudioLength != null && fileAudioLength.Value > new TimeSpan(0, 0, 25))
                {
                    ModelState.AddModelError("pushfileToUpload", string.Format("Android Push audio file length is longer then 25 seconds. Android Push notification sounds must be 25 seconds or shorter.", extenion));
                }
            }

            if (iOSPushfileToUpload != null && iOSPushfileToUpload.Length > 0)
            {
                var extenion = Path.GetExtension(iOSPushfileToUpload.FileName);

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

                if (extenion != ".caf")
                {
                    ModelState.AddModelError("iOSPushfileToUpload", string.Format("Audio file type ({0}) is not supported for iOS Push Notifications.", extenion));
                }

                if (iOSPushfileToUpload.Length > 1000000)
                {
                    ModelState.AddModelError("iOSPushfileToUpload", "iOS Push Audio file is too large, must be smaller then 1MB.");
                }

                //var fileAudioLength = await _audioValidatorProvider.GetWavFileDuration(pushfileToUpload.OpenReadStream());
                //if (fileAudioLength == null)
                //	ModelState.AddModelError("iOSPushfileToUpload", string.Format("Audio file type ({0}) is not supported for Push Notifications. CAF Files are required.", extenion));
                //else if (fileAudioLength != null && fileAudioLength.Value > new TimeSpan(0, 0, 25))
                //	ModelState.AddModelError("iOSPushfileToUpload", string.Format("iOS Push audio file length is longer then 25 seconds. iOS Push notification sounds must be 25 seconds or shorter.", extenion));
            }

            if (alertfileToUpload != null && alertfileToUpload.Length > 0)
            {
                var extenion = Path.GetExtension(alertfileToUpload.FileName);

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

                if (extenion != ".wav")
                {
                    ModelState.AddModelError("alertfileToUpload", string.Format("Audio file type ({0}) is not supported for Alert Notifications.", extenion));
                }

                if (alertfileToUpload.Length > 1000000)
                {
                    ModelState.AddModelError("alertfileToUpload", "Push Audio file is too large, must be smaller then 1MB.");
                }

                var fileAudioLength = _audioValidatorProvider.GetWavFileDuration(alertfileToUpload.OpenReadStream());
                if (fileAudioLength == null)
                {
                    ModelState.AddModelError("alertfileToUpload", string.Format("Audio file type ({0}) is not supported for Browser Alert Notifications. WAV Files are required.", extenion));
                }
                else if (fileAudioLength != null && fileAudioLength.Value > new TimeSpan(0, 0, 5))
                {
                    ModelState.AddModelError("alertfileToUpload", string.Format("Browser alert audio file length is longer then 5 seconds. Push notification sounds must be 5 seconds or shorter.", extenion));
                }
            }

            if (String.IsNullOrWhiteSpace(model.CallPriority.Name))
            {
                ModelState.AddModelError("CallPriority_Name", "You must specify a call priority name");
            }

            if (ModelState.IsValid)
            {
                if (alertfileToUpload != null && alertfileToUpload.Length > 0)
                {
                    byte[] uploadedFile = new byte[alertfileToUpload.OpenReadStream().Length];
                    alertfileToUpload.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                    model.CallPriority.ShortNotificationSound = uploadedFile;
                }

                if (pushfileToUpload != null && pushfileToUpload.Length > 0)
                {
                    byte[] uploadedFile = new byte[pushfileToUpload.OpenReadStream().Length];
                    pushfileToUpload.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                    model.CallPriority.PushNotificationSound = uploadedFile;
                }

                if (iOSPushfileToUpload != null && iOSPushfileToUpload.Length > 0)
                {
                    byte[] uploadedFile = new byte[iOSPushfileToUpload.OpenReadStream().Length];
                    iOSPushfileToUpload.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                    model.CallPriority.IOSPushNotificationSound = uploadedFile;
                }

                model.CallPriority.DepartmentId = DepartmentId;

                await _callsService.SaveCallPriorityAsync(model.CallPriority, cancellationToken);

                return(RedirectToAction("Types", "Department", new { Area = "User" }));
            }


            return(View(model));
        }
Beispiel #4
0
        public async Task <ActionResult> Receive(PostmarkInboundMessage message, CancellationToken cancellationToken)
        {
            if (message != null)
            {
                try
                {
                    var mailMessage = new MimeMessage();

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && message.FromFull.Email.Trim() == "*****@*****.**")
                    {
                        return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));
                    }

                    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
                    if (message.ToFull != null)
                    {
                        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 && message.CcFull != null)
                    {
                        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 (type == 0 && message.BccFull != null)
                    {
                        foreach (var email in message.BccFull)
                        {
                            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 = await _departmentSettingsService.GetDepartmentIdForDispatchEmailAsync(emailAddress);

                        if (departmentId.HasValue)
                        {
                            try
                            {
                                var emailSettings = await _departmentsService.GetDepartmentEmailSettingsAsync(departmentId.Value);

                                List <IdentityUser> departmentUsers = await _departmentsService.GetAllUsersForDepartmentAsync(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   = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value, false);
                                }
                                else if (emailSettings.Department == null)
                                {
                                    emailSettings.Department = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value);
                                }

                                var activeCalls = await _callsService.GetLatest10ActiveCallsByDepartmentAsync(emailSettings.Department.DepartmentId);

                                var units = await _unitsService.GetUnitsForDepartmentAsync(emailSettings.Department.DepartmentId);

                                var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(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, priorities);

                                if (call != null && call.CallId <= 0)
                                {
                                    // New Call Dispatch as normal
                                    call.DepartmentId = departmentId.Value;

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

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

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

                                    await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                                else if (call != null && call.CallId > 0)
                                {
                                    // Existing Call, just update
                                    if (!String.IsNullOrWhiteSpace(call.Address) && String.IsNullOrWhiteSpace(call.GeoLocationData))
                                    {
                                        call.GeoLocationData = await _geoLocationProvider.GetLatLonFromAddress(call.Address);
                                    }

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

                                    // If our Dispatch Count changed, i.e. 2nd Alarm to 3rd Alarm, redispatch
                                    if (call.DidDispatchCountChange())
                                    {
                                        var cqi = new CallQueueItem();
                                        cqi.Call                 = savedCall;
                                        cqi.Profiles             = (await _userProfileService.GetAllProfilesForDepartmentAsync(call.DepartmentId)).Select(x => x.Value).ToList();
                                        cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                                        await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);
                                    }

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest(message));
                            }
                        }
                        #endregion Dispatch
                    }
                    else if (type == 2)                     // Email List
                    {
                        #region Distribution Email
                        var list = await _distributionListsService.GetDistributionListByAddressAsync(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(await _fileService.SaveFileAsync(file, cancellationToken));
                                                }
                                            }
                                        }
                                    }
                                    catch { }

                                    var dlqi = new DistributionListQueueItem();
                                    dlqi.List  = list;
                                    dlqi.Users = await _departmentsService.GetAllUsersForDepartmentAsync(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;

                                    await _queueService.EnqueueDistributionListBroadcastAsync(dlqi, cancellationToken);
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogException(ex);
                                    return(BadRequest(message));
                                }
                            }
                            else
                            {
                                return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));
                            }
                        }

                        return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));

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

                        if (departmentGroup != null)
                        {
                            try
                            {
                                var emailSettings = await _departmentsService.GetDepartmentEmailSettingsAsync(departmentGroup.DepartmentId);

                                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 = await _departmentsService.GetDepartmentByIdAsync(departmentGroup.DepartmentId);
                                    }
                                }

                                var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(emailSettings.Department.DepartmentId);

                                var units = await _unitsService.GetAllUnitsForGroupAsync(departmentGroup.DepartmentGroupId);

                                var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(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, priorities);

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

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

                                    var cqi = new CallQueueItem();
                                    cqi.Call     = savedCall;
                                    cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(departmentGroupUsers.Select(x => x.UserId).ToList());

                                    cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                                    await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest());
                            }
                        }
                        #endregion Group Dispatch Email
                    }
                    if (type == 4)                      // Group Message
                    {
                        #region Group Message
                        var departmentGroup = await _departmentGroupsService.GetGroupByMessageEmailCodeAsync(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                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 = await _messageService.SaveMessageAsync(newMessage, cancellationToken);

                                await _messageService.SendMessageAsync(savedMessage, "", departmentGroup.DepartmentId, false, cancellationToken);

                                return(CreatedAtAction(nameof(Receive), new { id = savedMessage.MessageId }, savedMessage));
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest());
                            }
                        }

                        #endregion Group Message
                    }

                    return(BadRequest());
                }
                catch (Exception ex)
                {
                    Framework.Logging.LogException(ex);
                    return(BadRequest(ex.ToString()));
                }
            }
            else
            {
                // If our message was null, we throw an exception
                return(BadRequest("Error parsing Inbound Message, message is null."));
            }
        }
Beispiel #5
0
        public async Task <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 = await _departmentsService.GetAllUsersForDepartmentAsync(item.EmailSettings.DepartmentId, true);

                    var profiles = await _userProfileService.GetAllProfilesForDepartmentAsync(item.EmailSettings.DepartmentId);

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

                        retry++;
                    }

                    foreach (var email in emailResult.Emails)
                    {
                        var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(item.EmailSettings.Department.DepartmentId);

                        var units = await _unitsService.GetUnitsForDepartmentAsync(item.EmailSettings.Department.DepartmentId);

                        var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(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, priorities);

                        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 = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(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 = await _callsService.SaveCallAsync(newCall);

                                    var cqi = new CallQueueItem();
                                    cqi.Call = savedCall;

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

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

                    await _departmentsService.SaveDepartmentEmailSettingsAsync(emailResult.EmailSettings);

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

            return(new Tuple <bool, string>(success, result));
        }
Beispiel #6
0
        public async Task <ActionResult <NewCallPayloadResult> > GetNewCallData()
        {
            var results = new NewCallPayloadResult();

            results.Personnel    = new List <PersonnelInfoResult>();
            results.Groups       = new List <GroupInfoResult>();
            results.Units        = new List <UnitInfoResult>();
            results.Roles        = new List <RoleInfoResult>();
            results.Statuses     = new List <CustomStatusesResult>();
            results.UnitStatuses = new List <UnitStatusCoreResult>();
            results.UnitRoles    = new List <UnitRoleResult>();
            results.Priorities   = new List <CallPriorityResult>();
            results.CallTypes    = new List <CallTypeResult>();

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var groups = await _departmentGroupsService.GetAllDepartmentGroupsForDepartmentAsync(DepartmentId);

            var rolesForUsersInDepartment = await _personnelRolesService.GetAllRolesForUsersInDepartmentAsync(DepartmentId);

            var allRoles = await _personnelRolesService.GetRolesForDepartmentAsync(DepartmentId);

            var allProfiles = await _userProfileService.GetAllProfilesForDepartmentAsync(DepartmentId);

            var allGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);

            var unitTypes = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId);

            var callPriorites = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(DepartmentId);

            var callTypes = await _callsService.GetCallTypesForDepartmentAsync(DepartmentId);


            foreach (var user in users)
            {
                //var profile = _userProfileService.GetProfileByUserId(user.UserId);
                //var group = _departmentGroupsService.GetGroupForUser(user.UserId);

                UserProfile profile = null;
                if (allProfiles.ContainsKey(user.UserId))
                {
                    profile = allProfiles[user.UserId];
                }

                DepartmentGroup group = null;
                if (groups.ContainsKey(user.UserId))
                {
                    group = groups[user.UserId];
                }

                //var roles = _personnelRolesService.GetRolesForUser(user.UserId);

                List <PersonnelRole> roles = null;
                if (rolesForUsersInDepartment.ContainsKey(user.UserId))
                {
                    roles = rolesForUsersInDepartment[user.UserId];
                }

                var result = new PersonnelInfoResult();

                if (profile != null)
                {
                    result.Fnm = profile.FirstName;
                    result.Lnm = profile.LastName;
                    result.Id  = profile.IdentificationNumber;
                    result.Mnu = profile.MobileNumber;
                }
                else
                {
                    result.Fnm = "Unknown";
                    result.Lnm = "Check Profile";
                    result.Id  = "";
                    result.Mnu = "";
                }

                result.Eml = user.Email;
                result.Did = DepartmentId;
                result.Uid = user.UserId.ToString();

                if (group != null)
                {
                    result.Gid = group.DepartmentGroupId;
                    result.Gnm = group.Name;
                }

                result.Roles = new List <string>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        if (role != null)
                        {
                            result.Roles.Add(role.Name);
                        }
                    }
                }

                results.Personnel.Add(result);
            }

            foreach (var group in allGroups)
            {
                var groupInfo = new GroupInfoResult();
                groupInfo.Gid = group.DepartmentGroupId;
                groupInfo.Nme = group.Name;

                if (group.Type.HasValue)
                {
                    groupInfo.Typ = group.Type.Value;
                }

                if (group.Address != null)
                {
                    groupInfo.Add = group.Address.FormatAddress();
                }

                results.Groups.Add(groupInfo);
            }

            foreach (var unit in units)
            {
                var unitResult = new UnitInfoResult();
                unitResult.Uid = unit.UnitId;
                unitResult.Did = DepartmentId;
                unitResult.Nme = unit.Name;
                unitResult.Typ = unit.Type;

                if (!string.IsNullOrWhiteSpace(unit.Type))
                {
                    var unitType = unitTypes.FirstOrDefault(x => x.Type == unit.Type);

                    if (unitType != null)
                    {
                        unitResult.Cid = unitType.CustomStatesId.GetValueOrDefault();
                    }
                }
                else
                {
                    unitResult.Cid = 0;
                }

                if (unit.StationGroup != null)
                {
                    unitResult.Sid = unit.StationGroup.DepartmentGroupId;
                    unitResult.Snm = unit.StationGroup.Name;
                }

                results.Units.Add(unitResult);

                // Add unit roles for this unit
                var roles = await _unitsService.GetRolesForUnitAsync(unit.UnitId);

                foreach (var role in roles)
                {
                    var roleResult = new UnitRoleResult();
                    roleResult.Name       = role.Name;
                    roleResult.UnitId     = role.UnitId;
                    roleResult.UnitRoleId = role.UnitRoleId;

                    results.UnitRoles.Add(roleResult);
                }
            }

            var unitStatuses = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(DepartmentId);

            foreach (var us in unitStatuses)
            {
                var unitStatus = new UnitStatusCoreResult();
                unitStatus.UnitId      = us.UnitId;
                unitStatus.StateType   = (UnitStateTypes)us.State;
                unitStatus.StateTypeId = us.State;
                unitStatus.Type        = us.Unit.Type;
                unitStatus.Timestamp   = us.Timestamp.TimeConverter(department);
                unitStatus.Name        = us.Unit.Name;
                unitStatus.Note        = us.Note;

                if (us.DestinationId.HasValue)
                {
                    unitStatus.DestinationId = us.DestinationId.Value;
                }

                if (us.LocalTimestamp.HasValue)
                {
                    unitStatus.LocalTimestamp = us.LocalTimestamp.Value;
                }

                if (us.Latitude.HasValue)
                {
                    unitStatus.Latitude = us.Latitude.Value;
                }

                if (us.Longitude.HasValue)
                {
                    unitStatus.Longitude = us.Longitude.Value;
                }

                results.UnitStatuses.Add(unitStatus);
            }

            foreach (var role in allRoles)
            {
                var roleResult = new RoleInfoResult();
                roleResult.Rid = role.PersonnelRoleId;
                roleResult.Nme = role.Name;

                results.Roles.Add(roleResult);
            }

            var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(DepartmentId);

            foreach (var customState in customStates)
            {
                if (customState.IsDeleted)
                {
                    continue;
                }

                foreach (var stateDetail in customState.GetActiveDetails())
                {
                    if (stateDetail.IsDeleted)
                    {
                        continue;
                    }

                    var customStateResult = new CustomStatusesResult();
                    customStateResult.Id      = stateDetail.CustomStateDetailId;
                    customStateResult.Type    = customState.Type;
                    customStateResult.StateId = stateDetail.CustomStateId;
                    customStateResult.Text    = stateDetail.ButtonText;
                    customStateResult.BColor  = stateDetail.ButtonColor;
                    customStateResult.Color   = stateDetail.TextColor;
                    customStateResult.Gps     = stateDetail.GpsRequired;
                    customStateResult.Note    = stateDetail.NoteType;
                    customStateResult.Detail  = stateDetail.DetailType;

                    results.Statuses.Add(customStateResult);
                }
            }

            foreach (var priority in callPriorites)
            {
                var priorityResult = new CallPriorityResult();
                priorityResult.Id           = priority.DepartmentCallPriorityId;
                priorityResult.DepartmentId = priority.DepartmentId;
                priorityResult.Name         = priority.Name;
                priorityResult.Color        = priority.Color;
                priorityResult.Sort         = priority.Sort;
                priorityResult.IsDeleted    = priority.IsDeleted;
                priorityResult.IsDefault    = priority.IsDefault;

                results.Priorities.Add(priorityResult);
            }

            if (callTypes != null && callTypes.Any())
            {
                foreach (var callType in callTypes)
                {
                    var type = new CallTypeResult();
                    type.Id   = callType.CallTypeId;
                    type.Name = callType.Type;

                    results.CallTypes.Add(type);
                }
            }


            return(results);
        }