From 66424b170dc47aa31b02b3e959d655ccab9d7ac2 Mon Sep 17 00:00:00 2001 From: Azhe Kun Date: Mon, 10 Jun 2024 07:58:04 +0700 Subject: [PATCH] add more event for GitHub --- .../Core/ApiRequestBase.cs | 2 ++ .../Webhook/PostWebhookPayloadRequest.cs | 7 ++---- .../Services/WebhookService.cs | 14 +++++++++++ backend/ZiziBot.Parsers/SerializationUtil.cs | 8 +++++++ backend/ZiziBot.WebApi/RestApiExtension.cs | 23 ++++++------------- 5 files changed, 33 insertions(+), 21 deletions(-) diff --git a/backend/ZiziBot.Application/Core/ApiRequestBase.cs b/backend/ZiziBot.Application/Core/ApiRequestBase.cs index aaf789ad..2f770b09 100644 --- a/backend/ZiziBot.Application/Core/ApiRequestBase.cs +++ b/backend/ZiziBot.Application/Core/ApiRequestBase.cs @@ -41,4 +41,6 @@ public class ApiRequestBase : IRequest> [BindNever] [SwaggerIgnore] public string? BearerToken => Authorization?.Replace("Bearer ", string.Empty); + + public async Task RequestBody() => await HttpContextAccessor?.HttpContext?.GetBodyAsync(); } \ No newline at end of file diff --git a/backend/ZiziBot.Application/Handlers/RestApis/Webhook/PostWebhookPayloadRequest.cs b/backend/ZiziBot.Application/Handlers/RestApis/Webhook/PostWebhookPayloadRequest.cs index 939a039d..9b1235ee 100644 --- a/backend/ZiziBot.Application/Handlers/RestApis/Webhook/PostWebhookPayloadRequest.cs +++ b/backend/ZiziBot.Application/Handlers/RestApis/Webhook/PostWebhookPayloadRequest.cs @@ -10,9 +10,6 @@ namespace ZiziBot.Application.Handlers.RestApis.Webhook; public class PostWebhookPayloadRequest : ApiRequestBase { - [FromBody] - public object? Content { get; set; } - [FromRoute(Name = "targetId")] public string targetId { get; set; } @@ -50,12 +47,12 @@ CancellationToken cancellationToken var stopwatch = Stopwatch.StartNew(); var webhookSource = request.UserAgent.GetWebHookSource(); var webhookHeader = WebhookHeader.Parse(request.Headers); - var content = $"{request.Content}"; + var content = await request.RequestBody(); var response = new ApiResponseBase() { TransactionId = request.HttpContextAccessor?.HttpContext?.TraceIdentifier ?? string.Empty }; - if (request.Content == null) + if (content == null) { return response.BadRequest("Webhook payload is empty"); } diff --git a/backend/ZiziBot.Application/Services/WebhookService.cs b/backend/ZiziBot.Application/Services/WebhookService.cs index 385b0799..f6a35389 100644 --- a/backend/ZiziBot.Application/Services/WebhookService.cs +++ b/backend/ZiziBot.Application/Services/WebhookService.cs @@ -86,6 +86,20 @@ public async Task> ParseGitHub(WebhookHeader header, s .Bold("Status: ").TextBr(deploymentEvent.Deployment.Task); break; + case WebhookEventType.WorkflowRun: + var workflowRunEvent = payload.Deserialize(); + htmlMessage.Bold("Name: ").TextBr(workflowRunEvent.WorkflowRun.Name) + .Bold("Status: ").TextBr(workflowRunEvent.WorkflowRun.Status.StringValue) + .Bold("Actor: ").TextBr(workflowRunEvent.WorkflowRun.Actor.Login); + break; + + case WebhookEventType.CheckSuite: + var checkSuiteEvent = payload.Deserialize(); + htmlMessage.Bold("Name: ").TextBr(checkSuiteEvent.CheckSuite.App.Name) + .Bold("Status: ").TextBr(checkSuiteEvent.CheckSuite.Status.StringValue) + .Bold("Conclusion: ").TextBr(checkSuiteEvent.CheckSuite.Conclusion.StringValue); + break; + default: break; } diff --git a/backend/ZiziBot.Parsers/SerializationUtil.cs b/backend/ZiziBot.Parsers/SerializationUtil.cs index c93f1de2..4578ab78 100644 --- a/backend/ZiziBot.Parsers/SerializationUtil.cs +++ b/backend/ZiziBot.Parsers/SerializationUtil.cs @@ -49,4 +49,12 @@ public static string ToHeaderRawKv(this IHeaderDictionary headerDictionary) { return headerDictionary.Select(kv => $"{kv.Key}: {kv.Value}").StrJoin("\n"); } + + public static async Task GetBodyAsync(this HttpContext? context) + { + if (context == null) return string.Empty; + + using var reader = new StreamReader(context.Request.Body); + return await reader.ReadToEndAsync(); + } } \ No newline at end of file diff --git a/backend/ZiziBot.WebApi/RestApiExtension.cs b/backend/ZiziBot.WebApi/RestApiExtension.cs index c77129ad..4c5c5343 100644 --- a/backend/ZiziBot.WebApi/RestApiExtension.cs +++ b/backend/ZiziBot.WebApi/RestApiExtension.cs @@ -34,15 +34,13 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services) options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); } ) - .AddNewtonsoftJson() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var transactionId = context.HttpContext.Request.Headers[HeaderKey.TransactionId].FirstOrDefault(); var errorDetails = context.ModelState .Where(entry => entry.Value?.ValidationState == ModelValidationState.Invalid) - .Select(key => new - { + .Select(key => new { Id = key.Key, Field = key.Key.Split('.').Last(), Message = key.Value?.Errors.Select(e => e.ErrorMessage) @@ -50,13 +48,11 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services) var errors = errorDetails.SelectMany(x => x.Message).ToList(); - return new BadRequestObjectResult(new ApiResponseBase() - { + return new BadRequestObjectResult(new ApiResponseBase() { StatusCode = HttpStatusCode.BadRequest, TransactionId = transactionId, Message = "Please ensure your request", - Result = new - { + Result = new { Error = errors.Aggregate((a, b) => $"{a}\n{b}"), Errors = errors, ErrorDetails = errorDetails, @@ -71,8 +67,7 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services) options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { - o.TokenValidationParameters = new TokenValidationParameters - { + o.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = jwtConfig.Issuer, ValidAudience = jwtConfig.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key)), @@ -82,16 +77,14 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services) ValidateIssuerSigningKey = true }; - o.Events = new JwtBearerEvents - { + o.Events = new JwtBearerEvents { OnChallenge = async context => { context.HandleResponse(); context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; await context.Response.WriteAsJsonAsync( - new ApiResponseBase() - { + new ApiResponseBase() { StatusCode = HttpStatusCode.Unauthorized, Message = "Please ensure you have a valid token" } @@ -154,9 +147,7 @@ public static WebApplication ConfigureApi(this WebApplication app) app.ConfigureRateLimiter(); app.UseSwagger(); - app.UseSwaggerUI(options => { - options.DefaultModelsExpandDepth(-1); - }); + app.UseSwaggerUI(options => { options.DefaultModelsExpandDepth(-1); }); return app; }