public void EnqueueDistributionList(DistributionListQueueItem distributionListQueue)
        {
            string serializedObject = String.Empty;

            try
            {
                serializedObject = ObjectSerialization.Serialize(distributionListQueue);

                // We are limited to 256KB in azure queue messages
                var size = ASCIIEncoding.Unicode.GetByteCount(serializedObject);
                if (size > 220000)
                {
                    distributionListQueue.Users = null;
                    serializedObject            = ObjectSerialization.Serialize(distributionListQueue);
                }

                // If were still too big, strip out some attachments
                if (size > 220000)
                {
                    distributionListQueue.Message.Attachments = null;
                    serializedObject = ObjectSerialization.Serialize(distributionListQueue);
                }
            }
            catch { }

            // If we get an Exception, i.e. OutOfMemmory, lets just strip out the heavy data and try.
            if (String.IsNullOrWhiteSpace(serializedObject))
            {
                distributionListQueue.Users = null;
                distributionListQueue.Message.Attachments = null;
                serializedObject = ObjectSerialization.Serialize(distributionListQueue);
            }

            SendMessage(ServiceBusConfig.EmailBroadcastQueueName, serializedObject);
        }
Esempio n. 2
0
        public async Task <bool> Process(DistributionListQueueItem item)
        {
            bool success = true;

            if (Config.SystemBehaviorConfig.IsAzure)
            {
                //ProcessQueueMessage(_client.Receive());

                var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete       = false
                };

                // Register the function that will process messages
                _client.RegisterMessageHandler(ProcessQueueMessage, messageHandlerOptions);
            }
            else
            {
                return(await ProcessDistributionListQueueItem(item));
            }

            _queueService = null;
            return(false);
        }
Esempio n. 3
0
        private async Task OnDistributionListQueueReceived(DistributionListQueueItem dlqi)
        {
            _logger.LogInformation($"{Name}: Distribution List Queue Received with a message id of {dlqi.Message.MessageID}, starting processing...");
            await DistributionListLogic.ProcessDistributionListQueueItem(dlqi);

            _logger.LogInformation($"{Name}: Finished processing of distribution message {dlqi.Message.MessageID}.");
        }
Esempio n. 4
0
        public async Task <Tuple <bool, string> > ProcessQueueMessage(Message message, CancellationToken token)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            //message.Complete();
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }

                        await ProcessDistributionListQueueItem(dlqi);
                    }

                    try
                    {
                        if (success)
                        {
                            await _client.CompleteAsync(message.SystemProperties.LockToken);
                        }
                        //message.Complete();
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                    Logging.LogException(ex);
                    //message.Abandon();
                    await _client.DeadLetterAsync(message.SystemProperties.LockToken);
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 5
0
        public async Task <Tuple <bool, string> > Process(DistributionListQueueItem item)
        {
            bool   success = true;
            string result  = "";

            if (item?.List != null)
            {
                if (item.List.Type == null || item.List.Type == (int)DistributionListTypes.External)
                {
                    try
                    {
                        var emails = _distributionListProvider.GetNewMessagesFromMailbox(item.List);

                        if (emails != null && emails.Count > 0)
                        {
                            var listMembers = await _distributionListsService.GetAllListMembersByListIdAsync(item.List.DistributionListId);

                            foreach (var email in emails)
                            {
                                foreach (var member in listMembers)
                                {
                                    IdentityUser membership = null;
                                    if (member.User != null && member.User != null)
                                    {
                                        membership = member.User;
                                    }
                                    else
                                    {
                                        membership = _usersService.GetMembershipByUserId(member.UserId);
                                    }

                                    if (membership != null && !String.IsNullOrWhiteSpace(membership.Email))
                                    {
                                        _emailService.SendDistributionListEmail(email, membership.Email, item.List.Name, $"Resgrid ({item.List.Name}) List", $"{item.List.EmailAddress}@{Config.InboundEmailConfig.ListsDomain}");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        success = false;
                        result  = ex.ToString();
                    }
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 6
0
        public static Tuple <bool, string> ProcessQueueMessage(BrokeredMessage message)
        {
            bool   success = true;
            string result  = "";

            if (message != null)
            {
                try
                {
                    var body = message.GetBody <string>();

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(body);
                        }
                        catch (Exception ex)
                        {
                            success = false;
                            result  = "Unable to parse message body Exception: " + ex.ToString();
                            message.Complete();
                        }

                        ProcessDistributionListQueueItem(dlqi);
                    }

                    try
                    {
                        if (success)
                        {
                            message.Complete();
                        }
                    }
                    catch (MessageLockLostException)
                    {
                    }
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                    Logging.LogException(ex);
                    message.Abandon();
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Esempio n. 7
0
        public void Process(DistributionListQueueItem item)
        {
            bool success = true;

            if (Config.SystemBehaviorConfig.IsAzure)
            {
                ProcessQueueMessage(_client.Receive());
            }
            else
            {
                ProcessDistributionListQueueItem(item);
            }

            _queueService = null;
        }
Esempio n. 8
0
        public void EnqueueDistributionListBroadcast(DistributionListQueueItem dlqi)
        {
            if (Config.SystemBehaviorConfig.IsAzure)
            {
                _outboundQueueProvider.EnqueueDistributionList(dlqi);
            }
            else
            {
                QueueItem item = new QueueItem();
                item.QueueType = (int)QueueTypes.DistributionListBroadcast;
                item.SourceId  = dlqi.Message.MessageID.ToString();
                item.QueuedOn  = DateTime.UtcNow;

                _queueItemsRepository.SaveOrUpdate(item);
            }
        }
Esempio n. 9
0
        public void EnqueueDistributionList(DistributionListQueueItem distributionListQueue)
        {
            if (SystemBehaviorConfig.ServiceBusType == ServiceBusTypes.Rabbit)
            {
                _rabbitOutboundQueueProvider.EnqueueDistributionList(distributionListQueue);
                return;
            }

            VerifyAndCreateClients();
            string serializedObject = String.Empty;

            try
            {
                serializedObject = ObjectSerialization.Serialize(distributionListQueue);

                // We are limited to 256KB in azure queue messages
                var size = ASCIIEncoding.Unicode.GetByteCount(serializedObject);
                if (size > 220000)
                {
                    distributionListQueue.Users = null;
                    serializedObject            = ObjectSerialization.Serialize(distributionListQueue);
                }

                // If were still too big, strip out some attachments
                if (size > 220000)
                {
                    distributionListQueue.Message.Attachments = null;
                    serializedObject = ObjectSerialization.Serialize(distributionListQueue);
                }
            }
            catch { }

            // If we get an Exception, i.e. OutOfMemmory, lets just strip out the heavy data and try.
            if (String.IsNullOrWhiteSpace(serializedObject))
            {
                distributionListQueue.Users = null;
                distributionListQueue.Message.Attachments = null;
                serializedObject = ObjectSerialization.Serialize(distributionListQueue);
            }

            BrokeredMessage message = new BrokeredMessage(serializedObject);

            message.MessageId = string.Format("{0}|{1}", distributionListQueue.Message.MessageID, distributionListQueue.List.DistributionListId);

            SendMessage(_distributionListClient, message);
        }
Esempio n. 10
0
        public async Task <bool> EnqueueDistributionListBroadcastAsync(DistributionListQueueItem dlqi, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Config.SystemBehaviorConfig.IsAzure)
            {
                return(await _outboundQueueProvider.EnqueueDistributionList(dlqi));
            }
            else
            {
                QueueItem item = new QueueItem();
                item.QueueType = (int)QueueTypes.DistributionListBroadcast;
                item.SourceId  = dlqi.Message.MessageID.ToString();
                item.QueuedOn  = DateTime.UtcNow;

                await _queueItemsRepository.SaveOrUpdateAsync(item, cancellationToken);
            }

            return(true);
        }
Esempio n. 11
0
        public static async Task <bool> ProcessDistributionListQueueItem(DistributionListQueueItem dlqi)
        {
            var emailService             = Bootstrapper.GetKernel().Resolve <IEmailService>();
            var distributionListsService = Bootstrapper.GetKernel().Resolve <IDistributionListsService>();
            var fileService = Bootstrapper.GetKernel().Resolve <IFileService>();

            if (dlqi != null && dlqi.List != null && dlqi.Message != null)
            {
                // If we didn't get any profiles chances are the message size was too big for Azure, get selected profiles now.
                if (dlqi.Users == null)
                {
                    var departmentsService = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                    dlqi.Users = await departmentsService.GetAllUsersForDepartmentAsync(dlqi.List.DepartmentId);
                }

                var mailMessage = new MimeMessage();
                var builder     = new BodyBuilder();


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

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

                mailMessage.Subject = dlqi.Message.Subject;

                //mailMessage.From = new EmailAddress($"{dlqi.List.EmailAddress}@{Config.InboundEmailConfig.ListsDomain}", $"Resgrid ({dlqi.List.Name}) List");

                try
                {
                    if (dlqi.FileIds != null && dlqi.FileIds.Any())
                    {
                        foreach (var fileId in dlqi.FileIds)
                        {
                            var file = await fileService.GetFileByIdAsync(fileId);

                            // create an image attachment for the file located at path
                            var attachment = new MimePart(file.FileType)
                            {
                                ContentObject           = new ContentObject(new MemoryStream(file.Data), ContentEncoding.Default),
                                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                                ContentTransferEncoding = ContentEncoding.Base64,
                                FileName = file.FileName
                            };

                            builder.Attachments.Add(attachment);

                            //mailMessage.Attachments.Add(file.Data, file.FileName, file.ContentId, file.FileType,
                            //	new HeaderCollection(),	NewAttachmentOptions.None, MailTransferEncoding.None);

                            fileService.DeleteFileAsync(file);
                        }
                    }
                }
                catch { }

                mailMessage.Body = builder.ToMessageBody();

                if (dlqi.List.Members == null)
                {
                    dlqi.List = await distributionListsService.GetDistributionListByIdAsync(dlqi.List.DistributionListId);
                }

                foreach (var member in dlqi.List.Members)
                {
                    try
                    {
                        var user = dlqi.Users.FirstOrDefault(x => x.UserId == member.UserId);

                        if (user != null && !String.IsNullOrWhiteSpace(user.Email))
                        {
                            emailService.SendDistributionListEmail(mailMessage, user.Email, dlqi.List.Name, dlqi.List.Name, $"{dlqi.List.EmailAddress}@lists.resgrid.com");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogException(ex);
                    }
                }
            }

            emailService             = null;
            distributionListsService = null;
            fileService = null;

            return(true);
        }
Esempio n. 12
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.")
                });
            }
        }
Esempio n. 13
0
        private async Task StartMonitoring()
        {
            if (SystemBehaviorConfig.ServiceBusType == ServiceBusTypes.Rabbit)
            {
                var callQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                callQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CallQueueItem cqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqi = ObjectSerialization.Deserialize <CallQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqi != null)
                            {
                                if (CallQueueReceived != null)
                                {
                                    await CallQueueReceived.Invoke(cqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var messageQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                messageQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        MessageQueueItem mqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            mqi = ObjectSerialization.Deserialize <MessageQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (mqi != null)
                            {
                                if (MessageQueueReceived != null)
                                {
                                    await MessageQueueReceived.Invoke(mqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var distributionListQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                distributionListQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        DistributionListQueueItem dlqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            dlqi = ObjectSerialization.Deserialize <DistributionListQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (dlqi != null)
                            {
                                if (DistributionListQueueReceived != null)
                                {
                                    await DistributionListQueueReceived.Invoke(dlqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var notificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                notificationQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        NotificationItem ni = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            ni = ObjectSerialization.Deserialize <NotificationItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (ni != null)
                            {
                                if (NotificationQueueReceived != null)
                                {
                                    await NotificationQueueReceived.Invoke(ni);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var shiftNotificationQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                shiftNotificationQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        ShiftQueueItem sqi = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            sqi = ObjectSerialization.Deserialize <ShiftQueueItem>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (sqi != null)
                            {
                                if (ShiftNotificationQueueReceived != null)
                                {
                                    await ShiftNotificationQueueReceived.Invoke(sqi);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var cqrsEventQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                cqrsEventQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CqrsEvent cqrs = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqrs = ObjectSerialization.Deserialize <CqrsEvent>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqrs != null)
                            {
                                if (CqrsEventQueueReceived != null)
                                {
                                    await CqrsEventQueueReceived.Invoke(cqrs);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };

                var paymentEventQueueReceivedConsumer = new EventingBasicConsumer(_channel);
                paymentEventQueueReceivedConsumer.Received += async(model, ea) =>
                {
                    if (ea != null && ea.Body.Length > 0)
                    {
                        CqrsEvent cqrs = null;
                        try
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body.ToArray());
                            cqrs = ObjectSerialization.Deserialize <CqrsEvent>(message);
                        }
                        catch (Exception ex)
                        {
                            _channel.BasicNack(ea.DeliveryTag, false, false);
                            Logging.LogException(ex, Encoding.UTF8.GetString(ea.Body.ToArray()));
                        }

                        try
                        {
                            if (cqrs != null)
                            {
                                if (PaymentEventQueueReceived != null)
                                {
                                    await PaymentEventQueueReceived.Invoke(cqrs);

                                    _channel.BasicAck(ea.DeliveryTag, false);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                            if (RetryQueueItem(ea, ex))
                            {
                                _channel.BasicAck(ea.DeliveryTag, false);
                            }
                            else
                            {
                                _channel.BasicNack(ea.DeliveryTag, false, true);
                            }
                        }
                    }
                };


                String callQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.CallBroadcastQueueName),
                    autoAck: false,
                    consumer: callQueueReceivedConsumer);

                String messageQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.MessageBroadcastQueueName),
                    autoAck: false,
                    consumer: messageQueueReceivedConsumer);

                String distributionListQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.EmailBroadcastQueueName),
                    autoAck: false,
                    consumer: distributionListQueueReceivedConsumer);

                String notificationQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.NotificaitonBroadcastQueueName),
                    autoAck: false,
                    consumer: notificationQueueReceivedConsumer);

                String shiftNotificationQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.ShiftNotificationsQueueName),
                    autoAck: false,
                    consumer: shiftNotificationQueueReceivedConsumer);

                String cqrsEventQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.SystemQueueName),
                    autoAck: false,
                    consumer: cqrsEventQueueReceivedConsumer);

                String paymentEventQueueReceivedConsumerTag = _channel.BasicConsume(
                    queue: SetQueueNameForEnv(ServiceBusConfig.PaymentQueueName),
                    autoAck: false,
                    consumer: paymentEventQueueReceivedConsumer);
            }
        }