Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace azfwhook
- {
- using System;
- using System.IO;
- using System.Net;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Azure.WebJobs;
- using Microsoft.Azure.WebJobs.Extensions.Http;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- public static class WebHooks
- {
- //TODO: SECURE THIS ENDPOINT!!!!!!!
- // [HttpPost] // only handle POST (get support is handy for smoke testing in a browser)
- [FunctionName("AnyEntryUpdated")] // API method name (Webhook handler)
- public static async Task<IActionResult> Run(
- [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest webhookRequest,
- ILogger logger)
- {
- try
- {
- // webhook JSON payload from CMS
- string sWebhookBody = await new StreamReader(webhookRequest.Body).ReadToEndAsync();
- if (String.IsNullOrWhiteSpace(sWebhookBody))
- {
- // no JSON payload
- return new StatusCodeResult((int)HttpStatusCode.BadRequest);
- }
- JObject webhookBody = JObject.Parse(sWebhookBody);
- // ID of saved entry
- JToken uid = webhookBody.SelectToken("$.data.entry.uid");
- if (uid == null || String.IsNullOrWhiteSpace(uid.ToString()))
- {
- // no entry UID
- return new StatusCodeResult((int)HttpStatusCode.BadRequest);
- }
- // collect entry validation error messages
- string validationMessages = String.Empty;
- // when this process last ran
- JToken lastRan = webhookBody.SelectToken("$.data.entry.lastran");
- if (lastRan == null)
- {
- validationMessages += "The lastran field does not exist." + Environment.NewLine;
- }
- else if ((!String.IsNullOrEmpty(lastRan.ToString()))
- && DateTime.Parse(lastRan.ToString()).AddSeconds(1)
- > DateTime.Parse(webhookBody.SelectToken("$.data.entry.updated_at").ToString()))
- {
- // logic ran against entry within the previous second;
- // avoid infinite update webhook/handler recursion
- return new StatusCodeResult((int)HttpStatusCode.OK);
- }
- // CMS API endpoint for entry
- //TODO: shouldn't be hard-coded
- string url = "https://api.contentstack.io/v3/content_types/authors/entries/" + uid;
- HttpRequestHandler wfStageReqHandler = new HttpRequestHandler();
- JObject wfStageBody = JsonConvert.DeserializeObject<JObject>(
- await wfStageReqHandler.ProcessRequest(url + "?include_workflow=true"));
- // current workflow stage of entry
- JToken wfStage = wfStageBody.SelectToken("$.entry._workflow.name");
- if (wfStage == null)
- {
- validationMessages += "The entry has no workflow stage." + Environment.NewLine;
- }
- else if (wfStage.ToString() != "validation")
- {
- // only validate in validation workflow stage or no workflow stage
- return new StatusCodeResult((int)HttpStatusCode.OK);
- }
- validationMessages += ValidateDates(
- webhookBody.SelectToken("$.data.entry.dateone"),
- webhookBody.SelectToken("$.data.entry.datetwo"));
- if (String.Equals(validationMessages, webhookBody.SelectToken("$.data.entry.validationmessages").ToString()))
- {
- // no updates to commit
- return new StatusCodeResult((int)HttpStatusCode.OK);
- }
- // update the entry with the new validation results and record time of operation for use avoiding recursion
- JObject postBody = new JObject(
- new JProperty("entry", new JObject(
- new JProperty("validationmessages", validationMessages),
- new JProperty("lastran", new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Utc)))));
- HttpRequestHandler requestHandler = new HttpRequestHandler();
- string discard = await requestHandler.ProcessRequest(url, postBody);
- }
- catch (Exception)
- {
- //TODO:...
- return new StatusCodeResult((int)HttpStatusCode.InternalServerError);
- }
- return new StatusCodeResult((int)HttpStatusCode.OK);
- }
- private static string ValidateDates(JToken dateOne, JToken dateTwo)
- {
- string result = String.Empty;
- if (dateOne == null)
- {
- result += "The first date field does not exist." + Environment.NewLine;
- }
- else if (string.IsNullOrWhiteSpace(dateOne.ToString()))
- {
- result += "The first date field does not contain a value." + Environment.NewLine;
- }
- if (dateTwo == null)
- {
- result += "The second date field does not exist." + Environment.NewLine;
- }
- else if (string.IsNullOrWhiteSpace(dateTwo.ToString()))
- {
- result += "The second date field does not contain a value." + Environment.NewLine;
- }
- // if there are any validation messages already,
- // it might not be possible to compare the dates (potential null reference).
- // otherwise, compare the dates
- if (String.IsNullOrWhiteSpace(result)
- && DateTime.Parse(dateOne.ToString())
- > DateTime.Parse(dateTwo.ToString()))
- {
- result += "The second date must follow the first date." + Environment.NewLine;
- }
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement