using EonaCat.Json; using System.Collections.Concurrent; using System.Text; namespace EonaCat.Connections.REST { public class WebhookManager : IDisposable { private readonly ConcurrentDictionary> _webhooks = new(); private readonly HttpClient _httpClient = new(); private bool _disposed; public void Register(string eventName, string url) { var urls = _webhooks.GetOrAdd(eventName, _ => new HashSet(StringComparer.OrdinalIgnoreCase)); lock (urls) { urls.Add(url); } } public void Unregister(string eventName, string url) { if (_webhooks.TryGetValue(eventName, out var urls)) { lock (urls) { urls.Remove(url); } } } public void UnregisterAll(string eventName) { _webhooks.TryRemove(eventName, out _); } public async Task FireAsync(string eventName, object payload) { if (!_webhooks.TryGetValue(eventName, out var urls)) { return; } string[] snapshot; lock (urls) { snapshot = urls.ToArray(); } var json = JsonHelper.ToJson(payload); foreach (var url in snapshot) { try { using var content = new StringContent(json, Encoding.UTF8, "application/json"); await _httpClient.PostAsync(url, content).ConfigureAwait(false); } catch { } } } public Dictionary GetRegistrations() { var result = new Dictionary(); foreach (var kvp in _webhooks) { lock (kvp.Value) { result[kvp.Key] = kvp.Value.ToArray(); } } return result; } public void Dispose() { if (_disposed) { return; } _disposed = true; _httpClient.Dispose(); } } }