78 lines
2.6 KiB
C#
78 lines
2.6 KiB
C#
using System;
|
|
using System.ComponentModel;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
using Jellyfin.Plugin.MediaCleaner.Enums;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Jellyfin.Plugin.MediaCleaner.Helpers;
|
|
|
|
public class HttpHelper
|
|
{
|
|
private string _baseAddress { get; }
|
|
private HttpClient _httpClient { get; }
|
|
|
|
private static Configuration Configuration =>
|
|
Plugin.Instance!.Configuration;
|
|
|
|
public HttpHelper(ServerType serverType)
|
|
{
|
|
_httpClient = new HttpClient();
|
|
|
|
// Set the default request headers
|
|
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
_httpClient.DefaultRequestHeaders.Add("X-Api-Key", RetrieveApiKey(serverType));
|
|
|
|
_baseAddress = RetrieveBaseAddress(serverType);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sends a JSON request and returns the raw JSON element response.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Do NOT create a new HttpClient on every call; reuse one instance (DI or a singleton) to avoid socket exhaustion.
|
|
/// </remarks>
|
|
public async Task<JsonElement> SendHttpRequestAsync(HttpMethod method, string path, object? body = null)
|
|
{
|
|
var uri = new UriBuilder($"{_baseAddress}{path}").Uri;
|
|
using var request = new HttpRequestMessage(method, uri);
|
|
|
|
if (body != null)
|
|
{
|
|
var json = JsonSerializer.Serialize(body);
|
|
request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
|
|
}
|
|
|
|
var response = await _httpClient.SendAsync(request).ConfigureAwait(false);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
return JsonSerializer.Deserialize<JsonElement>(responseBody);
|
|
}
|
|
|
|
private string RetrieveApiKey(ServerType serverType)
|
|
{
|
|
return serverType switch
|
|
{
|
|
ServerType.Sonarr => Configuration.SonarrAPIKey,
|
|
ServerType.SonarrAnime => Configuration.SonarrAnimeAPIKey,
|
|
ServerType.Radarr => Configuration.RadarrAPIKey,
|
|
_ => string.Empty,
|
|
};
|
|
}
|
|
|
|
private string RetrieveBaseAddress(ServerType serverType)
|
|
{
|
|
return serverType switch
|
|
{
|
|
ServerType.Sonarr => Configuration.SonarrAddress,
|
|
ServerType.SonarrAnime => Configuration.SonarrAnimeAddress,
|
|
ServerType.Radarr => Configuration.RadarrAddress,
|
|
_ => string.Empty,
|
|
};
|
|
}
|
|
}
|