예제 #1
0
        internal async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                if (httpContext.Request.Method == "GET")
                {
                    var webhook = WebhookParser.ParseQuery <T>(httpContext.Request.Query);
                    _handler(webhook);
                }
                else if (httpContext.Request.Method == "POST")
                {
                    var webhook = await WebhookParser.ParseWebhookAsync <T>(httpContext.Request.Body, httpContext.Request.ContentType);

                    _handler(webhook);
                }
                httpContext.Response.StatusCode = 204;
            }
            catch (Exception)
            {
                httpContext.Response.StatusCode = 500;
            }
            if (_invokeNext)
            {
                await _next(httpContext);
            }
        }
예제 #2
0
        public async Task <IActionResult> DeliveryReceipt()
        {
            var dlr = WebhookParser.ParseQuery <DeliveryReceipt>(Request.Query);

            Console.WriteLine($"Delivery receipt received for messages {dlr.MessageId} at {dlr.MessageTimestamp}");
            return(NoContent());
        }
예제 #3
0
        public IActionResult InboundSms()
        {
            var sms = WebhookParser.ParseQuery <InboundSms>(Request.Query);

            Console.WriteLine($"SMS Received with message: {sms.Text}");
            return(NoContent());
        }
예제 #4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var parser       = new WebhookParser();
            var inboundEmail = parser.ParseInboundEmailWebhook(req.Body);

            log.LogInformation($"EmailForward received new email from {inboundEmail.From.Email}");

            double score = 0.0;

            if (!string.IsNullOrEmpty(inboundEmail.SpamScore))
            {
                score = double.Parse(inboundEmail.SpamScore);
                if (score >= 5.0)
                {
                    log.LogInformation($"Discarding email due to spam score of {score}");
                    return(new OkObjectResult("EmailForward discarded email due to spam!"));
                }
            }

            string response = await ForwardEmail(inboundEmail, score, log);

            if (string.IsNullOrEmpty(response))
            {
                log.LogError($"EmailForward FAILED");
                return(new OkObjectResult("EmailForward failed to send email!"));
            }

            log.LogInformation($"EmailForward successfully forwarded email {response}");
            return(new OkObjectResult($"EmailForward successfully forwarded email {response}"));
        }
예제 #5
0
        public async Task <IActionResult> Recording()
        {
            var record = await WebhookParser.ParseWebhookAsync <Record>(Request.Body, Request.ContentType);

            Console.WriteLine($"Record event received on webhook - URL: {record?.RecordingUrl}");
            return(StatusCode(204));
        }
예제 #6
0
        public async Task <IActionResult> Email()
        {
            var          parser       = new WebhookParser();
            InboundEmail inboundEmail = parser.ParseInboundEmailWebhook(Request.Body);
            await _messageSink.ProcessMessageAsync(CreateMessage(inboundEmail));

            return(Ok());
        }
예제 #7
0
        public async Task InboundEmailWithAttachmentsAsync()
        {
            using (var fileStream = File.OpenRead("InboudEmailTestData/email_with_attachments.txt"))
            {
                var parser       = new WebhookParser();
                var inboundEmail = await parser.ParseInboundEmailWebhookAsync(fileStream).ConfigureAwait(false);

                inboundEmail.ShouldNotBeNull();

                inboundEmail.Attachments.ShouldNotBeNull();
                inboundEmail.Attachments.Length.ShouldBe(2);
                inboundEmail.Attachments[0].ContentId.ShouldBeNull();
                inboundEmail.Attachments[0].ContentType.ShouldBe("image/jpeg");
                inboundEmail.Attachments[0].FileName.ShouldBe("001.jpg");
                inboundEmail.Attachments[0].Id.ShouldBe("attachment2");
                inboundEmail.Attachments[0].Name.ShouldBe("001.jpg");
                inboundEmail.Attachments[1].ContentId.ShouldBe("[email protected]");
                inboundEmail.Attachments[1].ContentType.ShouldBe("image/png");
                inboundEmail.Attachments[1].FileName.ShouldBe("image001.png");
                inboundEmail.Attachments[1].Id.ShouldBe("attachment1");
                inboundEmail.Attachments[1].Name.ShouldBe("image001.png");

                inboundEmail.Dkim.ShouldBe("{@hotmail.com : pass}");

                inboundEmail.To[0].Email.ShouldBe("*****@*****.**");
                inboundEmail.To[0].Name.ShouldBe("API test user");

                inboundEmail.Cc.Length.ShouldBe(0);

                inboundEmail.From.Email.ShouldBe("*****@*****.**");
                inboundEmail.From.Name.ShouldBe("Test User");

                inboundEmail.SenderIp.ShouldBe("40.92.19.62");

                inboundEmail.SpamReport.ShouldBeNull();

                inboundEmail.Envelope.From.ShouldBe("*****@*****.**");
                inboundEmail.Envelope.To.Length.ShouldBe(1);
                inboundEmail.Envelope.To.ShouldContain("*****@*****.**");

                inboundEmail.Subject.ShouldBe("Test #1");

                inboundEmail.SpamScore.ShouldBeNull();

                inboundEmail.Charsets.Except(new[]
                {
                    new KeyValuePair <string, Encoding>("to", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("filename", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("html", Encoding.ASCII),
                    new KeyValuePair <string, Encoding>("subject", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("from", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("text", Encoding.ASCII),
                }).Count().ShouldBe(0);

                inboundEmail.Spf.ShouldBe("pass");
            }
        }
예제 #8
0
        public async Task PostAsync()
        {
            // Personally, I don't like just blindly passing the body of the request to be parsed here. It makes integration testing difficult.
            // Newtonsoft JSON is also many many times slower than the new System.Text.JsonSerializer.
            // However, this is what's documented in the Vonage SDK, so this is what we'll use.
            // https://github.com/Vonage/vonage-dotnet-sdk#post-2
            var dlr = await WebhookParser.ParseWebhookAsync <DeliveryReceipt>(Request.Body, Request.ContentType);

            await _donorService.HandleDlr(dlr);
        }
        public async Task <IActionResult> AdvancedInsights()
        {
            var insights = await WebhookParser.ParseWebhookAsync <AdvancedInsightsResponse>
                               (Request.Body, Request.ContentType);

            Console.WriteLine($"Advanced insights received: {insights.RequestId} " +
                              $"that number's carrier is {insights.CurrentCarrier.Name} " +
                              $"and it's ported status is: {insights.Ported}");
            return(NoContent());
        }
예제 #10
0
        public async Task <IActionResult> OnInput()
        {
            var input = await WebhookParser.ParseWebhookAsync <MultiInput>(Request.Body, Request.ContentType);

            var talkAction = new TalkAction();

            talkAction.Text = input.Speech.SpeechResults[0].Text;
            var ncco = new Ncco(talkAction);

            return(Ok(ncco.ToString()));
        }
        public async Task <IActionResult> Dtmf()
        {
            var input      = WebhookParser.ParseWebhook <MultiInput>(Request.Body, Request.ContentType);
            var talkAction = new TalkAction()
            {
                Text = $"You Pressed {input?.Dtmf.Digits}, goodbye"
            };
            var ncco = new Ncco(talkAction);

            return(Ok(ncco.ToString()));
        }
예제 #12
0
        public void ValidateWebhookSignature()
        {
            // Arrange
            var parser = new WebhookParser();

            // Act
            var result = parser.ParseSignedEventsWebhook(SAMPLE_PAYLOAD, SAMPLE_PUBLIC_KEY, SAMPLE_SIGNATURE, SAMPLE_TIMESTAMP);

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(11);             // The sample payload contains 11 events
        }
예제 #13
0
        public async Task <IActionResult> Notify()
        {
            var notification = await WebhookParser.ParseWebhookAsync <Notification <FooBar> >(Request.Body, Request.ContentType);

            Console.WriteLine($"Notification received payload's foo = {notification.Payload.Foo}");
            var talkAction = new TalkAction()
            {
                Text = "Your notification has been received, loud and clear"
            };
            var ncco = new Ncco(talkAction);

            return(Ok(ncco.ToString()));
        }
예제 #14
0
        public async Task <ActionResult> Dtmf()
        {
            var input = await WebhookParser.ParseWebhookAsync <MultiInput>
                            (Request.Body, Request.ContentType);

            var talkAction = new TalkAction
            {
                Text = $"Thank you for inputing: {input.Dtmf.Digits}"
            };
            var ncco = new Ncco(talkAction);

            return(Ok(ncco.ToString()));
        }
        public void ParseEvent()
        {
            // Arrange
            var path    = Path.Combine(Environment.CurrentDirectory, "Payloads", "MediaPlay.json");
            var payload = File.ReadAllText(path);
            var parser  = new WebhookParser();

            // Act
            var plexEvent = parser.ParseEvent(payload);

            // Assert
            Assert.IsType <MediaPlay>(plexEvent);
        }
예제 #16
0
        public async Task RawPayloadWithAttachmentsAsync()
        {
            var parser = new WebhookParser();

            using (Stream stream = new MemoryStream())
            {
                using (var fileStream = File.OpenRead("InboudEmailTestData/raw_data.txt"))
                {
                    await fileStream.CopyToAsync(stream).ConfigureAwait(false);
                }
                stream.Position = 0;

                InboundEmail inboundEmail = await parser.ParseInboundEmailWebhookAsync(stream).ConfigureAwait(false);

                inboundEmail.ShouldNotBeNull();

                inboundEmail.Dkim.ShouldBe("{@sendgrid.com : pass}");

                var rawEmailTestData = File.ReadAllText("InboudEmailTestData/raw_email.txt");
                inboundEmail.RawEmail.Trim().ShouldBe(rawEmailTestData);

                inboundEmail.To[0].Email.ShouldBe("*****@*****.**");
                inboundEmail.To[0].Name.ShouldBe(string.Empty);

                inboundEmail.Cc.Length.ShouldBe(0);

                inboundEmail.From.Email.ShouldBe("*****@*****.**");
                inboundEmail.From.Name.ShouldBe("Example User");

                inboundEmail.SenderIp.ShouldBe("0.0.0.0");

                inboundEmail.SpamReport.ShouldBeNull();

                inboundEmail.Envelope.From.ShouldBe("*****@*****.**");
                inboundEmail.Envelope.To.Length.ShouldBe(1);
                inboundEmail.Envelope.To.ShouldContain("*****@*****.**");

                inboundEmail.Subject.ShouldBe("Raw Payload");

                inboundEmail.SpamScore.ShouldBeNull();

                inboundEmail.Charsets.Except(new[]
                {
                    new KeyValuePair <string, Encoding>("to", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("subject", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("from", Encoding.UTF8)
                }).Count().ShouldBe(0);

                inboundEmail.Spf.ShouldBe("pass");
            }
        }
예제 #17
0
        public void GroupResubscribe()
        {
            // Arrange
            var responseContent = $"[{GROUPRESUBSCRIBE_JSON}]";
            var parser          = new WebhookParser();
            var mockResponse    = GetMockRequest(responseContent);

            // Act
            var result = parser.ParseWebhookEventsAsync(mockResponse.Object).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(GroupResubscribeEvent));
        }
예제 #18
0
        public async Task GroupResubscribe()
        {
            // Arrange
            var responseContent = $"[{GROUPRESUBSCRIBE_JSON}]";
            var parser          = new WebhookParser();
            var stream          = GetStream(responseContent);

            // Act
            var result = await parser.ParseWebhookEventsAsync(stream).ConfigureAwait(false);

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(GroupResubscribeEvent));
        }
예제 #19
0
        public IActionResult VerifySms()
        {
            var VONAGE_API_SIGNATURE_SECRET = Environment.GetEnvironmentVariable("VONAGE_API_SIGNATURE_SECRET") ?? "VONAGE_API_SIGNATURE_SECRET";
            var sms = WebhookParser.ParseQuery <InboundSms>(Request.Query);

            if (sms.ValidateSignature(VONAGE_API_SIGNATURE_SECRET, Vonage.Cryptography.SmsSignatureGenerator.Method.md5hash))
            {
                Console.WriteLine("Signature is valid");
            }
            else
            {
                Console.WriteLine("Signature not valid");
            }
            return(NoContent());
        }
예제 #20
0
        public void Click()
        {
            // Arrange
            var responseContent = $"[{CLICK_JSON}]";
            var parser          = new WebhookParser();
            var stream          = GetStream(responseContent);

            // Act
            var result = parser.ParseWebhookEventsAsync(stream).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(ClickEvent));
        }
예제 #21
0
        public void GroupUnsubscribe()
        {
            // Arrange
            var responseContent = $"[{GROUPUNSUBSCRIBE_JSON}]";
            var parser          = new WebhookParser();
            var stream          = GetStream(responseContent);

            // Act
            var result = parser.ParseWebhookEventsAsync(stream).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(GroupUnsubscribeEvent));
        }
예제 #22
0
        public async Task Open()
        {
            // Arrange
            var responseContent = $"[{OPEN_JSON}]";
            var parser          = new WebhookParser();
            var stream          = GetStream(responseContent);

            // Act
            var result = await parser.ParseWebhookEventsAsync(stream).ConfigureAwait(false);

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(OpenEvent));
        }
예제 #23
0
        public void Open()
        {
            // Arrange
            var responseContent = $"[{OPEN_JSON}]";
            var parser          = new WebhookParser();
            var mockResponse    = GetMockRequest(responseContent);

            // Act
            var result = parser.ParseWebhookEventsAsync(mockResponse.Object).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(1);
            result[0].GetType().ShouldBe(typeof(OpenEvent));
        }
예제 #24
0
        public ActionResult InboundWhatsAppMessage()
        {
            var inbound = WebhookParser.ParseWebhook <JObject>
                              (Request.Body, Request.ContentType);
            var message = new WhatsAppMessage
            {
                MessageId = inbound["message_uuid"].ToString(),
                From      = inbound["from"]["number"].ToString(),
                To        = inbound["to"]["number"].ToString(),
                Text      = inbound["message"]["content"]["text"].ToString()
            };

            _db.Messages.Add(message);
            _db.SaveChanges();
            return(Ok());
        }
예제 #25
0
        public async Task Processed()
        {
            // Arrange
            var responseContent = $"[{PROCESSED_JSON}]";
            var parser          = new WebhookParser();

            using (var stream = GetStream(responseContent))
            {
                // Act
                var result = await parser.ParseEventsWebhookAsync(stream).ConfigureAwait(false);

                // Assert
                result.ShouldNotBeNull();
                result.Length.ShouldBe(1);
                result[0].GetType().ShouldBe(typeof(ProcessedEvent));
            }
        }
예제 #26
0
        public async Task Unsubscribe()
        {
            // Arrange
            var responseContent = $"[{UNSUBSCRIBE_JSON}]";
            var parser          = new WebhookParser();

            using (var stream = GetStream(responseContent))
            {
                // Act
                var result = await parser.ParseEventsWebhookAsync(stream).ConfigureAwait(false);

                // Assert
                result.ShouldNotBeNull();
                result.Length.ShouldBe(1);
                result[0].GetType().ShouldBe(typeof(UnsubscribeEvent));
                result[0].EventType.ShouldBe(EventType.Unsubscribe);
            }
        }
예제 #27
0
        public void InboundEmail()
        {
            // Arrange
            using (var stream = new MemoryStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(INBOUND_EMAIL_WEBHOOK);
                    writer.Flush();
                    stream.Position = 0;

                    // Act
                    var parser       = new WebhookParser();
                    var inboundEmail = parser.ParseInboundEmailWebhook(stream);

                    // Assert
                    inboundEmail.Attachments.ShouldNotBeNull();
                    inboundEmail.Attachments.Length.ShouldBe(0);
                    inboundEmail.Cc.ShouldNotBeNull();
                    inboundEmail.Cc.Length.ShouldBe(0);
                    inboundEmail.Charsets.ShouldNotBeNull();
                    inboundEmail.Charsets.Length.ShouldBe(5);
                    inboundEmail.Dkim.ShouldBe("{@hotmail.com : pass}");
                    inboundEmail.From.ShouldNotBeNull();
                    inboundEmail.From.Email.ShouldBe("*****@*****.**");
                    inboundEmail.From.Name.ShouldBe("Bob Smith");
                    inboundEmail.Headers.ShouldNotBeNull();
                    inboundEmail.Headers.Length.ShouldBe(40);
                    inboundEmail.Html.ShouldStartWith("<html", Case.Insensitive);
                    inboundEmail.SenderIp.ShouldBe("10.43.24.23");
                    inboundEmail.SpamReport.ShouldBeNull();
                    inboundEmail.SpamScore.ShouldBeNull();
                    inboundEmail.Spf.ShouldBe("softfail");
                    inboundEmail.Subject.ShouldBe("Test #1");
                    inboundEmail.Text.ShouldBe("Test #1\r\n");
                    inboundEmail.To.ShouldNotBeNull();
                    inboundEmail.To.Length.ShouldBe(1);
                    inboundEmail.To[0].Email.ShouldBe("*****@*****.**");
                    inboundEmail.To[0].Name.ShouldBe("Test Recipient");
                }
            }
        }
예제 #28
0
 internal async Task InvokeAsync(HttpContext httpContext)
 {
     try
     {
         InboundSms sms;
         if (httpContext.Request.Method == "GET")
         {
             sms = WebhookParser.ParseQuery <InboundSms>(httpContext.Request.Query);
         }
         else
         {
             sms = await WebhookParser.ParseWebhookAsync <InboundSms>(httpContext.Request.Body, httpContext.Request.ContentType);
         }
         if (!string.IsNullOrEmpty(_signatureSecret))
         {
             if (sms.ValidateSignature(_signatureSecret, _signatureMethod))
             {
                 httpContext.Response.StatusCode = 204;
                 _delegate(sms);
             }
             else
             {
                 httpContext.Response.StatusCode = 401;
             }
         }
         else
         {
             httpContext.Response.StatusCode = 204;
             _delegate(sms);
         }
     }
     catch (Exception)
     {
         httpContext.Response.StatusCode = 500;
     }
     if (_invokeNextMiddleware)
     {
         await _next(httpContext);
     }
 }
예제 #29
0
        public async Task InboundEmail_with_unusual_encoding()
        {
            // Arrange
            var parser = new WebhookParser();

            using (var stream = GetStream(INBOUND_EMAIL_UNUSUAL_ENCODING_WEBHOOK))
            {
                // Act
                var inboundEmail = await parser.ParseInboundEmailWebhookAsync(stream).ConfigureAwait(false);

                // Assert
                inboundEmail.Charsets.ShouldNotBeNull();
                inboundEmail.Charsets.Except(new[]
                {
                    new KeyValuePair <string, Encoding>("to", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("subject", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("from", Encoding.UTF8),
                    new KeyValuePair <string, Encoding>("html", Encoding.ASCII),
                    new KeyValuePair <string, Encoding>("text", Encoding.UTF8)                          // The original encoding is iso-8859-10 but we fallback on UTF-8
                }).Count().ShouldBe(0);
                inboundEmail.Text.Replace("\r\n", "\n").ShouldBe("Hello SendGrid!\n");
            }
        }
예제 #30
0
        public IActionResult Answer()
        {
            var host = Request.Host.ToString();
            //Uncomment the next line if using ngrok with --host-header option
            //host = Request.Headers["X-Original-Host"];

            var request        = WebhookParser.ParseQuery <Answer>(Request.Query);
            var eventUrl       = $"{Request.Scheme}://{host}/webhooks/asr";
            var speechSettings = new SpeechSettings {
                Language = "en-US", EndOnSilence = 1, Uuid = new[] { request.Uuid }
            };
            var inputAction = new MultiInputAction {
                Speech = speechSettings, EventUrl = new[] { eventUrl }
            };

            var talkAction = new TalkAction {
                Text = "Please speak now"
            };

            var ncco = new Ncco(talkAction, inputAction);

            return(Ok(ncco.ToString()));
        }