2020-12-20 20:56:40 +08:00
|
|
|
using System;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Net.Http;
|
|
|
|
using System.Text;
|
|
|
|
using System.Threading.Tasks;
|
2021-01-01 14:46:27 +08:00
|
|
|
using BililiveRecorder.Core.Config.V2;
|
2020-12-20 20:56:40 +08:00
|
|
|
using Newtonsoft.Json;
|
2021-02-23 18:03:37 +08:00
|
|
|
using Serilog;
|
2020-12-20 20:56:40 +08:00
|
|
|
|
2021-02-23 18:03:37 +08:00
|
|
|
namespace BililiveRecorder.Core.SimpleWebhook
|
2020-12-20 20:56:40 +08:00
|
|
|
{
|
2021-02-23 18:03:37 +08:00
|
|
|
public class BasicWebhookV1
|
2020-12-20 20:56:40 +08:00
|
|
|
{
|
2021-02-23 18:03:37 +08:00
|
|
|
private static readonly ILogger logger = Log.ForContext<BasicWebhookV1>();
|
2020-12-20 20:56:40 +08:00
|
|
|
private static readonly HttpClient client;
|
|
|
|
|
2021-01-01 14:46:27 +08:00
|
|
|
private readonly ConfigV2 Config;
|
2020-12-20 20:56:40 +08:00
|
|
|
|
2021-02-23 18:03:37 +08:00
|
|
|
static BasicWebhookV1()
|
2020-12-20 20:56:40 +08:00
|
|
|
{
|
|
|
|
client = new HttpClient();
|
2021-02-26 21:57:10 +08:00
|
|
|
client.DefaultRequestHeaders.Add("User-Agent", $"BililiveRecorder/{GitVersionInformation.FullSemVer}");
|
2020-12-20 20:56:40 +08:00
|
|
|
}
|
|
|
|
|
2021-02-23 18:03:37 +08:00
|
|
|
public BasicWebhookV1(ConfigV2 config)
|
2020-12-20 20:56:40 +08:00
|
|
|
{
|
|
|
|
this.Config = config ?? throw new ArgumentNullException(nameof(config));
|
|
|
|
}
|
|
|
|
|
2021-02-23 18:03:37 +08:00
|
|
|
public async Task SendAsync(RecordEndData data)
|
2020-12-20 20:56:40 +08:00
|
|
|
{
|
2021-01-01 14:46:27 +08:00
|
|
|
var urls = this.Config.Global.WebHookUrls;
|
2020-12-20 20:56:40 +08:00
|
|
|
if (string.IsNullOrWhiteSpace(urls)) return;
|
|
|
|
|
|
|
|
var dataStr = JsonConvert.SerializeObject(data, Formatting.None);
|
|
|
|
using var body = new ByteArrayContent(Encoding.UTF8.GetBytes(dataStr));
|
|
|
|
body.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
|
|
|
|
2021-01-01 14:46:27 +08:00
|
|
|
var tasks = urls!
|
2020-12-20 20:56:40 +08:00
|
|
|
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
|
|
|
|
.Select(x => x.Trim())
|
|
|
|
.Where(x => !string.IsNullOrWhiteSpace(x))
|
|
|
|
.Select(x => this.SendImplAsync(x, body));
|
|
|
|
|
|
|
|
await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task SendImplAsync(string url, HttpContent data)
|
|
|
|
{
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
|
|
try
|
|
|
|
{
|
|
|
|
var result = await client.PostAsync(url, data).ConfigureAwait(false);
|
|
|
|
result.EnsureSuccessStatusCode();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
2021-02-23 18:03:37 +08:00
|
|
|
logger.Warning(ex, "发送 Webhook 到 {Url} 失败", url);
|
2020-12-20 20:56:40 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|