62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using System.Net.Http.Json;
|
|
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using System.Xml.Linq;
|
|
|
|
namespace Salmon.Core;
|
|
|
|
public class Transmitter
|
|
{
|
|
Cliff.Translator Translator { get; } = new();
|
|
HttpClient Client { get; } = new();
|
|
public Uri? BaseUrl { get; set; } = null;
|
|
|
|
public async Task SendAsync(Uri uri, IEnumerable<Element> elements, CancellationToken tk = default)
|
|
{
|
|
List<Triplet> triplets = new();
|
|
foreach (Element element in elements)
|
|
triplets.AddRange(Translator.Encode(element));
|
|
|
|
var result = await Client.PostAsJsonAsync(uri, triplets, cancellationToken: tk);
|
|
|
|
if (!result.IsSuccessStatusCode)
|
|
throw new Exception($"SendAsync call return code {result.StatusCode} when call {uri}.");
|
|
|
|
}
|
|
|
|
public async Task SendAsync(Uri uri, IEnumerable<Event> events, CancellationToken tk = default)
|
|
{
|
|
await Client.PostAsJsonAsync(uri, events, cancellationToken: tk);
|
|
}
|
|
|
|
public async Task SendAsync(IEnumerable<Element> elements, CancellationToken tk = default)
|
|
{
|
|
if (BaseUrl is null)
|
|
throw new Exception("SendAsync call without defining BaseUrl.");
|
|
|
|
Uri uri = new Uri(BaseUrl, "Push/Elements");
|
|
|
|
await SendAsync(uri, elements, tk);
|
|
}
|
|
|
|
public async Task SendAsync(Element element, CancellationToken tk = default)
|
|
{
|
|
await SendAsync(new[] { element });
|
|
}
|
|
|
|
public async Task SendAsync(IEnumerable<Event> events, CancellationToken tk = default)
|
|
{
|
|
if (BaseUrl is null)
|
|
throw new Exception("SendAsync call without defining BaseUrl.");
|
|
|
|
Uri uri = new Uri(BaseUrl, "Push/Events");
|
|
|
|
await Client.PostAsJsonAsync(uri, events, tk);
|
|
}
|
|
|
|
public async Task SendAsync(Event ev, CancellationToken tk = default)
|
|
{
|
|
await SendAsync(new[] { ev });
|
|
}
|
|
}
|