Updated
This commit is contained in:
1 parent
2c5b69bf2c
commit
22dee59f47
132 files changed
+19653
-7192
No files matched your search
@@ -0,0 +1,91 @@
|
||||
using EonaCat.Json;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.Connections.REST
|
||||
{
|
||||
public class WebhookManager : IDisposable
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, HashSet<string>> _webhooks = new();
|
||||
private readonly HttpClient _httpClient = new();
|
||||
private bool _disposed;
|
||||
|
||||
public void Register(string eventName, string url)
|
||||
{
|
||||
var urls = _webhooks.GetOrAdd(eventName, _ => new HashSet<string>(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<string, string[]> GetRegistrations()
|
||||
{
|
||||
var result = new Dictionary<string, string[]>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user