Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix reachable and IP leak test #44

Merged
merged 2 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions UmlautAdaptarr/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@

internal class Program
{
private static void Main(string[] args)
private static void Main(string[] args) {
MainAsync(args).Wait();
}

private static async Task MainAsync(string[] args)
{
Helper.ShowLogo();
Helper.ShowInformation();
// TODO:
// add option to sort by nzb age
var builder = WebApplication.CreateBuilder(args);
Expand Down Expand Up @@ -43,9 +45,9 @@ private static void Main(string[] args)
builder.AddTitleLookupService();
builder.Services.AddSingleton<SearchItemLookupService>();
builder.Services.AddSingleton<TitleMatchingService>();
builder.AddSonarrSupport();
builder.AddLidarrSupport();
builder.AddReadarrSupport();
await builder.AddSonarrSupport();
await builder.AddLidarrSupport();
await builder.AddReadarrSupport();
builder.Services.AddSingleton<CacheService>();
builder.Services.AddSingleton<ProxyRequestService>();
builder.Services.AddSingleton<ArrApplicationFactory>();
Expand All @@ -54,6 +56,13 @@ private static void Main(string[] args)

var app = builder.Build();

Helper.ShowLogo();

if (app.Configuration.GetValue<bool>("IpLeakTest:Enabled"))
{
await Helper.ShowInformation();
}

GlobalStaticLogger.Initialize(app.Services.GetService<ILoggerFactory>()!);
app.UseHttpsRedirection();
app.UseAuthorization();
Expand Down Expand Up @@ -109,4 +118,4 @@ private static void ConfigureLogger(ConfigurationManager configuration)
//.Enrich.With(new ApiKeyMaskingEnricher("appsettings.json")) // TODO - Not working currently
.CreateLogger();
}
}
}
4 changes: 2 additions & 2 deletions UmlautAdaptarr/Utilities/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ public static void ShowLogo()
"\r\n _ _ _ _ ___ _ _ \r\n| | | | | | | | / _ \\ | | | | \r\n| | | |_ __ ___ | | __ _ _ _| |_/ /_\\ \\ __| | __ _ _ __ | |_ __ _ _ __ _ __ \r\n| | | | '_ ` _ \\| |/ _` | | | | __| _ |/ _` |/ _` | '_ \\| __/ _` | '__| '__|\r\n| |_| | | | | | | | (_| | |_| | |_| | | | (_| | (_| | |_) | || (_| | | | | \r\n \\___/|_| |_| |_|_|\\__,_|\\__,_|\\__\\_| |_/\\__,_|\\__,_| .__/ \\__\\__,_|_| |_| \r\n | | \r\n |_| \r\n");
}

public static void ShowInformation()
public static async Task ShowInformation()
{
Console.WriteLine("--------------------------[IP Leak Test]-----------------------------");
var ipInfo = GetPublicIpAddressInfoAsync().GetAwaiter().GetResult();
var ipInfo = await GetPublicIpAddressInfoAsync();

if (ipInfo != null)
{
Expand Down
12 changes: 6 additions & 6 deletions UmlautAdaptarr/Utilities/ServicesExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static class ServicesExtensions
/// <param name="builder">The <see cref="WebApplicationBuilder" /> to configure the service collection.</param>
/// <param name="sectionName">The name of the configuration section containing service options.</param>
/// <returns>The configured <see cref="WebApplicationBuilder" />.</returns>
private static WebApplicationBuilder AddServicesWithOptions<TOptions, TService, TInterface>(
private static async Task<WebApplicationBuilder> AddServicesWithOptions<TOptions, TService, TInterface>(
this WebApplicationBuilder builder, string sectionName)
where TOptions : class, new()
where TService : class, TInterface
Expand Down Expand Up @@ -57,9 +57,9 @@ private static WebApplicationBuilder AddServicesWithOptions<TOptions, TService,

foreach (var option in optionsArray)
{
GlobalInstanceOptionsValidator validator = new GlobalInstanceOptionsValidator();
GlobalInstanceOptionsValidator validator = new();

var results = validator.Validate(option as GlobalInstanceOptions);
var results = await validator.ValidateAsync(option as GlobalInstanceOptions);

if (!results.IsValid)
{
Expand Down Expand Up @@ -143,7 +143,7 @@ private static WebApplicationBuilder AddServiceWithOptions<TOptions, TService>(t
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder" /> to configure the service collection.</param>
/// <returns>The configured <see cref="WebApplicationBuilder" />.</returns>
public static WebApplicationBuilder AddSonarrSupport(this WebApplicationBuilder builder)
public static Task<WebApplicationBuilder> AddSonarrSupport(this WebApplicationBuilder builder)
{
// builder.Serviceses.AddSingleton<IOptionsMonitoSonarrInstanceOptionsns>, OptionsMonitoSonarrInstanceOptionsns>>();
return builder.AddServicesWithOptions<SonarrInstanceOptions, SonarrClient, IArrApplication>("Sonarr");
Expand All @@ -154,7 +154,7 @@ public static WebApplicationBuilder AddSonarrSupport(this WebApplicationBuilder
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder" /> to configure the service collection.</param>
/// <returns>The configured <see cref="WebApplicationBuilder" />.</returns>
public static WebApplicationBuilder AddLidarrSupport(this WebApplicationBuilder builder)
public static Task<WebApplicationBuilder> AddLidarrSupport(this WebApplicationBuilder builder)
{
return builder.AddServicesWithOptions<LidarrInstanceOptions, LidarrClient, IArrApplication>("Lidarr");
}
Expand All @@ -164,7 +164,7 @@ public static WebApplicationBuilder AddLidarrSupport(this WebApplicationBuilder
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder" /> to configure the service collection.</param>
/// <returns>The configured <see cref="WebApplicationBuilder" />.</returns>
public static WebApplicationBuilder AddReadarrSupport(this WebApplicationBuilder builder)
public static Task<WebApplicationBuilder> AddReadarrSupport(this WebApplicationBuilder builder)
{
return builder.AddServicesWithOptions<ReadarrInstanceOptions, ReadarrClient, IArrApplication>("Readarr");
}
Expand Down
42 changes: 14 additions & 28 deletions UmlautAdaptarr/Validator/GlobalInstanceOptionsValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ namespace UmlautAdaptarr.Validator;

public class GlobalInstanceOptionsValidator : AbstractValidator<GlobalInstanceOptions>
{
private readonly static HttpClient httpClient = new() {
Timeout = TimeSpan.FromSeconds(3)
};

public GlobalInstanceOptionsValidator()
{
RuleFor(x => x.Enabled).NotNull();
Expand All @@ -14,12 +18,14 @@ public GlobalInstanceOptionsValidator()
{
RuleFor(x => x.Host)
.NotEmpty().WithMessage("Host is required when Enabled is true.")
.Must(BeAValidUrl).WithMessage("Host/Url must start with http:// or https:// and be a valid address.")
.Must(BeReachable)
.WithMessage("Host/Url is not reachable. Please check your Host or your UmlautAdaptrr Settings");
.Must(BeAValidUrl).WithMessage("Host/Url must start with http:// or https:// and be a valid address.");

RuleFor(x => x.ApiKey)
.NotEmpty().WithMessage("ApiKey is required when Enabled is true.");

RuleFor(x => x)
.MustAsync(BeReachable)
.WithMessage("Host/Url is not reachable. Please check your Host or your UmlautAdaptrr Settings");
});
}

Expand All @@ -29,50 +35,30 @@ private bool BeAValidUrl(string url)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}

private static bool BeReachable(string url)
private static async Task<bool> BeReachable(GlobalInstanceOptions opts, CancellationToken cancellationToken)
{
var endTime = DateTime.Now.AddMinutes(3);
var reachable = false;
var url = $"{opts.Host}/api?apikey={opts.ApiKey}";

while (DateTime.Now < endTime)
{
try
{
// TODO use HttpClient here
var request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.Timeout = 3000;
using var response = (HttpWebResponse)request.GetResponse();
using var response = await httpClient.GetAsync(url, cancellationToken);
reachable = response.StatusCode == HttpStatusCode.OK;
if (reachable)
if (response.IsSuccessStatusCode)
{
break;
}
// If status is 301/302 (Found), follow the redirect manually
else if (response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Found)
{
var redirectUrl = response.Headers["Location"]; // Get the redirect URL
if (!string.IsNullOrEmpty(redirectUrl))
{
// Create a new request for the redirected URL
var redirectRequest = (HttpWebRequest)WebRequest.Create(redirectUrl);
redirectRequest.Timeout = 3000;
using var redirectResponse = (HttpWebResponse)redirectRequest.GetResponse();
reachable = redirectResponse.StatusCode == HttpStatusCode.OK;
if (reachable)
{
break;
}
}
}
}
catch
{

}

// Wait for 15 seconds for next try
Console.WriteLine($"The URL \"{url}\" is not reachable. Next attempt in 15 seconds...");
Console.WriteLine($"The URL \"{opts.Host}\" is not reachable. Next attempt in 15 seconds...");
Thread.Sleep(15000);
}

Expand Down
3 changes: 3 additions & 0 deletions UmlautAdaptarr/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,8 @@
"Enabled": false,
"Host": "your_readarr_host_url",
"ApiKey": "your_readarr_api_key"
},
"IpLeakTest": {
"Enabled": false
}
}