89 lines
2.9 KiB
C#
89 lines
2.9 KiB
C#
using System.Globalization;
|
|
|
|
namespace Flypaper.Core.Settings;
|
|
|
|
public static class RuntimeSettingsParser
|
|
{
|
|
private const int MaxLimit = 100_000;
|
|
private const int MaxRetentionDays = 3650;
|
|
|
|
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
|
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
|
|
|
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
|
{
|
|
var errors = new Dictionary<string, string>();
|
|
|
|
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
|
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
|
|
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
|
|
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
|
|
|
|
if (maxConnections is { } total && perIp is { } single && single > total
|
|
&& !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
|
|
{
|
|
errors[nameof(input.MaxConnectionsPerIp)] = "Darf nicht größer sein als die Gesamtzahl der Verbindungen.";
|
|
}
|
|
|
|
if (errors.Count > 0)
|
|
{
|
|
return new RuntimeSettingsParseResult(null, errors);
|
|
}
|
|
|
|
var settings = new RuntimeSettings(
|
|
maxConnections!.Value,
|
|
perIp!.Value,
|
|
hold!.Value,
|
|
retention!.Value,
|
|
input.IgnorePrivateNetworks);
|
|
return new RuntimeSettingsParseResult(settings, errors);
|
|
}
|
|
|
|
private static TimeSpan? ParseTimeSpan(
|
|
string? raw,
|
|
string field,
|
|
TimeSpan min,
|
|
TimeSpan max,
|
|
Dictionary<string, string> errors)
|
|
{
|
|
var text = raw?.Trim();
|
|
if (string.IsNullOrEmpty(text))
|
|
{
|
|
errors[field] = "Pflichtfeld.";
|
|
return null;
|
|
}
|
|
|
|
if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
|
|
{
|
|
errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10.";
|
|
return null;
|
|
}
|
|
|
|
if (value < min || value > max)
|
|
{
|
|
errors[field] = $"Zwischen {min.ToString("c", CultureInfo.InvariantCulture)} und {max.ToString("c", CultureInfo.InvariantCulture)}.";
|
|
return null;
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private static int? ParseInt(string? raw, string field, int min, int max, Dictionary<string, string> errors)
|
|
{
|
|
var text = raw?.Trim();
|
|
if (string.IsNullOrEmpty(text))
|
|
{
|
|
errors[field] = "Pflichtfeld.";
|
|
return null;
|
|
}
|
|
|
|
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value < min || value > max)
|
|
{
|
|
errors[field] = $"Ganze Zahl zwischen {min} und {max}.";
|
|
return null;
|
|
}
|
|
|
|
return value;
|
|
}
|
|
}
|