Beispiel #1
0
        public async Task <BaseResponse <MailgunMessage> > update(MailgunMessageRequest messageRequest)
        {
            var message = _mapper.Map <MailgunMessage>(messageRequest);

            MailgunMessage messageFound = null;

            var finalResponse = BaseResponseFactory <MailgunMessage> .CreateDefaultBaseResponse();

            var filter = false;

            if (messageRequest.Token.NotEmpty())
            {
                messageFound = await _context.MailgunMessages.FirstOrDefaultAsync(e => e.Token == messageRequest.Token);

                if (messageFound == null)
                {
                    finalResponse.Errors.Add(new ApiError {
                        description = "Token not found."
                    });
                }

                filter = true;
            }

            if (messageRequest.MessageId.NotEmpty())
            {
                messageFound = await _context.MailgunMessages.FirstOrDefaultAsync(e => e.MessageId == messageRequest.MessageId);

                if (messageFound == null)
                {
                    finalResponse.Errors.Add(new ApiError {
                        description = "MessageId not found."
                    });
                }

                filter = true;
            }

            if (messageFound != null)
            {
                _context.Attach(messageFound).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                finalResponse.Data.Add(messageFound);
            }

            if (!filter)
            {
                finalResponse.Errors.Add(new ApiError {
                    description = "inform either MessageId or Token to delete."
                });
            }

            return(finalResponse);
        }
Beispiel #2
0
        public async Task <BaseResponse <MailgunMessage> > create(MailgunMessageRequest messageRequest)
        {
            var response = BaseResponseFactory <MailgunMessage> .CreateDefaultBaseResponse();

            messageRequest.RemoteIpAddress = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            var message = _mapper.Map <MailgunMessage>(messageRequest);

            var tokenFound = await _context.MailgunMessages.FirstOrDefaultAsync(e => e.Token == message.Token);

            if (tokenFound != null)
            {
                response.Errors.Add(new ApiError {
                    description = "Token already used."
                });
                return(response);
            }

            var mailgunApiToken = Encoding.ASCII.GetBytes(_options.Value.mailgunApiToken);
            var hash            = new HMACSHA256(mailgunApiToken);

            if (BitConverter.ToString(hash.ComputeHash(Encoding.ASCII.GetBytes(message.Timestamp + message.Token))).Replace("-", "").ToLower().Equals(message.Signature))
            {
                message.Valid = true;
            }

            message.Validated = DateTime.Now;

            await _context.AddAsync(message);

            await _context.SaveChangesAsync();

            response.Data.Add(message);

            return(response);
        }
Beispiel #3
0
        public async Task <BaseResponse <MailgunMessage> > delete(MailgunMessageRequest messageRequest)
        {
            var message = _mapper.Map <MailgunMessage>(messageRequest);

            MailgunMessage messageFound = null;

            var finalResponse = BaseResponseFactory <MailgunMessage> .CreateDefaultBaseResponse();

            IList <ApiError> errors = new List <ApiError>();

            var filter = false;

            if (messageRequest.Token.NotEmpty())
            {
                messageFound = await _context.MailgunMessages.FirstOrDefaultAsync(e => e.Token == message.Token);

                if (messageFound == null)
                {
                    errors.Add(new ApiError {
                        description = "Token not found."
                    });
                }

                filter = true;
            }

            if (messageRequest.MessageId.NotEmpty())
            {
                messageFound = await _context.MailgunMessages.FirstOrDefaultAsync(e => e.Id == Guid.Parse(message.MessageId));

                if (messageFound == null)
                {
                    errors.Add(new ApiError {
                        description = "MessageId not found."
                    });
                }

                filter = true;
            }

            if (messageFound != null)
            {
                _context.Remove(messageFound);
                await _context.SaveChangesAsync();

                finalResponse.Data.Add(messageFound);
            }

            if (!filter)
            {
                errors.Add(new ApiError {
                    description = "inform either MessageId or Token to delete."
                });
            }

            if (errors.Any())
            {
                finalResponse.Errors = errors.ToArray();
            }

            return(finalResponse);
        }
        private async Task <BaseResponse <BaseMessage> > import(BaseMessage message)
        {
            var response = BaseResponseFactory <BaseMessage> .CreateDefaultBaseResponse();

            using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                if (message == null)
                {
                    _logger.LogInformation("Parameter is null");
                    response.Errors.Add(new ApiError {
                        description = "Parameter is null"
                    });
                    return(response);
                }

                if (!message.Valid)
                {
                    _logger.LogInformation("Message {Id} is not valid by provider, so we cannot process it", message.Id);
                    response.Errors.Add(new ApiError {
                        description = "Message is not valid by provider, so we cannot process it"
                    });
                    return(response);
                }

                if (message is MailgunMessage)
                {
                    var mailgunMessage = (MailgunMessage)message;

                    Mail newMail = null;

                    try
                    {
                        newMail = await _context.Mails
                                  .AsNoTracking()
                                  .FirstOrDefaultAsync(e => e.BaseMessageId == message.Id);

                        if (newMail == null)
                        {
                            newMail = new Mail(message);
                            await _context.Mails.AddAsync(newMail);

                            await _context.SaveChangesAsync();
                        }

                        if (newMail.Retries <= 0)
                        {
                            _logger.LogError("Too many reprocessed");
                            return(response);
                        }

                        bool recipientEmpty = mailgunMessage.Recipient != null?mailgunMessage.Recipient.Equals(string.Empty) : true;

                        bool toEmpty = mailgunMessage.To != null?
                                       mailgunMessage.To.Equals(string.Empty) : true;

                        if (recipientEmpty && toEmpty)
                        {
                            _logger.LogInformation("recipient and to email headers are empty");
                            response.Errors.Add(new ApiError {
                                description = "recipient and to email headers are empty"
                            });
                            return(response);
                        }

                        var toRecipient = !recipientEmpty ? new MailAddress(mailgunMessage.Recipient) : new MailAddress(mailgunMessage.To);
                        var domainFound = await _domainService.get(toRecipient.Host);

                        if (domainFound == null)
                        {
                            var errorMessage = string.Format("message id: {0} the domain {1} was not found", message.Id, toRecipient.Host);
                            await SetMailError(newMail, errorMessage);

                            _logger.LogError(errorMessage);
                            response.Errors.Add(new ApiError {
                                description = "Domain not found"
                            });
                            return(response);
                        }

                        var mailboxFound = await _mailboxService.GetMailbox(toRecipient.Address);

                        if (mailboxFound == null)
                        {
                            var newMailbox = _mailboxService.CreateDefaultMailbox(toRecipient, domainFound);
                            mailboxFound = await _mailboxService.CreateMailbox(newMailbox);
                        }

                        var mail = _mapper.Map <Mail>(mailgunMessage);

                        mail.Id            = newMail.Id;
                        mail.BaseMessageId = newMail.BaseMessageId;

                        _context.Entry(newMail).State = EntityState.Detached;

                        if (mail.Attachments.NotEmpty())
                        {
                            var jsonAttachments = mail.Attachments.Replace("\\\"", "\"");
                            var attachments     = JsonConvert.DeserializeObject <MailAttachment[]>(jsonAttachments);
                            ICollection <Task <MailAttachment> > getFiles = new List <Task <MailAttachment> >();

                            attachments.ToList().ForEach(async e =>
                            {
                                e        = await _mailgunAttachment.get(e);
                                e.MailId = mail.Id;
                                e.Id     = Guid.NewGuid();
                                await _context.AddAsync(e);
                            });

                            await _context.SaveChangesAsync();

                            mail.MailAttachmentsJobStatus = JobStats.Done;
                        }

                        mail.ErrorMessage = string.Empty;
                        mail.ErrorDate    = null;
                        mail.NextRetry    = null;

                        mail.JobStats = JobStats.Done;
                        mail.MailAttachmentsJobStatus = JobStats.Done;

                        _context.Mails.Update(mail);

                        await _context.SaveChangesAsync();

                        transaction.Commit();
                    }
                    catch (Exception exception)
                    {
                        transaction.Rollback();

                        var errorMessage = string.Format("{0} - {1}", exception.Message, exception.StackTrace);
                        await SetMailError(newMail, errorMessage);

                        _logger.LogError(errorMessage);
                        response.Errors.Add(new ApiError {
                            description = errorMessage
                        });
                    }
                }
            }

            return(response);
        }