CShock/CShocker/Devices/Additional/ApiHttpClient.cs

66 lines
2.9 KiB
C#
Raw Normal View History

using System.Diagnostics;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Logging;
namespace CShocker.Devices.Additional;
public static class ApiHttpClient
{
2025-01-16 21:38:30 +01:00
private static readonly ProductInfoHeaderValue UserAgent = GetUserAgent();
private static ProductInfoHeaderValue GetUserAgent()
{
Assembly assembly = Assembly.GetExecutingAssembly();
2025-01-16 21:38:30 +01:00
FileVersionInfo fvi;
if (assembly.Location == String.Empty)
{
DirectoryInfo dir = new (AppContext.BaseDirectory);
FileInfo? f = dir.GetFiles("*.exe").FirstOrDefault();
if (f is null)
return new("CShocker", "Release");
fvi = FileVersionInfo.GetVersionInfo(f.FullName);
}
else
{
fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
}
return new (fvi.ProductName ?? fvi.FileName, fvi.ProductVersion);
}
internal static HttpResponseMessage MakeAPICall(HttpMethod method, string uri, string? jsonContent, ILogger? logger = null, params ValueTuple<string, string>[] customHeaders)
{
HttpRequestMessage request = new (method, uri)
{
Headers =
{
2025-01-16 21:38:30 +01:00
UserAgent = { UserAgent },
Accept = { new MediaTypeWithQualityHeaderValue("application/json") },
}
};
if (jsonContent is not null && jsonContent.Length > 0)
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(jsonContent))
{
Headers = { ContentType = MediaTypeHeaderValue.Parse("application/json") }
};
foreach ((string, string) customHeader in customHeaders)
request.Headers.Add(customHeader.Item1, customHeader.Item2);
2024-02-12 03:06:28 +01:00
logger?.Log(LogLevel.Debug, string.Join("\n\t",
"Request:",
$"\u251c\u2500\u2500 URI: {request.RequestUri}",
$"\u251c\u2500\u2510 Headers: {string.Concat(request.Headers.Select(h => $"\n\t\u2502 {(request.Headers.Last().Key.Equals(h.Key) ? "\u2514" : "\u251c")} {h.Key}: {string.Join(", ", h.Value)}"))}",
$"\u2514\u2500\u2500 Content: {request.Content?.ReadAsStringAsync().Result}"));
HttpClient httpClient = new();
HttpResponseMessage response = httpClient.Send(request);
2024-02-12 03:06:28 +01:00
logger?.Log(!response.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, string.Join("\n\t",
2025-01-16 20:55:24 +01:00
"Response:",
2024-02-12 03:06:28 +01:00
$"\u251c\u2500\u2500 URI: {request.RequestUri}",
$"\u251c\u2500\u2510 Headers: {string.Concat(response.Headers.Select(h => $"\n\t\u2502 {(response.Headers.Last().Key.Equals(h.Key) ? "\u2514" : "\u251c")} {h.Key}: {string.Join(", ", h.Value)}"))}",
2025-01-16 20:55:24 +01:00
$"\u2514\u2500\u2500 Content: {response.Content.ReadAsStringAsync().Result}"));
httpClient.Dispose();
return response;
}
}