-
Notifications
You must be signed in to change notification settings - Fork 0
Expanding webhooks #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
16e07fc
split webhook service into smaller components + add new column for ty…
Skyfall1235 6a7314a
db changes + event repo regorganisation
Skyfall1235 3b5b72e
Upgrade CodeQL actions to version 4
Skyfall1235 16641ff
Potential fix for code scanning alert no. 6: Log entries created from…
Skyfall1235 43a1670
Potential fix for code scanning alert no. 8: Log entries created from…
Skyfall1235 ad12b5c
Update BaseWebhookService.cs
Skyfall1235 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
152 changes: 152 additions & 0 deletions
152
src/RandomAPI/APIServices/Services/BaseWebhookService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using RandomAPI.Models; | ||
| using RandomAPI.Repository; | ||
| using static IWebhookService; | ||
|
|
||
| namespace RandomAPI.Services.Webhooks | ||
| { | ||
| public class WebhookActionService : BaseWebhookService, IWebhookService | ||
| { | ||
|
|
||
| public WebhookActionService(IWebhookRepository repo, ILogger<IWebhookService> logger) | ||
| : base(repo, logger) { } | ||
|
|
||
| public async Task<IActionResult> HandleGetListenersActionAsync() | ||
| { | ||
| var urls = await base.GetListenersAsync(); | ||
| return new OkObjectResult(urls); | ||
| } | ||
|
|
||
| public async Task<IActionResult> HandleGetListenersOfTypeAsync(WebhookType type) | ||
| { | ||
| var urls = await base.GetListenersAsync(type); | ||
| return new OkObjectResult(urls); | ||
| } | ||
|
|
||
| public async Task<IActionResult> HandleRegisterActionAsync([FromBody] string url, IWebhookService.WebhookType type = default) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(url)) | ||
| return new BadRequestObjectResult("URL cannot be empty."); | ||
| //neede both on regisdter and deregister | ||
| url = url.Trim(); | ||
| var safeUrlForLog = url.Replace("\r", "").Replace("\n", ""); | ||
|
|
||
| await base.AddListenerAsync(url, type); | ||
|
|
||
| _logger.LogInformation("Registered new webhook listener: {Url}", safeUrlForLog); | ||
|
|
||
| return new OkObjectResult(new { Message = $"Listener added successfully: {url}" }); | ||
| } | ||
|
|
||
| public async Task<IActionResult> HandleUnregisterActionAsync([FromBody] string url) | ||
| { | ||
| string safeUrlForLog = url; | ||
| if (string.IsNullOrWhiteSpace(url)) | ||
| { | ||
| safeUrlForLog = url.Replace("\r", "").Replace("\n", ""); | ||
| return new BadRequestObjectResult("URL cannot be empty."); | ||
| } | ||
| url = url.Trim(); | ||
|
|
||
| var removed = await base.RemoveListenerAsync(url); | ||
|
|
||
| if (!removed) | ||
| { | ||
| return new NotFoundObjectResult(new { Message = $"URL not found: {url}" }); | ||
| } | ||
|
|
||
| _logger.LogInformation("Unregistered webhook listener: {Url}", safeUrlForLog); | ||
| return new OkObjectResult(new { Message = $"Listener removed: {url}" }); | ||
| } | ||
|
|
||
| public async Task<IActionResult> HandleBroadcastActionAsync([FromBody] IWebHookPayload payload) | ||
| { | ||
| var listeners = await base.GetListenersAsync(); | ||
|
|
||
| if (!listeners.Any()) | ||
| return new BadRequestObjectResult("No listeners registered to broadcast to."); | ||
|
|
||
| switch (payload) | ||
| { | ||
| case WebhookPayload p: | ||
| p.Timestamp = DateTime.UtcNow; | ||
|
|
||
| break; | ||
|
|
||
| case DiscordWebhookPayload p: | ||
| break; | ||
|
|
||
| default: | ||
| _logger.LogWarning("Received unsupported payload type: {Type}", payload.GetType().Name); | ||
| return new BadRequestObjectResult(new { Message = "Unsupported webhook payload type." }); | ||
| } | ||
|
|
||
| _logger.LogInformation("Broadcasting test payload: {Message}", payload.content); | ||
| await base.BroadcastAsync(payload); | ||
| return new OkObjectResult(new | ||
| { | ||
| Message = $"Broadcast sent for message: '{payload.content}'. Check logs for delivery status." | ||
| }); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| public class BaseWebhookService | ||
| { | ||
| protected readonly IWebhookRepository _repo; | ||
| protected readonly HttpClient _client = new(); | ||
| protected readonly ILogger<IWebhookService> _logger; | ||
|
|
||
| public BaseWebhookService(IWebhookRepository repo, ILogger<IWebhookService> logger) | ||
| { | ||
| _repo = repo; | ||
| _logger = logger; | ||
| } | ||
|
|
||
| public async Task<IEnumerable<string>> GetListenersAsync() | ||
| { | ||
| var urls = await _repo.GetAllUrlsAsync(); | ||
| return urls.Select(u => u.Url); | ||
| } | ||
|
|
||
| public async Task<IEnumerable<string>> GetListenersAsync(WebhookType type = WebhookType.Default) | ||
| { | ||
| var urls = await _repo.GetUrlsOfTypeAsync(type); | ||
| return urls.Select(u => u.Url); | ||
| } | ||
|
|
||
| public async Task AddListenerAsync(string url, WebhookType type = default) | ||
| { | ||
| await _repo.AddUrlAsync(url, type); | ||
| } | ||
|
|
||
| public async Task<bool> RemoveListenerAsync(string url) | ||
| { | ||
| var result = await _repo.DeleteUrlAsync(url); | ||
| return result > 0; | ||
| } | ||
|
|
||
| //basic broadcast for all | ||
| public async Task BroadcastAsync<T>(T payload) where T : class | ||
| { | ||
| IEnumerable<string> urls = await GetListenersAsync(); | ||
| await BroadcastAsync(payload, urls); | ||
| } | ||
| //derived for the payloads | ||
| public async Task BroadcastAsync<T>(T payload, IEnumerable<string> urls) where T : class | ||
| { | ||
| var tasks = urls.Select(async url => | ||
| { | ||
| try | ||
| { | ||
| await _client.PostAsJsonAsync(url, payload); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogWarning(ex, "Webhook POST failed for URL: {url}", url); | ||
| } | ||
| }); | ||
| await Task.WhenAll(tasks); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.