|
| 1 | +using DotEnv.Core; |
| 2 | + |
| 3 | +namespace Playtesters.API.Services; |
| 4 | + |
| 5 | +public interface INotificationService |
| 6 | +{ |
| 7 | + Task SendAsync(NotificationMessage message); |
| 8 | +} |
| 9 | + |
| 10 | +public record NotificationMessage( |
| 11 | + string TesterName, |
| 12 | + string IpAddress, |
| 13 | + string Country, |
| 14 | + string City, |
| 15 | + DateTime Timestamp |
| 16 | +); |
| 17 | + |
| 18 | +public class NotificationService : INotificationService |
| 19 | +{ |
| 20 | + private readonly ILogger<NotificationService> _logger; |
| 21 | + private readonly HttpClient _httpClient; |
| 22 | + private readonly string _discordWebhookUrl; |
| 23 | + private record DiscordWebhookPayload(string Content); |
| 24 | + |
| 25 | + public NotificationService( |
| 26 | + HttpClient httpClient, |
| 27 | + ILogger<NotificationService> logger) |
| 28 | + { |
| 29 | + var envReader = new EnvReader(); |
| 30 | + if (!envReader.TryGetStringValue("DISCORD_WEBHOOK_URL", out var webhookUrl)) |
| 31 | + { |
| 32 | + logger.LogError("'DISCORD_WEBHOOK_URL' has not been set as an environment variable"); |
| 33 | + } |
| 34 | + _discordWebhookUrl = webhookUrl ?? string.Empty; |
| 35 | + _logger = logger; |
| 36 | + _httpClient = httpClient; |
| 37 | + } |
| 38 | + |
| 39 | + public async Task SendAsync(NotificationMessage message) |
| 40 | + { |
| 41 | + if (string.IsNullOrWhiteSpace(_discordWebhookUrl)) |
| 42 | + { |
| 43 | + _logger.LogError("Discord webhook URL is not configured. Skipping notification for Tester {TesterName}", message.TesterName); |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + var content = |
| 48 | + $""" |
| 49 | + 🔔 *New validated access* |
| 50 | + 👤 Tester: **{message.TesterName}** |
| 51 | + 🌐 IP: `{message.IpAddress}` |
| 52 | + 🌍 Country: {message.Country} |
| 53 | + 🏙️ City: {message.City} |
| 54 | + ⏰ {message.Timestamp:yyyy-MM-dd HH:mm:ss} |
| 55 | + """; |
| 56 | + |
| 57 | + try |
| 58 | + { |
| 59 | + var payload = new DiscordWebhookPayload(content); |
| 60 | + var response = await _httpClient.PostAsJsonAsync(_discordWebhookUrl, payload); |
| 61 | + response.EnsureSuccessStatusCode(); |
| 62 | + } |
| 63 | + catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException) |
| 64 | + { |
| 65 | + _logger.LogError(ex, "DiscordWebhook timed out for Tester {TesterName}", message.TesterName); |
| 66 | + } |
| 67 | + catch (HttpRequestException ex) |
| 68 | + { |
| 69 | + _logger.LogError(ex, "DiscordWebhook HTTP error for Tester {TesterName}", message.TesterName); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments