Exemplo n.º 1
0
        public static IApplicationBuilder UseMedium(this IApplicationBuilder app, Action <MediumOptions> options)
        {
            var configurator  = app.ApplicationServices.GetService <IMediumConfigurator>();
            var mediumOptions = new MediumOptions();

            options(mediumOptions);
            var configuration = mediumOptions.SettingsLoader.Load();
            var settings      = JsonConvert.DeserializeObject <MediumSettings>(configuration);
            var webhooks      = settings.Webhooks.Select(x => WebhookModel.MapToWebhook(x));

            foreach (var webhook in webhooks)
            {
                configurator.AddWebhook(webhook);
            }
            var mediumConfiguration = configurator.Configure();

            if (!mediumConfiguration.Webhooks.Any())
            {
                return(app);
            }
            var repository = mediumConfiguration.Repository;
            var tasks      = new List <Task>();

            foreach (var webhook in mediumConfiguration.Webhooks)
            {
                tasks.Add(repository.AddAsync(webhook));
            }
            Task.WaitAll(tasks.ToArray());

            return(app);
        }
        public async Task ReturnsOkWheneverPossible(PayloadType payloadType, string artefactType, string dataType, string operation)
        {
            Item[]     items      = null;
            Taxonomy[] taxonomies = null;

            switch (payloadType)
            {
            case PayloadType.Items:
                items = new[] { new Item {
                                    Codename = "Test", Type = dataType
                                } };
                break;

            case PayloadType.Taxonomies:
                taxonomies = new[] { new Taxonomy {
                                         Codename = "Test"
                                     } };
                break;
            }

            var model = new WebhookModel
            {
                Data = new Data {
                    Items = items, Taxonomies = taxonomies
                },
                Message = new Message {
                    Type = artefactType, Operation = operation
                }
            };

            var controller = new WebhooksController(new DeliveryCacheManager(new MemoryCache(Options.Create(new MemoryCacheOptions())), Options.Create(new DeliveryCacheOptions())));
            var result     = (StatusCodeResult)await Task.Run(() => controller.Index(model));

            Assert.InRange(result.StatusCode, 200, 299);
        }
Exemplo n.º 3
0
 internal RestWebhook(RestDiscordClient client, WebhookModel model) : base(client, model.Id)
 {
     Token   = model.Token;
     GuildId = model.GuildId;
     Guild   = new RestDownloadable <RestGuild>(options => Client.GetGuildAsync(GuildId, options));
     Channel = new RestDownloadable <RestTextChannel>(async options => await client.GetChannelAsync(ChannelId, options).ConfigureAwait(false) as RestTextChannel);
 }
Exemplo n.º 4
0
        public HttpResponseMessage ZenPost([FromBody] WebhookModel message)
        {
            var jsonContent = JsonConvert.SerializeObject(message);

            _theHub.Clients.All.receiveWebHookTicket(jsonContent);
            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemplo n.º 5
0
        public void WebhookMapper_Map_Model_BodyAsJson()
        {
            // Assign
            var model = new WebhookModel
            {
                Request = new WebhookRequestModel
                {
                    Url     = "https://localhost",
                    Method  = "get",
                    Headers = new Dictionary <string, string>
                    {
                        { "x", "y" }
                    },
                    BodyAsJson = new { n = 12345 }
                }
            };

            var result = WebhookMapper.Map(model);

            result.Request.Url.Should().Be("https://localhost");
            result.Request.Method.Should().Be("get");
            result.Request.Headers.Should().HaveCount(1);
            result.Request.BodyData.BodyAsString.Should().BeNull();
            result.Request.BodyData.BodyAsJson.Should().NotBeNull();
            result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.Json);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Demonstrates creating an Apex class in a client's Salesforce instance.
        /// </summary>
        private async Task CreateWebhookClassAsync(WebhookModel webhookModel, ForceClient client)
        {
            // First check if a class with this name already exists
            var existingWebhookClass = await client.QueryAsync <ApexClass>("SELECT Id FROM ApexClass WHERE Name = 'ActionRelayWebhook'");

            // If the class does not exist
            if (!existingWebhookClass.Records.Any())
            {
                var classBody = GetApexCode("SalesforceIntegration.ApexTemplates.WebhookTemplate.txt");

                var apexClass = new ApexClass
                {
                    ApiVersion = _apiVersion.TrimStart('v'),
                    Body       = classBody,
                    Name       = "ActionRelayWebhook"
                };

                var success = await client.CreateAsync("ApexClass", apexClass);

                if (!success.Success)
                {
                    throw new HttpException((int)HttpStatusCode.InternalServerError, "Create Failed!");
                }
            }
        }
Exemplo n.º 7
0
        public async Task ProcessMessage(WebhookModel value)
        {
            foreach (var msg in value.events)
            {
                switch (msg.type)
                {
                case "follow":
                    await NanaAPIHelper.ReplyMessage(GetTextReply(msg.replyToken, "follow event type"));

                    break;

                case "postback":
                    await NanaAPIHelper.ReplyMessage(GetTextReply(msg.replyToken, msg.postback.data));

                    break;

                case "join":
                    await NanaAPIHelper.ReplyMessage(GetTextReply(msg.replyToken, "join event type"));

                    break;

                case "message":
                    var res = await NanaAPIHelper.ReplyMessage(HandleMessageObject(msg));

                    break;

                default:
                    await NanaAPIHelper.ReplyMessage(GetTextReply(msg.replyToken, "not support"));

                    break;
                }
            }
        }
Exemplo n.º 8
0
        public void WebhookMapper_Map_Model_BodyAsString_And_UseTransformerIsTrue()
        {
            // Assign
            var model = new WebhookModel
            {
                Request = new WebhookRequestModel
                {
                    Url     = "https://localhost",
                    Method  = "get",
                    Headers = new Dictionary <string, string>
                    {
                        { "x", "y" }
                    },
                    Body           = "test",
                    UseTransformer = true
                }
            };

            var result = WebhookMapper.Map(model);

            result.Request.Url.Should().Be("https://localhost");
            result.Request.Method.Should().Be("get");
            result.Request.Headers.Should().HaveCount(1);
            result.Request.BodyData.BodyAsJson.Should().BeNull();
            result.Request.BodyData.BodyAsString.Should().Be("test");
            result.Request.BodyData.DetectedBodyType.Should().Be(BodyType.String);
            result.Request.UseTransformer.Should().BeTrue();
            result.Request.TransformerType.Should().Be(TransformerType.Handlebars);
        }
 public void HandleWebhook(WebhookModel webhook)
 {
     if (webhook != null)
     {
         if (webhook.Type == WebhookTypes.DocumentConcluded)
         {
             var concludedDocument = JsonConvert.DeserializeObject <DocumentConcludedModel>(webhook.Data.ToString());
             System.Console.WriteLine($"Document {concludedDocument.Id} is concluded!");
         }
         else if (webhook.Type == WebhookTypes.DocumentRefused)
         {
             var refusedDocument = JsonConvert.DeserializeObject <DocumentRefusedModel>(webhook.Data.ToString());
             System.Console.WriteLine($"Document {refusedDocument.Id} is refused!");
         }
         else if (webhook.Type == WebhookTypes.DocumentApproved)
         {
             var approvedDocument = JsonConvert.DeserializeObject <DocumentApprovedModel>(webhook.Data.ToString());
             System.Console.WriteLine($"Document {approvedDocument.Id} is approved!");
         }
         else if (webhook.Type == WebhookTypes.DocumentSigned)
         {
             var signedDocument = JsonConvert.DeserializeObject <DocumentSignedModel>(webhook.Data.ToString());
             System.Console.WriteLine($"Document {signedDocument.Id} is signed!");
         }
     }
 }
Exemplo n.º 10
0
        public async Task <ActionResult> DeleteConfirmed(WebhookModel webhookModel)
        {
            var salesforceService = new SalesforceService((ClaimsPrincipal)User, SignInManager);
            await salesforceService.DeleteWebhookAsync(webhookModel);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 11
0
 public async Task CreateSalesforceObjectsAsync(WebhookModel webhookModel)
 {
     await GetClientWithRefresh(async client =>
     {
         await CreateWebhookClassAsync(webhookModel, client);
         await CreateTriggerAsync(webhookModel, client);
     });
 }
        public async Task <HttpResponseMessage> Post()
        {
            var body = await Request.Content.ReadAsStringAsync();

            LogInfo("WebHook_Received", new Dictionary <string, string>
            {
                { "Request Body", body }
            });

            if (!_Bot.Authenticator.VerifySignature(Request.Headers.GetValues("X-Hub-Signature").FirstOrDefault(), body))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            WebhookModel webhookModel = _Bot.ProcessWebhookRequest(body);

            if (webhookModel._Object != "page")
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            foreach (var entry in webhookModel.Entries)
            {
                foreach (var evt in entry.Events)
                {
                    if (evt.EventType == WebhookEventType.PostbackRecievedCallback ||
                        evt.EventType == WebhookEventType.MessageReceivedCallback)
                    {
                        await _Bot.SendApi.SendActionAsync(evt.Sender.ID, SenderAction.typing_on);

                        var userProfileRsp = await _Bot.UserProfileApi.GetUserProfileAsync(evt.Sender.ID);

                        if (evt.EventType == WebhookEventType.PostbackRecievedCallback)
                        {
                            await ProcessPostBack(evt.Sender.ID, userProfileRsp?.FirstName, evt.Postback);
                        }
                        if (evt.EventType == WebhookEventType.MessageReceivedCallback)
                        {
                            if (evt.Message.IsQuickReplyPostBack)
                            {
                                await ProcessPostBack(evt.Sender.ID, userProfileRsp?.FirstName, evt.Message.QuickReplyPostback);
                            }
                            else
                            {
                                await _Bot.SendApi.SendTextAsync(evt.Sender.ID, $"We got your message {userProfileRsp?.FirstName}, to prove it, we'll send it back to you :)");
                                await ResendMessageToUser(evt);
                                await ConfirmIfCorrect(evt);
                            }
                        }
                    }

                    await _Bot.SendApi.SendActionAsync(evt.Sender.ID, SenderAction.typing_off);
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemplo n.º 13
0
 internal RestWebhook(RestDiscordClient client, WebhookModel model) : base(client, model.Id)
 {
     Type    = model.Type;
     Token   = model.Token;
     GuildId = model.GuildId;
     Guild   = RestFetchable.Create(this, (@this, options) =>
                                    @this.Client.GetGuildAsync(@this.GuildId, options));
     Channel = RestFetchable.Create(this, (@this, options) =>
                                    @this.Client.GetChannelAsync <RestTextChannel>(@this.ChannelId, options));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Demonstrates deleting an Apex trigger from a client's Salesforce instance.
        /// </summary>
        public async Task DeleteWebhookAsync(WebhookModel webhookModel)
        {
            await GetClientWithRefresh(async client =>
            {
                var success = await client.DeleteAsync("ApexTrigger", webhookModel.Id);

                if (!success)
                {
                    throw new HttpException((int)HttpStatusCode.InternalServerError, "Delete Failed!");
                }
            });
        }
Exemplo n.º 15
0
        internal void Update(WebhookModel model)
        {
            ChannelId = model.ChannelId;

            if (model.User != null)
            {
                Owner = new RestUser(Client, model.User);
            }

            Name       = model.Name;
            AvatarHash = model.Avatar;
        }
Exemplo n.º 16
0
        public async Task <ActionResult> Create(WebhookModel webhookModel)
        {
            if (ModelState.IsValid)
            {
                var salesforceService = new SalesforceService((ClaimsPrincipal)User, SignInManager);
                await salesforceService.CreateSalesforceObjectsAsync(webhookModel);

                return(RedirectToAction("Index"));
            }

            return(View(webhookModel));
        }
Exemplo n.º 17
0
        // Webhook response only comes when your project is live
        public ActionResult webhook(WebhookModel webhook)
        {
            MacCalculator macCalculator = new MacCalculator();
            var           values        = WebhookToDictonary(webhook);             // Convert to dictionary
            var           salt          = InstamojoCredentials.privateSalt;        // Private Salt
            var           response      = macCalculator.MacComparer(values, salt); // Compare dictionary and Salt

            // If response is true than you have to save transaction data in database
            if (response)
            {
            }
            return(new HttpStatusCodeResult(400));
        }
Exemplo n.º 18
0
        public static IWebhook Map(WebhookModel model)
        {
            var webhook = new Webhook
            {
                Request = new WebhookRequest
                {
                    Url     = model.Request.Url,
                    Method  = model.Request.Method,
                    Headers = model.Request.Headers?.ToDictionary(x => x.Key, x => new WireMockList <string>(x.Value)) ?? new Dictionary <string, WireMockList <string> >()
                }
            };

            if (model.Request.UseTransformer == true)
            {
                webhook.Request.UseTransformer = true;
                if (!Enum.TryParse <TransformerType>(model.Request.TransformerType, out var transformerType))
                {
                    transformerType = TransformerType.Handlebars;
                }
                webhook.Request.TransformerType = transformerType;
            }

            IEnumerable <string> contentTypeHeader = null;

            if (webhook.Request.Headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)))
            {
                contentTypeHeader = webhook.Request.Headers.First(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase)).Value;
            }

            if (model.Request.Body != null)
            {
                webhook.Request.BodyData = new BodyData
                {
                    BodyAsString     = model.Request.Body,
                    DetectedBodyType = BodyType.String,
                    DetectedBodyTypeFromContentType = BodyParser.DetectBodyTypeFromContentType(contentTypeHeader?.FirstOrDefault())
                };
            }
            else if (model.Request.BodyAsJson != null)
            {
                webhook.Request.BodyData = new BodyData
                {
                    BodyAsJson       = model.Request.BodyAsJson,
                    DetectedBodyType = BodyType.Json,
                    DetectedBodyTypeFromContentType = BodyParser.DetectBodyTypeFromContentType(contentTypeHeader?.FirstOrDefault())
                };
            }

            return(webhook);
        }
        private IDictionary <string, string> GetBodyFromMock(WebhookModel model)
        {
            var dictionary = new Dictionary <string, string>();

            dictionary.Add("id", model.Id);
            dictionary.Add("action", model.Action);
            dictionary.Add("activityId", model.ActivityId);
            dictionary.Add("offerId", model.OfferId);
            dictionary.Add("planId", model.PlanId);
            dictionary.Add("publisherId", model.PublisherId);
            dictionary.Add("quantity", model.Quantity?.ToString());
            dictionary.Add("status", model.Status);
            dictionary.Add("subscriptionId", model.SubscriptionId);
            dictionary.Add("timestamp", model.Timestamp.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"));
            return(dictionary);
        }
Exemplo n.º 20
0
        public void HandleWebhook(WebhookModel webhook)
        {
            if (webhook != null)
            {
                if (webhook.Type == WebhookTypes.InvoiceClosed)
                {
                    var invoice = (InvoiceClosedModel)webhook.Data;

                    System.Console.WriteLine($"Invoice {invoice.Id} for year {invoice.Year} and month {invoice.Month} is closed");
                    System.Console.WriteLine($"The standing value is {invoice.Value}");

                    if (invoice.Organization.Owner != null)
                    {
                        System.Console.WriteLine($"This is a personal account invoice for {invoice.Organization.Owner.Name}");
                    }
                    else
                    {
                        System.Console.WriteLine($"This is an organization invoice for {invoice.Organization.Name}");
                    }

                    foreach (var total in invoice.InvoiceTotals)
                    {
                        //check the total.Price property for additional info on the pricing for that type
                        System.Console.WriteLine($"{total.Total} transactions of type {total.TransactionType} equals {total.Value}");
                    }

                    if (invoice.BillingInformation != null)
                    {
                        var info = invoice.BillingInformation;
                        System.Console.WriteLine($"Contact information: {info.ContactName} - {info.Email} - {info.Phone}");

                        if (info.Type == BillingInformationTypes.Individual)
                        {
                            System.Console.WriteLine($"Individual information: {info.Individual.Name} - {info.Individual.Identifier}");
                        }
                        else
                        {
                            System.Console.WriteLine($"Company information: {info.Company.Name} - {info.Company.Identifier}");
                        }

                        System.Console.WriteLine($"Address: {info.StreetAddress} - {info.AddressNumber} - {info.AdditionalAddressInfo}");
                        System.Console.WriteLine($"{info.Neighborhood} - {info.ZipCode}");
                        System.Console.WriteLine($"{info.City} - {info.State}");
                    }
                }
            }
        }
Exemplo n.º 21
0
        private ReplyModel GetJsonReply(WebhookModel value)
        {
            foreach (var daa in value.events)
            {
                try
                {
                    return(LineHelper.ReturnSingleSting(daa.replyToken, JsonConvert.SerializeObject(value)));
                }
                catch (Exception ex)
                {
                    return(LineHelper.ReturnSingleSting(daa.replyToken, JsonConvert.SerializeObject(ex)));
                }
            }



            return(null);
        }
        public async Task <IActionResult> ResetMfa([FromBody] WebhookModel dto)
        {
            if (string.IsNullOrEmpty(dto.Email))
            {
                logger.LogError("Cannot reset Mfa if email does not have value");
                return(BadRequest("Email cannot be null"));
            }

            var result = await webhookService.SendResetMfaEmail(dto.Username, CreateMfaResetLink);

            if (!result.Succeeded)
            {
                logger.LogError($"ResetMfa webhook failed: {result.ErrorMessage}");
                return(BadRequest(result.ErrorMessage));
            }

            return(Ok());
        }
        private WebhookModel GetWebHookSucceededMock(string action)
        {
            var mockData = new WebhookModel()
            {
                Id             = "id",
                Action         = action,
                ActivityId     = "activityId",
                OfferId        = "offerId",
                PlanId         = "planId",
                PublisherId    = "publisherId",
                Quantity       = 1,
                Status         = "anything",
                SubscriptionId = "subscriptionId",
                Timestamp      = DateTime.UtcNow
            };

            return(mockData);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Demonstrates creating an Apex trigger in a client's Salesforce instance.
        /// </summary>
        private async Task CreateTriggerAsync(WebhookModel webhookModel, ForceClient client)
        {
            var triggerBody = GetApexCode("SalesforceIntegration.ApexTemplates.TriggerTemplate.txt", webhookModel);

            var apexTrigger = new ApexTrigger
            {
                ApiVersion    = _apiVersion.TrimStart('v'),
                Body          = triggerBody,
                Name          = "ActionRelayTrigger" + webhookModel.Name,
                TableEnumOrId = webhookModel.SObject
            };

            var success = await client.CreateAsync("ApexTrigger", apexTrigger);

            if (!success.Success)
            {
                throw new HttpException((int)HttpStatusCode.InternalServerError, "Create Failed!");
            }
        }
Exemplo n.º 25
0
        public ActionResult Receive(WebhookModel data)
        {
            var hub = GlobalHost.ConnectionManager.GetHubContext <MessengerHub>();

            //            foreach (var entry in data.entry)
            //            {
            //                foreach (var msg in entry.messaging)
            //                {
            //                    if (string.IsNullOrWhiteSpace(msg?.message?.text))
            //                        continue;
            //
            //
            //                    hub.Clients.All.addNewMessageToPage(msg);
            //                }
            //            }
            hub.Clients.All.addNewMessageToPage(data);
            System.IO.File.AppendAllText(Server.MapPath("~/Content/webhook.txt"), JsonConvert.SerializeObject(data));
            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
Exemplo n.º 26
0
        private Dictionary <string, string> WebhookToDictonary(WebhookModel webhook)
        {
            Dictionary <string, string> dict = new
                                               Dictionary <string, string>();

            dict.Add("amount", webhook.amount.ToString());
            dict.Add("buyer", webhook.buyer);
            dict.Add("buyer_name", webhook.buyer_name);
            dict.Add("buyer_phone", webhook.buyer_phone);
            dict.Add("currency", webhook.currency);
            dict.Add("fees", webhook.fees.ToString());
            dict.Add("longurl", webhook.longurl);
            dict.Add("mac", webhook.mac);
            dict.Add("payment_id", webhook.payment_id);
            dict.Add("payment_request_id", webhook.payment_request_id);
            dict.Add("purpose", webhook.purpose);
            dict.Add("shorturl", webhook.shorturl);
            dict.Add("status", webhook.status);
            return(dict);
        }
Exemplo n.º 27
0
        public ActionResult Post(WebhookModel webhookModel)
        {
            Console.WriteLine(webhookModel);

            return(Ok(webhookModel));
            //WebhookModel requestBody = JsonConvert.DeserializeObject<WebhookModel>(Request.Body.ToString());

            //if (requestBody._object.Equals("page"))
            //{
            //    foreach (var entry in requestBody.entry)
            //    {
            //        var webhookEvent = entry.messaging.FirstOrDefault();

            //        Console.WriteLine(webhookEvent);
            //    }

            //    return Ok("EVENT_RECEIVED");
            //}

            //return NotFound();
        }
Exemplo n.º 28
0
        public async Task <HttpResponseMessage> Post([FromBody] WebhookModel value)
        {
            if (value._object != "page")
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            foreach (var item in value.entry[0].messaging)
            {
                if (item.message == null && item.postback == null)
                {
                    continue;
                }
                else
                {
                    await SendMessage(GetMessageTemplate(item.message.text, item.sender.id));
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        public IActionResult Index([FromBody] WebhookModel model)
        {
            if (model != null)
            {
                var dependencies = new HashSet <string>();
                if (model.Data.Items?.Any() == true)
                {
                    foreach (var item in model.Data.Items ?? Enumerable.Empty <Item>())
                    {
                        dependencies.Add(CacheHelpers.GetItemDependencyKey(item.Codename));
                    }

                    dependencies.Add(CacheHelpers.GetItemsDependencyKey());
                }

                if (model.Data.Taxonomies?.Any() == true)
                {
                    foreach (var taxonomy in model.Data.Taxonomies ?? Enumerable.Empty <Taxonomy>())
                    {
                        dependencies.Add(CacheHelpers.GetTaxonomyDependencyKey(taxonomy.Codename));
                    }

                    dependencies.Add(CacheHelpers.GetTaxonomiesDependencyKey());
                    dependencies.Add(CacheHelpers.GetItemsDependencyKey());
                    dependencies.Add(CacheHelpers.GetTypesDependencyKey());
                }

                if (model.Message.Type == "content_type")
                {
                    dependencies.Add(CacheHelpers.GetTypesDependencyKey());
                }

                foreach (var dependency in dependencies)
                {
                    _cacheManager.InvalidateDependencyAsync(dependency);
                }
            }

            return(Ok());
        }
Exemplo n.º 30
0
        public async Task ProcessMessage(WebhookModel value)
        {
            //  await APIHelper.ReplyMessage(GetJsonReply(value));
            foreach (var msg in value.events)
            {
                switch (msg.type)
                {
                //case "follow":
                //    await APIHelper.ReplyMessage(GetFollowReply(msg));
                //    break;
                case "postback":
                    await APIHelper.ReplyMessage(GetPostbackReply(msg));

                    break;
                //case "memberJoined":
                //    await APIHelper.ReplyMessage(GetmemberJoinReply(msg));
                //    break;
                //case "memberLefted":
                //    await APIHelper.ReplyMessage(GetMemberLeftReply(msg));
                //    break;
                //case "unfollow":
                //    await APIHelper.ReplyMessage(GetUnfollowReply(msg));
                //    break;
                //case "leave":
                //    await APIHelper.ReplyMessage(GetLeaveReply(msg));
                //    break;

                case "message":
                    var res = await APIHelper.ReplyMessage(HandleMessageObject(msg));

                    break;

                default:
                    await APIHelper.ReplyMessage(GetTextReply(msg.replyToken, "not support"));

                    break;
                }
            }
        }