DocSpace-client/common/ASC.Api.Core/Middleware/WebhooksMiddleware.cs

72 lines
2.2 KiB
C#
Raw Normal View History

2021-08-03 16:26:28 +00:00
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ASC.Webhooks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
2021-08-03 16:26:28 +00:00
using Microsoft.AspNetCore.Routing.Patterns;
namespace ASC.Api.Core.Middleware
{
public class WebhooksMiddleware
{
private readonly RequestDelegate _next;
private WebhookPublisher WebhookPublisher { get; }
2021-07-28 15:16:56 +00:00
private WebhooksIdentifier WebhooksIdentifier { get; }
2021-07-28 15:16:56 +00:00
public WebhooksMiddleware(RequestDelegate next, WebhookPublisher webhookPublisher, WebhooksIdentifier webhooksIdentifier)
{
_next = next;
WebhookPublisher = webhookPublisher;
2021-07-28 15:16:56 +00:00
WebhooksIdentifier = webhooksIdentifier;
}
public async Task InvokeAsync(HttpContext context)
{
2021-08-03 16:26:28 +00:00
var methodList = new List<string> { "POST", "UPDATE", "DELETE" };
2021-08-03 16:26:28 +00:00
var method = context.Request.Method;
var endpoint = (RouteEndpoint)context.GetEndpoint();
var routePattern = endpoint.RoutePattern.RawText;
2021-08-03 16:26:28 +00:00
if (!methodList.Contains(method) && !WebhooksIdentifier.Identify(routePattern))
{
await _next(context);
return;
}
string responseContent;
var originalResponseBody = context.Response.Body;
using (var ms = new MemoryStream())
{
context.Response.Body = ms;
await _next(context);
ms.Position = 0;
var responseReader = new StreamReader(ms);
responseContent = responseReader.ReadToEnd();
ms.Position = 0;
await ms.CopyToAsync(originalResponseBody);
context.Response.Body = originalResponseBody;
}
2021-08-03 16:26:28 +00:00
var eventName = "method: " + method + ", " + "route: " + routePattern;
WebhookPublisher.Publish(eventName, responseContent);
}
}
public static class WebhooksMiddlewareExtensions
{
public static IApplicationBuilder UseWebhooksMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WebhooksMiddleware>();
}
}
}