Просмотр исходного кода

Simple file size calculation utility

Lukas Angerer 3 лет назад
Родитель
Сommit
6186cd35a0

+ 1 - 1
src/RunnersMeet.Server/Controllers/ApiSettings.cs

@@ -4,6 +4,6 @@ public class ApiSettings
 {
 	public const string SectionName = "ApiSettings";
 
-	public long GpxFileSizeLimit { get; set; } = 2 << 16; // 64KB
+	public long GpxFileSizeLimit { get; set; } = FileSize.FromMagnitudeValue(64, FileSize.Magnitude.Kilo).Bytes;
 	public int PageSize { get; set; } = 10;
 }

+ 1 - 1
src/RunnersMeet.Server/Controllers/TracksController.cs

@@ -55,7 +55,7 @@ public class TracksController : ControllerBase
 	{
 		if (file.Length > _settings.GpxFileSizeLimit)
 		{
-			throw new ApiException($"Uploaded tracks cannot be larger than {_settings.GpxFileSizeLimit / (1024 * 1024)}MB");
+			throw new ApiException($"Uploaded tracks cannot be larger than {new FileSize(_settings.GpxFileSizeLimit).ToHumanReadable()}");
 		}
 
 		var fileName = await _fileStorage.UploadFileAsync(file, cancellationToken);

+ 55 - 0
src/RunnersMeet.Server/FileSize.cs

@@ -0,0 +1,55 @@
+namespace RunnersMeet.Server;
+
+public class FileSize
+{
+	private const long MagnitudeStep = 1024;
+
+	private static readonly IDictionary<Magnitude, string> UnitMap = new Dictionary<Magnitude, string>
+	{
+		[Magnitude.Single] = "B",
+		[Magnitude.Kilo] = "KB",
+		[Magnitude.Mega] = "MB",
+		[Magnitude.Giga] = "GB",
+		[Magnitude.Tera] = "TB",
+	};
+
+	public static FileSize FromMagnitudeValue(long number, Magnitude magnitude)
+	{
+		return new FileSize(number * (1 << (10 * (int)magnitude)));
+	}
+
+	public static explicit operator FileSize(long value)
+	{
+		return new FileSize(value);
+	}
+
+	public long Bytes { get; }
+
+	public FileSize(long bytes)
+	{
+		Bytes = bytes;
+	}
+
+	public string ToHumanReadable()
+	{
+		double value = Bytes;
+		var magnitude = Magnitude.Single;
+
+		while (value > MagnitudeStep && (int)magnitude < (int)Magnitude.Tera)
+		{
+			value /= MagnitudeStep;
+			magnitude = (Magnitude)((int)magnitude + 1);
+		}
+
+		return $"{value:0.00} {UnitMap[magnitude]}";
+	}
+
+	public enum Magnitude
+	{
+		Single = 0,
+		Kilo = 1,
+		Mega = 2,
+		Giga = 3,
+		Tera = 4
+	}
+}