Exemple #1
0
        public async Task <List <NotificationOutcome> > Send(SendPayload payload)
        {
            var pns = new List <Platform>
            {
                Platform.iOS,
                Platform.Android
            };

            return(await Send(payload, pns));
        }
        private void SendAsync(SendPayload payload)
        {
            lock (sendQueue)
            {
                if (sending)
                {
                    sendQueue.Enqueue(payload);
                    return;
                }
                sending = true;
            }

            SendBufferAsync(payload);
        }
        public async Task <SendResponse> Send(SendPayload payload)
        {
            using (HttpResponseMessage response = await _apiHelper.Client.PostAsJsonAsync(_sendEndpointPath, payload))
            {
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsAsync <SendResponse>();

                    return(result);
                }

                throw new Exception(response.ReasonPhrase);
            }
        }
Exemple #4
0
        public async Task <List <NotificationOutcome> > Send(SendPayload payload, List <Platform> pns)
        {
            string tagExpression = "";

            if (payload.Tags != null && payload.Tags.Count > 0)
            {
                foreach (var tag in payload.Tags)
                {
                    tagExpression += tag;
                    tagExpression += "||";
                }

                tagExpression = tagExpression.Substring(0, tagExpression.Length - 2);
            }
            else if (!string.IsNullOrEmpty(payload.TagExpression))
            {
                tagExpression = payload.TagExpression;
            }

            if (!tagExpression.Contains("UserId") && !string.IsNullOrEmpty(payload.UserId))
            {
                if (!string.IsNullOrEmpty(tagExpression))
                {
                    tagExpression += "||";
                }
                tagExpression += $"UserId:{payload.UserId}";
            }

            var outcomes = new List <NotificationOutcome>();

            if (pns.Contains(Platform.iOS))
            {
                var pushMsg = "{\"aps\":{\"alert\":\"" + payload.Message + "\", \"sound\":\"default\"}}";
                var outcome = await _hub.SendAppleNativeNotificationAsync(pushMsg, tagExpression);

                outcomes.Add(outcome);
            }
            if (pns.Contains(Platform.Android))
            {
                var pushMsg = "{\"notification\": {\"body\": \"" + payload.Message + "\", \"sound\" :\"default\" }}";
                var outcome = await _hub.SendGcmNativeNotificationAsync(pushMsg, tagExpression);

                outcomes.Add(outcome);
            }

            return(outcomes);
        }
Exemple #5
0
        public async Task <HttpResponseMessage> Post([FromBody] SendPayload sendPayload)
        {
            HttpStatusCode             ret      = HttpStatusCode.InternalServerError;
            List <NotificationOutcome> outcomes = null;
            AzureNotificationHub       hub      = await _dbRepo.GetAzureNotificationHubEndpoint(sendPayload.AppId);

            if (string.IsNullOrEmpty(hub.Endpoint) && string.IsNullOrEmpty(hub.HubName))
            {
                throw new Exception($"Unable to find an enpoint for appId = '{sendPayload.AppId}'");
            }

            var _nhRepo = new NotificationHubRepository(hub.Endpoint, hub.HubName);

            if (!string.IsNullOrEmpty(sendPayload.UserId))
            {
                var pns = await _dbRepo.GetPns(sendPayload.AppId, sendPayload.UserId);

                outcomes = await _nhRepo.Send(sendPayload, pns);
            }
            else
            {
                outcomes = await _nhRepo.Send(sendPayload);
            }

            if (outcomes != null)
            {
                ret = HttpStatusCode.OK;

                foreach (var outcome in outcomes)
                {
                    if ((outcome.State == NotificationOutcomeState.Abandoned) ||
                        (outcome.State == NotificationOutcomeState.Unknown))
                    {
                        ret = HttpStatusCode.InternalServerError;
                        break;
                    }
                }
            }

            return(Request.CreateResponse(ret, "{\"result\":\"OK\"}"));
        }
        private void SendBufferAsync(SendPayload payload)
        {
            try
            {
                socket.BeginSend(payload.buffer.data, 0, payload.buffer.size, SocketFlags.None, out SocketError error, OnSend, payload);

                if (CheckError(error))
                {
                    Log.Error("SocketError received on SendAsync: " + error);
                    if (payload.packet is ITokenPacket token && !token.TokenResponse)
                    {
                        tokenCallbacks.TryRemove(token.Token, out var dummy);
                    }
                    Disconnect();
                    return;
                }
            }
            catch (ObjectDisposedException e)
            {
                Disconnect();
                return;
            }
        }
        private async Task MessageRecieved(object sender, BasicDeliverEventArgs e)
        {
            ReadOnlyMemory <byte> body = null;

            try
            {
                body = e.Body;

                var message = JsonSerializer.Deserialize <SendEmailMessage>(body.Span);

                string[] recipients = new string[] { };
                if (message.To != null)
                {
                    recipients = message.To.Select(recipient => recipient?.Email).ToArray();
                }

                _logger.LogInformation(
                    $"Recieved message to send to recipients: { string.Join(", ", recipients) }" +
                    $" with subject: \"{ message.Subject }\", with { message.Attachments?.Count ?? 0 } attachments");


                if (message.EventPayload == null)
                {
                    message.Payload = new EmailPayload();
                }

                var payload = new SendPayload
                {
                    Messages    = new[] { message },
                    SandboxMode = _sandboxMode
                };

                for (var i = 0; i < _retriesCount; i++)
                {
                    _logger.LogInformation($"Sending email { message.Payload.Id } { i + 1 }/{ _retriesCount }");

                    try
                    {
                        var response = await _sendEndpoint.Send(payload);

                        _logger.LogInformation("Response:\n" + JsonSerializer.Serialize(response));
                        break;
                    }
                    catch (Exception exc)
                    {
                        _logger.LogError(exc, exc.Message);
                        await Task.Delay(_retryDelay);

                        if (i >= _retriesCount - 1)
                        {
                            var statusUpdateMessage = new UpdateStoredEmailStatusMessage
                            {
                                ErrorInfo    = "SendWorker unable to send message to MailJet",
                                EventPayload = new EmailPayload {
                                    Id = message.Payload.Id, Trackable = true
                                },
                                Status     = MailEventType.bounce,
                                RecievedAt = DateTime.Now
                            };

                            _channel.QueueDeclare(_statusUpdateQueueId, true, false, false, null);
                            var serializedMessage = JsonSerializer.Serialize(statusUpdateMessage);
                            var statusUpdateBody  = Encoding.UTF8.GetBytes(serializedMessage);
                            var properties        = _channel.CreateBasicProperties();
                            properties.Persistent = true;
                            _channel.BasicPublish("", _statusUpdateQueueId, false, properties, statusUpdateBody);
                        }

                        continue;
                    }
                }
            }
            finally
            {
                _logger.LogInformation("Free message from queue");
                _channel.BasicAck(e.DeliveryTag, false);
            }
        }
        public async Task <SendResponse> Send([FromBody] SendPayload sendPayload)
        {
            _logger.LogInformation($"Recieved sendPayload SandboxMode = { sendPayload.SandboxMode }, with { sendPayload.Messages.Count } messages");

            SendResponse result = new SendResponse {
                Messages = new List <MessageSendDetails>()
            };

            string baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

            var hubUrl = baseUrl.TrimEnd('/') + EmailsHub.HubUrl;

            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(hubUrl)
                                .Build();

            await hubConnection.StartAsync();

            foreach (var email in sendPayload.Messages)
            {
                _logger.LogInformation($"Recieved email: Subject: \"{ email.Subject }\", " +
                                       $"From { email.From.Email } ({ email.From.Name }), " +
                                       $"To: { string.Join(", ", email.To.Select(recipient => $"{ recipient.Email } ({ recipient.Name })")) }, " +
                                       $"Text: { email.TextPart }, " +
                                       $"HTML: { email.HTMLPart }, " +
                                       $"With { email.InlinedAttachments?.Count ?? 0 } inlined and { email.Attachments?.Count ?? 0 } not inlined attachments, " +
                                       $"CustomId: { email.CustomId }, " +
                                       $"Payload: { email.EventPayload }");

                await hubConnection.SendAsync("EmailRecieved", email);

                var messageDetail = new MessageSendDetails
                {
                    Status = "success",
                    To     = new List <SendDetails>()
                };

                foreach (var recipient in email.To)
                {
                    var emailGuid = Guid.NewGuid().ToString();
                    var messageId = new Random().Next(int.MaxValue);

                    var eventTime = DateTimeOffset.Now.ToUnixTimeSeconds();

                    var sendDetails = new SendDetails
                    {
                        Email       = recipient.Email,
                        MessageID   = messageId,
                        MessageUUID = emailGuid,
                        MessageHref = "https://some.url.must.be.here.at.production.that.contains/MessageUUID"
                    };

                    await _eventsRecieverEndpoint.SendEvent <MailSentEvent>(new MailSentEvent
                    {
                        Time             = eventTime,
                        EmailAddress     = recipient.Email,
                        MessageGuid      = emailGuid,
                        MessageId        = messageId,
                        CustomId         = email.CustomId ?? "",
                        Payload          = email.EventPayload,
                        MailjetMessageId = messageId.ToString(),
                        CustomCampaign   = "",
                        SmtpReply        = "sent (250 2.0.0 OK 4242424242 fa5si855896wjc.199 - gsmtp)"
                    });

                    messageDetail.To.Add(sendDetails);
                }

                result.Messages.Add(messageDetail);
            }

            return(result);
        }