DocSpace-client/common/ASC.Webhooks/WebhookSender.cs

104 lines
3.7 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ASC.Common;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Web.Webhooks;
using ASC.Webhooks.Dao.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ASC.Webhooks
{
[Singletone]
public class WebhookSender
{
private const int repeatCount = 5;
private static readonly HttpClient httpClient = new HttpClient();
private IServiceProvider ServiceProvider { get; }
private ILog Log { get; }
public WebhookSender(IOptionsMonitor<ILog> options, IServiceProvider serviceProvider)
{
Log = options.Get("ASC.Webhooks");
ServiceProvider = serviceProvider;
}
public async Task Send(WebhookRequest webhookRequest)
{
var URI = webhookRequest.URI;
var secretKey = webhookRequest.SecretKey;
using var scope = ServiceProvider.CreateScope();
var dbWorker = scope.ServiceProvider.GetService<DbWorker>();
for (int i = 0; i < repeatCount; i++)
{
try
{
var testRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8092/api/2.0/authentication.json");
string httpContent = @"{ ""userName"":""www.vna-97@mail.ru"", ""password"":""265676-333"" }";
testRequest.Content = new StringContent(
httpContent,
Encoding.UTF8,
"application/json");
var testResponse = httpClient.Send(testRequest);
//HttpResponseMessage testResponseCalendar =httpClient.GetAsync("http://localhost:8092/api/2.0/calendar/info");
//var token = "1FR2TsR3kXu2zor7fModuf/3nBJRPI4I7LG5x3ODzTVVgFmUd3NguHEmVqDNMJkNc7MRJjeacv+UaAOlRmLcUyCBtEt54Hzd6TCADQtzUEVvl2M20tX0uYd8sftTdIn/faWV415KXFsY3E16StTZ5A==";
var request = new HttpRequestMessage(HttpMethod.Post, URI);
request.Headers.Add("Accept", "*/*");
request.Headers.Add("Secret","SHA256=" + GetSecretHash(secretKey, webhookRequest.Data));
//request.Headers.Add("Authorization", token);
request.Content = new StringContent(
webhookRequest.Data,
Encoding.UTF8,
"application/json");
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
dbWorker.UpdateStatus(webhookRequest.Id, ProcessStatus.Success);
Log.Debug("Response: " + response);
break;
}
}
catch (Exception ex)
{
if(i == repeatCount)
{
dbWorker.UpdateStatus(webhookRequest.Id, ProcessStatus.Failed);
}
Log.Error(ex.Message);
continue;
}
}
}
private string GetSecretHash(string secretKey, string body)
{
string computedSignature;
var secretBytes = Encoding.UTF8.GetBytes(secretKey);
using (var hasher = new HMACSHA256(secretBytes))
{
var data = Encoding.UTF8.GetBytes(body);
computedSignature = BitConverter.ToString(hasher.ComputeHash(data));
}
return computedSignature;
}
}
}