aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDaniel <107576740+maskedmaxx@users.noreply.github.com>2026-05-20 20:55:17 -0400
committerGitHub <noreply@github.com>2026-05-20 20:55:17 -0400
commit96b62ac8596a8ba2c028b88964ff76a8aad3e5bf (patch)
treeb55aa04d606b258b32fd48c1183507a4a16c090d
parent61703575cf9038f6a0de89bb5b9be44431439618 (diff)
parent03b35a5ababfd7bc2d0af053d8622a14cdd6b8fe (diff)
downloadslskd-96b62ac8596a8ba2c028b88964ff76a8aad3e5bf.tar.gz
Merge branch 'master' into fix/issue-1726-relay-controller-trailing-slash
-rw-r--r--src/slskd/Common/CommonExtensions.cs12
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs6
-rw-r--r--src/slskd/Common/Validation/GuidAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/NonTraversingPathAttribute.cs (renamed from src/slskd/Common/Validation/DisallowedCharactersAttribute.cs)44
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs8
-rw-r--r--src/slskd/Common/Validation/StringAttribute.cs99
-rw-r--r--src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs3
-rw-r--r--src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs101
-rw-r--r--src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs108
-rw-r--r--src/slskd/Core/Data/Migrator.cs2
-rw-r--r--src/slskd/Core/Options.cs13
-rw-r--r--src/slskd/Program.cs1
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs205
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs113
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (renamed from src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs)26
-rw-r--r--src/slskd/Transfers/API/DTO/Transfer.cs169
-rw-r--r--src/slskd/Transfers/Downloads/BatchService.cs140
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs51
-rw-r--r--src/slskd/Transfers/Extensions.cs1
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs43
-rw-r--r--src/slskd/Transfers/Types/Batch.cs118
-rw-r--r--src/slskd/Transfers/Types/BatchOptions.cs48
-rw-r--r--src/slskd/Transfers/Types/Transfer.cs208
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs54
-rw-r--r--src/web/package-lock.json407
-rw-r--r--src/web/package.json2
-rw-r--r--tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs2
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafetyTests.cs2
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs35
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs254
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs106
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs94
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs28
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs422
-rw-r--r--tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs40
-rw-r--r--tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs304
37 files changed, 2548 insertions, 803 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index e0d56511..5ff3e519 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -557,9 +557,17 @@ namespace slskd
/// <returns>The new object deserialized from the string.</returns>
public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions());
- private static JsonSerializerOptions GetJsonSerializerOptions()
+ /// <summary>
+ /// Applies the standard json serializer options to the specified instance.
+ /// </summary>
+ /// <param name="opt">The instance.</param>
+ /// <returns>The instances with the standard options applied.</returns>
+ public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt)
+ => GetJsonSerializerOptions(opt);
+
+ private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null)
{
- var options = new JsonSerializerOptions();
+ var options = opt ?? new JsonSerializerOptions();
options.Converters.Add(new IPAddressConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new KnownUnsupportedTypeConverter());
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
index 4c9f5e53..1999220f 100644
--- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -49,12 +49,6 @@ namespace slskd.Validation
{
return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path.");
}
-
- // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
- if (FileSafety.ContainsTraversalSegments(path))
- {
- return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
- }
}
return ValidationResult.Success;
diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs
new file mode 100644
index 00000000..7c04f1f9
--- /dev/null
+++ b/src/slskd/Common/Validation/GuidAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="GuidAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System;
+
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the value is a valid Guid.
+ /// </summary>
+ public class GuidAttribute : ValidationAttribute
+ {
+ public GuidAttribute(bool allowEmpty = false)
+ {
+ AllowEmpty = allowEmpty;
+ }
+
+ public bool AllowEmpty { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value is null)
+ {
+ return ValidationResult.Success;
+ }
+
+ if (value is Guid guid)
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ if (value is string str && Guid.TryParse(str, out guid))
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID");
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
index 90ed3d81..1e2616bd 100644
--- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
+++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
@@ -1,4 +1,4 @@
-// <copyright file="DisallowedCharactersAttribute.cs" company="JP Dillingham">
+// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -30,42 +30,28 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-namespace slskd.Validation;
-
-using System.ComponentModel.DataAnnotations;
-using System.Linq;
-
-/// <summary>
-/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters.
-/// </summary>
-public class DisallowedCharactersAttribute : ValidationAttribute
+namespace slskd.Validation
{
- public DisallowedCharactersAttribute(params char[] disallowed)
- {
- Disallowed = disallowed;
- }
+ using System.ComponentModel.DataAnnotations;
/// <summary>
- /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>.
+ /// Validates that the specified path does not contain traversal segments '.' or '..'.
/// </summary>
- public bool IgnoreCase { get; set; } = true;
-
- private char[] Disallowed { get; }
-
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ public class NonTraversingPathAttribute : ValidationAttribute
{
- if (value is not null and string str)
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
- var invalid = IgnoreCase
- ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)))
- : str.Where(c => Disallowed.Contains(c));
-
- if (invalid.Any())
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
- return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ var path = value.ToString();
+
+ if (FileSafety.ContainsTraversalSegments(path))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
+ }
}
- }
- return ValidationResult.Success;
+ return ValidationResult.Success;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
index edaef1be..64e418b1 100644
--- a/src/slskd/Common/Validation/RelativePathAttribute.cs
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -49,15 +49,9 @@ namespace slskd.Validation
{
return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path.");
}
-
- // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
- if (FileSafety.ContainsTraversalSegments(path))
- {
- return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
- }
}
return ValidationResult.Success;
}
}
-} \ No newline at end of file
+}
diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs
new file mode 100644
index 00000000..bb323ba2
--- /dev/null
+++ b/src/slskd/Common/Validation/StringAttribute.cs
@@ -0,0 +1,99 @@
+// <copyright file="StringAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// Validates that the value is not null or whitespace.
+ /// </summary>
+ public class StringAttribute : ValidationAttribute
+ {
+ public bool AllowNull { get; set; } = true;
+ public bool AllowEmpty { get; set; } = true;
+ public bool AllowWhiteSpace { get; set; } = true;
+ public char[] DisallowedCharacters { get; set; } = [];
+ public int MinimumLength { get; set; } = 0;
+ public int MaximumLength { get; set; } = int.MaxValue;
+ public Regex Pattern { get; set; } = null;
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ var val = (string)value;
+
+ if (val is null)
+ {
+ if (!AllowNull)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not be null");
+ }
+ else
+ {
+ return ValidationResult.Success;
+ }
+ }
+
+ if (!AllowEmpty && val is "")
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character");
+ }
+
+ // check this after empty to avoid overlap
+ if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c)))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace");
+ }
+
+ if (val.Length < MinimumLength || val.Length > MaximumLength)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters");
+ }
+
+ var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)));
+
+ if (invalid.Any())
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ }
+
+ if (Pattern is not null && Pattern.IsMatch(val))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}");
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
index 6c5810c5..1a155f18 100644
--- a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
+++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs
@@ -69,7 +69,10 @@ public class Z2025_04_01_TransferStateMigration : IMigration
var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
var txfers = schema["Transfers"];
+#pragma warning disable CS0618 // Type or member is obsolete
return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription));
+#pragma warning restore CS0618 // Type or member is obsolete
+
}
public void Apply()
diff --git a/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs
new file mode 100644
index 00000000..4fb25b1f
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs
@@ -0,0 +1,101 @@
+// <copyright file="Z2026_04_30_DropTransferStartOffsetMigration.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Migrations;
+
+using System;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Updates the Transfers table to drop the unused StartOffset column.
+/// </summary>
+public class Z2026_04_30_DropTransferStartOffsetMigration : IMigration
+{
+ public Z2026_04_30_DropTransferStartOffsetMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_04_30_DropTransferStartOffsetMigration>();
+ private string ConnectionString { get; }
+
+ public bool NeedsToBeApplied()
+ {
+ var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
+
+ var columns = schema["Transfers"];
+
+ if (columns.Any(c => c.Name == "StartOffset"))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ public void Apply()
+ {
+ if (!NeedsToBeApplied())
+ {
+ Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_04_30_DropTransferStartOffsetMigration));
+ return;
+ }
+
+ using var connection = new SqliteConnection(ConnectionString);
+ connection.Open();
+
+ using var transaction = connection.BeginTransaction();
+
+ try
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Dropping StartOffset column from the Transfers table...");
+
+ Exec("ALTER TABLE Transfers DROP COLUMN StartOffset;");
+
+ transaction.Commit();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs
new file mode 100644
index 00000000..9b373f71
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs
@@ -0,0 +1,108 @@
+// <copyright file="Z2026_05_06_AddBatchesTableMigration.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Migrations;
+
+using System;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Creates the Batches table in the Transfers database.
+/// </summary>
+public class Z2026_05_06_AddBatchesTableMigration : IMigration
+{
+ public Z2026_05_06_AddBatchesTableMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z2026_05_06_AddBatchesTableMigration>();
+ private string ConnectionString { get; }
+
+ public bool NeedsToBeApplied()
+ {
+ var schema = SchemaInspector.GetDatabaseSchema(ConnectionString);
+
+ if (schema.ContainsKey("Batches"))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ public void Apply()
+ {
+ if (!NeedsToBeApplied())
+ {
+ Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_05_06_AddBatchesTableMigration));
+ return;
+ }
+
+ using var connection = new SqliteConnection(ConnectionString);
+ connection.Open();
+
+ using var transaction = connection.BeginTransaction();
+
+ try
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Creating the Batches table...");
+
+ Exec(@"
+ CREATE TABLE Batches (
+ Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY,
+ SearchId TEXT,
+ Username TEXT,
+ Direction INTEGER NOT NULL,
+ CreatedAt TEXT NOT NULL,
+ Options TEXT
+ );");
+
+ Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);");
+
+ transaction.Commit();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs
index 7289b070..d53d7c8c 100644
--- a/src/slskd/Core/Data/Migrator.cs
+++ b/src/slskd/Core/Data/Migrator.cs
@@ -60,6 +60,8 @@ public class Migrator
{ nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) },
{ nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) },
{ nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) },
+ { nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) },
+ { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) },
};
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 51b3cab1..83e534a1 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -198,7 +198,6 @@ namespace slskd
[Argument('i', "instance-name")]
[EnvironmentVariable("INSTANCE_NAME")]
[Description("optional; a unique name for this instance")]
- [DisallowedCharacters('/', '\\')]
[RequiresRestart]
public string InstanceName { get; init; } = "default";
@@ -655,7 +654,6 @@ namespace slskd
[Description("the name for this agent")]
[StringLength(255, MinimumLength = 1)]
[NotNullOrWhiteSpace]
- [DisallowedCharacters('/', '\\')]
[Secret]
public string InstanceName { get; init; }
@@ -768,6 +766,7 @@ namespace slskd
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
[AbsolutePath]
+ [NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory;
@@ -779,6 +778,7 @@ namespace slskd
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
[AbsolutePath]
+ [NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
@@ -845,9 +845,15 @@ namespace slskd
directories?.Where(share => !IsAbsolutePath(share)).ToList()
.ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported.")));
+ // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /..
+ // which is resolved by some OS and will cause weird, unintended side effects
+ bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$");
+ directories?.Where(share => ContainsTraversalSegments(share)).ToList()
+ .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment.")));
+
(string Raw, string Alias, string Path) Digest(string share)
{
- var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$");
+ var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$");
if (matches.Any())
{
@@ -2015,6 +2021,7 @@ namespace slskd
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
[AbsolutePath]
+ [NonTraversingPath]
[RequiresRestart]
public string Socket { get; init; }
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 42f43918..d4baf276 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -780,6 +780,7 @@ namespace slskd
services.AddSingleton<ITransferService, TransferService>();
services.AddSingleton<IDownloadService, DownloadService>();
services.AddSingleton<IUploadService, UploadService>();
+ services.AddSingleton<IBatchService, BatchService>();
services.AddSingleton<FileService>();
services.AddSingleton<IRelayService, RelayService>();
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 494ee722..3191e3a8 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -42,6 +42,7 @@ namespace slskd.Transfers.API
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using slskd.Users;
@@ -217,7 +218,7 @@ namespace slskd.Transfers.API
}
/// <summary>
- /// Enqueues the specified download.
+ /// (Obsolete) Enqueues the specified download.
/// </summary>
/// <param name="username">The username of the download source.</param>
/// <param name="requests">The list of download requests.</param>
@@ -225,6 +226,7 @@ namespace slskd.Transfers.API
/// <response code="201">The download was successfully enqueued.</response>
/// <response code="403">The download was rejected.</response>
/// <response code="500">An unexpected error was encountered.</response>
+ [Obsolete("Will be phased out in future versions; use batches")]
[HttpPost("downloads/{username}")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(201)]
@@ -249,7 +251,12 @@ namespace slskd.Transfers.API
if (requests.Any(r => r is null))
{
- return BadRequest("One or more records in the request are null");
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (requests.Any(r => FileSafety.ContainsTraversalSegments(r.Filename)))
+ {
+ return BadRequest("One or more files in the request contain a dangerous path traversal segment");
}
if (!DownloadRequestLimiter.Wait(0))
@@ -282,6 +289,155 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Enqueues a batch of downloads.
+ /// </summary>
+ /// <param name="request">The batch details.</param>
+ /// <returns></returns>
+ /// <response code="201">All downloads were successfully enqueued.</response>
+ /// <response code="200">The request succeeded, but all downloads failed to be enqueued.</response>
+ /// <response code="207">Some downloads were successfully enqueued, while some failed.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="403">The request was forbidden.</response>
+ /// <response code="409">A batch with the same ID already exists.</response>
+ /// <response code="429">Request throttled.</response>
+ /// <response code="500">An unexpected error was encountered.</response>
+ [HttpPost("downloads/batches")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
+ public async Task<IActionResult> EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!ModelState.IsValid)
+ {
+ return BadRequest(ModelState.GetReadableString());
+ }
+
+ if (request.Files.Any(r => r is null))
+ {
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count)
+ {
+ return BadRequest("Two or more files in the request are repeated");
+ }
+
+ Guid? batchId;
+ Guid? searchId;
+
+ try
+ {
+ batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id);
+ searchId = string.IsNullOrWhiteSpace(request.SearchId) ? null : Guid.Parse(request.SearchId);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message);
+ return BadRequest("One or more provided identifiers is not a valid GUID/UUID");
+ }
+
+ batchId ??= Guid.NewGuid();
+
+ if (!DownloadRequestLimiter.Wait(0))
+ {
+ return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
+ }
+
+ try
+ {
+ var endpoint = await Users.GetIPEndPointAsync(request.Username);
+
+ if (Users.IsBlacklisted(request.Username, endpoint.Address))
+ {
+ throw new UserOfflineException($"User {request.Username} appears to be offline");
+ }
+
+ // throws DuplicateException if a record already exists
+ await Transfers.Downloads.Batches.CreateAsync(new()
+ {
+ Id = batchId.Value,
+ SearchId = searchId,
+ Username = request.Username,
+ Options = new()
+ {
+ Destination = request.Options.Destination,
+ },
+ });
+
+ // Transfer records will have been inserted before this returns, unless they were rejected
+ // because they were already in progress, in which case they will show up in 'failed'. or maybe they
+ // failed with an error. either way this complicates the return code
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(
+ username: request.Username,
+ files: request.Files.Select(r => (r.Filename, r.Size.Value)),
+ batchId: batchId);
+
+ if (failed.Count > 0)
+ {
+ Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed);
+ }
+
+ // the returned batch will have whatever Transfers were successfully inserted attached (via Include())
+ // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been
+ // properly finalized and marked as a failure
+ var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId);
+
+ var response = new QueueDownloadBatchResponse
+ {
+ Batch = batch,
+ Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(),
+ };
+
+ // basically a no-op, but we did create the batch record (and it's useless, but it's there)
+ // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me,
+ // but it doesn't allow a body and without it the caller will never know the id unless they supplied it
+ if (response.Failures.Count == request.Files.Count)
+ {
+ return StatusCode(StatusCodes.Status200OK, response);
+ }
+
+ // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code
+ // along with the batch and list of failures; the caller will have to pick through it and decide what to do
+ if (response.Failures.Count > 0)
+ {
+ return StatusCode(StatusCodes.Status207MultiStatus, response);
+ }
+
+ // everything passed and we are now (or will eventually be) downloading asynchronously
+ return StatusCode(StatusCodes.Status201Created, response);
+ }
+ catch (UserOfflineException ex)
+ {
+ return StatusCode(StatusCodes.Status404NotFound, ex.Message);
+ }
+ catch (DuplicateException ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id);
+ return Conflict($"A batch with ID {batchId} already exists");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message);
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ finally
+ {
+ DownloadRequestLimiter.Release();
+ }
+ }
+
+ /// <summary>
/// Gets all downloads.
/// </summary>
/// <returns></returns>
@@ -313,6 +469,47 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Gets the specified batch and associated transfers.
+ /// </summary>
+ /// <param name="id">The id of the batch.</param>
+ /// <returns></returns>
+ /// <response code="400">The specified id is not valid.</response>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified batch was not found.</response>
+ [HttpGet("downloads/batches/{id}")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(200)]
+ public async Task<IActionResult> Get([FromRoute, Required] string id)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!Guid.TryParse(id, out var guid))
+ {
+ return BadRequest($"The specified id {id} is not a valid GUID/UUID");
+ }
+
+ try
+ {
+ var found = await Transfers.Downloads.Batches.FindAsync(b => b.Id == guid);
+
+ if (found is null)
+ {
+ return NotFound();
+ }
+
+ return Ok(found);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to get batch with ID {Id}: {Message}", guid, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
/// Gets all downloads for the specified username.
/// </summary>
/// <param name="username"></param>
@@ -351,7 +548,7 @@ namespace slskd.Transfers.API
[HttpGet("downloads/{username}/{id}")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
@@ -386,7 +583,7 @@ namespace slskd.Transfers.API
/// <response code="404">The specified download was not found.</response>
[HttpGet("downloads/{username}/{id}/position")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
new file mode 100644
index 00000000..c1b7d725
--- /dev/null
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
@@ -0,0 +1,113 @@
+// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+
+namespace slskd.Transfers.API;
+
+/// <summary>
+/// Enqueue a batch of downloads.
+/// </summary>
+public record QueueDownloadBatchRequest
+{
+ /// <summary>
+ /// The ID of the Batch.
+ /// </summary>
+ /// <remarks>
+ /// If not supplied, one will be randomly generated.
+ /// </remarks>
+ [Guid]
+ public string Id { get; init; }
+
+ /// <summary>
+ /// The ID of the associated Search, if applicable.
+ /// </summary>
+ [Guid]
+ public string SearchId { get; init; }
+
+ /// <summary>
+ /// The username of the user from which to download.
+ /// </summary>
+ [Required]
+ [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)]
+ public string Username { get; init; }
+
+ /// <summary>
+ /// The list of files to download.
+ /// </summary>
+ [Required]
+ [MinLength(1)]
+ public IReadOnlyCollection<EnqueueDownloadBatchItem> Files { get; init; } = [];
+
+ /// <summary>
+ /// Options for the Batch.
+ /// </summary>
+ public EnqueueDownloadBatchOptions Options { get; init; } = new();
+}
+
+/// <summary>
+/// An item in a download batch.
+/// </summary>
+public record EnqueueDownloadBatchItem
+{
+ /// <summary>
+ /// The name of the file.
+ /// </summary>
+ [Required]
+ [NotNullOrWhiteSpace]
+ [NonTraversingPath]
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// The file size.
+ /// </summary>
+ [Required]
+ [Range(0, long.MaxValue)]
+ public long? Size { get; init; }
+}
+
+/// <summary>
+/// Download batch options.
+/// </summary>
+public record EnqueueDownloadBatchOptions
+{
+ /// <summary>
+ /// The destination directory for the files, relative to the configured download directory.
+ /// </summary>
+ [RelativePath]
+ [NonTraversingPath]
+ [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
+ public string Destination { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
index ce3331ca..84b570bc 100644
--- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
@@ -1,4 +1,4 @@
-// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
+// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -30,28 +30,18 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-using System;
using System.Collections.Generic;
-using System.ComponentModel.DataAnnotations;
namespace slskd.Transfers.API;
-public record EnqueueDownloadBatchRequest
+public record QueueDownloadBatchResponse
{
- public Guid? BatchId { get; init; }
- public Guid? SearchId { get; init; }
-
- [Required]
- [StringLength(500, MinimumLength = 1)]
- public string Username { get; init; }
- public List<EnqueueDownloadBatchItem> Files { get; init; } = [];
+ public Batch Batch { get; init; }
+ public IReadOnlyCollection<QueueDownloadBatchResponseFailure> Failures { get; init; } = [];
}
-public record EnqueueDownloadBatchItem
+public record QueueDownloadBatchResponseFailure
{
- [Required]
- public string Filename { get; set; }
-
- [Range(0, int.MaxValue)]
- public long Size { get; set; }
-} \ No newline at end of file
+ public string Filename { get; init; }
+ public string Message { get; init; }
+}
diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs
deleted file mode 100644
index 949f15d4..00000000
--- a/src/slskd/Transfers/API/DTO/Transfer.cs
+++ /dev/null
@@ -1,169 +0,0 @@
-// <copyright file="Transfer.cs" company="JP Dillingham">
-// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
-// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
-// █__ --█ █__ --█ ◄█ - █
-// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
-// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
-// │ Copyright (c) JP Dillingham.
-// │
-// │ This program is free software: you can redistribute it and/or modify
-// │ it under the terms of the GNU Affero General Public License as published
-// │ by the Free Software Foundation, version 3.
-// │
-// │ This program is distributed in the hope that it will be useful,
-// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
-// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// │ GNU Affero General Public License for more details.
-// │
-// │ You should have received a copy of the GNU Affero General Public License
-// │ along with this program. If not, see https://www.gnu.org/licenses/.
-// │
-// │ This program is distributed with Additional Terms pursuant to Section 7
-// │ of the AGPLv3. See the LICENSE file in the root directory of this
-// │ project for the complete terms and conditions.
-// │
-// │ https://slskd.org
-// │
-// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
-// │ SPDX-FileCopyrightText: JP Dillingham
-// │ SPDX-License-Identifier: AGPL-3.0-only
-// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
-// </copyright>
-
-namespace slskd.Transfers.API
-{
- using System;
- using System.Net;
- using Soulseek;
-
- /// <summary>
- /// A single file transfer.
- /// </summary>
- public class Transfer
- {
- /// <summary>
- /// Gets the current average transfer speed.
- /// </summary>
- public double AverageSpeed { get; set; }
-
- /// <summary>
- /// Gets the number of remaining bytes to be transferred.
- /// </summary>
- public long BytesRemaining { get; set; }
-
- /// <summary>
- /// Gets the total number of bytes transferred.
- /// </summary>
- public long BytesTransferred { get; set; }
-
- /// <summary>
- /// Gets the transfer direction.
- /// </summary>
- public TransferDirection Direction { get; set; }
-
- /// <summary>
- /// Gets the current duration of the transfer, if it has been started.
- /// </summary>
- public double? ElapsedTime { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state.
- /// </summary>
- public DateTime? EndTime { get; set; }
-
- /// <summary>
- /// Gets the filename of the file to be transferred.
- /// </summary>
- public string Filename { get; set; }
-
- /// <summary>
- /// Gets the transfer id.
- /// </summary>
- public string Id => Compute.Sha1Hash(Filename);
-
- /// <summary>
- /// Gets the ip endpoint of the remote transfer connection, if one has been established.
- /// </summary>
- public IPEndPoint IPEndPoint { get; set; }
-
- /// <summary>
- /// Gets the current progress in percent.
- /// </summary>
- public double PercentComplete { get; set; }
-
- /// <summary>
- /// Gets the current place in queue, if it has been fetched.
- /// </summary>
- public int? PlaceInQueue { get; set; }
-
- /// <summary>
- /// Gets the projected remaining duration of the transfer.
- /// </summary>
- public double? RemainingTime { get; set; }
-
- /// <summary>
- /// Gets the remote unique token for the transfer.
- /// </summary>
- public int? RemoteToken { get; set; }
-
- /// <summary>
- /// Gets the size of the file to be transferred, in bytes.
- /// </summary>
- public long Size { get; set; }
-
- /// <summary>
- /// Gets the starting offset of the transfer, in bytes.
- /// </summary>
- public long StartOffset { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state.
- /// </summary>
- public DateTime? StartTime { get; set; }
-
- /// <summary>
- /// Gets the state of the transfer.
- /// </summary>
- public TransferStates State { get; set; }
-
- /// <summary>
- /// Gets the unique token for the transfer.
- /// </summary>
- public int Token { get; set; }
-
- /// <summary>
- /// Gets the username of the peer to or from which the file is to be transferred.
- /// </summary>
- public string Username { get; set; }
-
- /// <summary>
- /// Gets the Exception that caused the failure of the transfer, if applicable.
- /// </summary>
- public string Exception { get; set; }
-
- public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer)
- {
- return new Transfer()
- {
- AverageSpeed = transfer.AverageSpeed,
- BytesRemaining = transfer.BytesRemaining,
- BytesTransferred = transfer.BytesTransferred,
- Direction = transfer.Direction,
- ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds,
- EndTime = transfer.EndTime,
- Filename = transfer.Filename,
- IPEndPoint = transfer.IPEndPoint,
- PercentComplete = transfer.PercentComplete,
- RemainingTime = transfer.RemainingTime?.TotalMilliseconds,
- RemoteToken = transfer.RemoteToken,
- Size = transfer.Size,
- StartOffset = transfer.StartOffset,
- StartTime = transfer.StartTime,
- State = transfer.State,
- Token = transfer.Token,
- Username = transfer.Username,
- Exception = transfer.Exception?.Message,
- };
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs
new file mode 100644
index 00000000..7ea9a70a
--- /dev/null
+++ b/src/slskd/Transfers/Downloads/BatchService.cs
@@ -0,0 +1,140 @@
+// <copyright file="BatchService.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers.Downloads;
+
+using System;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Threading.Tasks;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using Serilog;
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public interface IBatchService
+{
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ Task<Batch> CreateAsync(Batch batch);
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression);
+}
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public class BatchService : IBatchService
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BatchService"/> class.
+ /// </summary>
+ /// <param name="contextFactory">The database context factory to use.</param>
+ public BatchService(IDbContextFactory<TransfersDbContext> contextFactory)
+ {
+ ContextFactory = contextFactory;
+ }
+
+ private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<BatchService>();
+
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ public async Task<Batch> CreateAsync(Batch batch)
+ {
+ if (batch == default)
+ {
+ throw new ArgumentNullException(nameof(batch));
+ }
+
+ if (batch.Id == Guid.Empty)
+ {
+ throw new ArgumentOutOfRangeException(nameof(batch.Id), message: $"Batch ID may not be an empty uuid ({Guid.Empty})");
+ }
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Batches.Add(batch);
+
+ await context.SaveChangesAsync();
+
+ return batch;
+ }
+ catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19 })
+ {
+ throw new DuplicateException($"A Batch with ID {batch.Id} already exists.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Failed to create Batch: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ public async Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression)
+ {
+ if (expression == default)
+ {
+ throw new ArgumentException("An expression must be supplied.", nameof(expression));
+ }
+
+ using var context = ContextFactory.CreateDbContext();
+
+ return await context.Batches
+ .AsNoTracking()
+ .Include(b => b.Transfers)
+ .Where(expression)
+ .SingleOrDefaultAsync();
+ }
+}
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index d4d8004a..83e91ced 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -56,6 +56,11 @@ namespace slskd.Transfers.Downloads
public interface IDownloadService
{
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ IBatchService Batches { get; }
+
+ /// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
/// </summary>
/// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
@@ -71,12 +76,13 @@ namespace slskd.Transfers.Downloads
/// </remarks>
/// <param name="username">The username of remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
+ Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single download matching the specified <paramref name="expression"/>.
@@ -158,6 +164,7 @@ namespace slskd.Transfers.Downloads
public class DownloadService : IDownloadService
{
public DownloadService(
+ IBatchService batchService,
IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient soulseekClient,
IDbContextFactory<TransfersDbContext> contextFactory,
@@ -166,6 +173,7 @@ namespace slskd.Transfers.Downloads
IFTPService ftpClient,
EventBus eventBus)
{
+ Batches = batchService;
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
ContextFactory = contextFactory;
@@ -178,6 +186,11 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ public IBatchService Batches { get; }
+
+ /// <summary>
/// These tokens give users the ability to cancel transfers via the UI (or API).
///
/// The lifecycle is:
@@ -249,12 +262,13 @@ namespace slskd.Transfers.Downloads
/// </summary>
/// <param name="username">The username of the remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- public async Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
+ public async Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
@@ -273,6 +287,11 @@ namespace slskd.Transfers.Downloads
throw new ArgumentException("At least one filename is null or empty", nameof(files));
}
+ if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename)))
+ {
+ throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files));
+ }
+
if (fileList.Count != fileList.Distinct().Count())
{
throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
@@ -306,7 +325,7 @@ namespace slskd.Transfers.Downloads
}
List<Transfer> enqueued = [];
- List<string> failed = [];
+ List<(string Filename, string Message)> failed = [];
SemaphoreSlim userSemaphore;
Task userSemaphoreWaitTask;
@@ -404,7 +423,7 @@ namespace slskd.Transfers.Downloads
if (existingInProgressRecord is not null)
{
Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -416,7 +435,7 @@ namespace slskd.Transfers.Downloads
if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false)
{
Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -431,11 +450,11 @@ namespace slskd.Transfers.Downloads
var transfer = new Transfer()
{
Id = transferId,
+ BatchId = batchId,
Username = username,
Direction = TransferDirection.Download,
Filename = file.Filename, // important! use the remote filename
Size = file.Size,
- StartOffset = 0, // todo: maybe implement resumeable downloads?
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
@@ -607,7 +626,7 @@ namespace slskd.Transfers.Downloads
{
Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
TryFail(transferId, exception: ex);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, $"Error: {ex.Message}"));
if (CancellationTokens.TryRemove(transferId, out var cts))
{
@@ -973,9 +992,11 @@ namespace slskd.Transfers.Downloads
// the final update after all retry attempts have been exhausted to add it.
// this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all
// retries is to look for this flag
- if (transfer.Attempts < retryOptions.Attempts)
+ if (args.Transfer.State.HasFlag(TransferStates.Completed)
+ && !args.Transfer.State.HasFlag(TransferStates.Succeeded)
+ && transfer.Attempts < retryOptions.Attempts)
{
- transfer.State &= ~TransferStates.Completed; // remove the Completed flag
+ transfer.State = TransferStates.Queued | TransferStates.Locally;
}
// todo: broadcast
@@ -1028,12 +1049,10 @@ namespace slskd.Transfers.Downloads
? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
: null;
- // if the transfer has an associated batch id, store the incomplete file in a directory of the same name
- // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file)
+ // store incomplete files under a username subdirectory to prevent collisions between users
+ // and to make it safe to resume partial downloads without risking picking up an unrelated file
var incompleteFilename = transfer.Filename.ToLocalFilename(
- baseDirectory: System.IO.Path.Combine(
- OptionsMonitor.CurrentValue.Directories.Incomplete,
- transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty));
+ baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters()));
Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
transfer.Attempts = 1;
@@ -1128,7 +1147,7 @@ namespace slskd.Transfers.Downloads
{
// if the transfer has an associated batch id, then:
// some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext
- destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString());
+ destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString());
}
else
{
@@ -1141,7 +1160,7 @@ namespace slskd.Transfers.Downloads
Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);
var finalFilename = Files.MoveFile(
- sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete),
+ sourceFilename: incompleteFilename,
destinationDirectory: destinationDirectory,
unixFileMode: unixFileMode,
overwrite: false,
diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs
index 48179ff2..3180dbd9 100644
--- a/src/slskd/Transfers/Extensions.cs
+++ b/src/slskd/Transfers/Extensions.cs
@@ -44,7 +44,6 @@ namespace slskd.Transfers
Direction = transfer.Direction,
Filename = transfer.Filename,
Size = transfer.Size,
- StartOffset = t.StartOffset,
State = t.State,
RequestedAt = transfer.RequestedAt,
EnqueuedAt = transfer.EnqueuedAt,
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index be312e8e..b25e7663 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -33,6 +33,7 @@
namespace slskd.Transfers
{
using System;
+ using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@@ -43,16 +44,23 @@ namespace slskd.Transfers
{
}
+ public DbSet<Batch> Batches { get; set; }
public DbSet<Transfer> Transfers { get; set; }
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// this is absolutely NOT IDEAL and will accellerate the move away from EF
+ // we have to do this to store both the integer and the string value in the database
+ // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history
+ // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries,
+ // which is the main driver for this.
foreach (var entry in ChangeTracker.Entries<Transfer>())
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
+#pragma warning disable CS0618 // Type or member is obsolete
entry.Entity.StateDescription = entry.Entity.State.ToString();
+#pragma warning restore CS0618 // Type or member is obsolete
}
}
@@ -61,6 +69,12 @@ namespace slskd.Transfers
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
+ ConfigureTransfers(modelBuilder);
+ ConfigureBatches(modelBuilder);
+ }
+
+ private void ConfigureTransfers(ModelBuilder modelBuilder)
+ {
modelBuilder
.Entity<Transfer>()
.Property(e => e.StartedAt)
@@ -114,5 +128,34 @@ namespace slskd.Transfers
.HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size })
.HasDatabaseName("IDX_Transfers_UserUploadStatistics");
}
+
+ private void ConfigureBatches(ModelBuilder modelBuilder)
+ {
+ modelBuilder
+ .Entity<Batch>()
+ .Property(e => e.CreatedAt)
+ .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasMany(b => b.Transfers)
+ .WithOne()
+ .HasForeignKey(t => t.BatchId)
+ .IsRequired(false)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ modelBuilder
+ .Entity<Batch>()
+ .Property(b => b.Options)
+ .HasConversion(
+ convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()),
+ convertFromProviderExpression: v => JsonSerializer.Deserialize<BatchOptions>(v, new JsonSerializerOptions().WithStandardOptions()))
+ .HasColumnType("TEXT");
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasIndex(b => b.SearchId)
+ .HasDatabaseName("IDX_Batches_SearchId");
+ }
}
}
diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs
new file mode 100644
index 00000000..a0d71bef
--- /dev/null
+++ b/src/slskd/Transfers/Types/Batch.cs
@@ -0,0 +1,118 @@
+// <copyright file="Batch.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Soulseek;
+
+/// <summary>
+/// <para>
+/// A Transfer Batch is a lightweight association between a number of related Transfer
+/// records and optionally the associated Search the Transfers are intended to fulfil.
+/// </para>
+/// <para>
+/// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the
+/// available API(s) to determine whether all of the Transfers within the Batch are complete,
+/// but otherwise a Batch serves no functional purpose within the application.
+/// </para>
+/// </summary>
+public record Batch
+{
+ /// <summary>
+ /// Gets the associated <see cref="slskd.Search.Search.Id"/>, if one was specified when the
+ /// Batch was enqueued.
+ /// </summary>
+ public Guid? SearchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Batch.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the username associated with the Batch.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Batch direction (Upload, Download).
+ /// </summary>
+ /// <remarks>
+ /// We don't have, and likely will never be able to implement, upload batches,
+ /// nor are they of any particular use.
+ /// </remarks>
+ public TransferDirection Direction { get; init; } = TransferDirection.Download;
+
+ /// <summary>
+ /// Gets the time at which the Batch was created.
+ /// </summary>
+ public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
+
+ /// <summary>
+ /// Gets the Transfer records associated with the batch.
+ /// </summary>
+ public ICollection<Transfer> Transfers { get; init; } = null;
+
+ /// <summary>
+ /// Gets the options for the batch.
+ /// </summary>
+ public BatchOptions Options { get; init; }
+
+ /*
+ future: [NotMapped] properties that aggregate values from the associated Transfer records.
+ there's no use for these now, but if we ever decide to leverage Batch records for anything
+ but determining whether a Search has been fulfilled, allowing a user to override a download directory,
+ or to handle an event when a batch is completed, we can add them and figure out how persistence should work.
+
+ file count and size are also not included because of the transfer deduplication that takes place during
+ the enqueue; if a batch is created and some or all of the files within are already in progress, they are
+ dropped and no new transfer records are created. this would create data inconsistency, and for no reason (for now)
+
+ loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer
+ records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works,
+ but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches
+ from results (as this must be aggregated on the fly for each batch.. forever)
+
+ my thinking (and reason for punting on this for now); add the interesting properties (Removed, BytesTransferred,
+ AverageSpeed, etc) to this class as nullable, and don't set a value until all of the associated Transfer
+ records have been finalized, then update the columns. when fetching batches we can deduce that any Batch
+ record missing those properties is still in progress, and we can aggregate the data on the fly. for historical
+ records that have completed, the data is all in the database and is quick to query.
+
+ this can sit until/if we have further use for Batch records, i want to get this out and don't want to sit
+ and go back and forth trying to speculate on how this might need to work in the future.
+ */
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs
new file mode 100644
index 00000000..6bacef8c
--- /dev/null
+++ b/src/slskd/Transfers/Types/BatchOptions.cs
@@ -0,0 +1,48 @@
+// <copyright file="BatchOptions.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Options for <see cref="Batch"/>es.
+/// </summary>
+public record BatchOptions
+{
+ /// <summary>
+ /// Gets the optional destination directory for the files in the Batch, relative to the configured
+ /// download directory.
+ /// </summary>
+ /// <remarks>
+ /// If specified, takes precedence over other configured placement rules.
+ /// </remarks>
+ public string Destination { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs
index 93a23380..d33a5efc 100644
--- a/src/slskd/Transfers/Types/Transfer.cs
+++ b/src/slskd/Transfers/Types/Transfer.cs
@@ -30,72 +30,146 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-namespace slskd.Transfers
+namespace slskd.Transfers;
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Text.Json.Serialization;
+using Soulseek;
+
+/// <summary>
+/// A file Transfer between network peers.
+/// </summary>
+public class Transfer
{
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text.Json.Serialization;
- using Soulseek;
-
- public class Transfer
- {
- public Guid? BatchId { get; init; } = null;
-
- [Key]
- public Guid Id { get; init; }
- public string Username { get; init; }
- public TransferDirection Direction { get; init; }
-
- /// <summary>
- /// Gets the remote filename.
- /// </summary>
- public string Filename { get; init; }
- public long Size { get; set; }
- public long StartOffset { get; init; }
-
- public TransferStates State { get; set; } = TransferStates.None;
-
- /// <summary>
- /// Gets the string representation of the transfer <see cref="State"/>.
- /// </summary>
- /// <remarks>
- /// This is a hack to get the string into the database. *DO NOT* use this property in code
- /// and especially **DO NOT** set the value. The getter and setter can't be protected because
- /// EF Core needs them to be public.
- /// </remarks>
- public string StateDescription { get; set; }
- public DateTime RequestedAt { get; set; }
- public DateTime? EnqueuedAt { get; set; }
- public DateTime? StartedAt { get; set; }
-
- /// <summary>
- /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress.
- /// </summary>
- /// <remarks>
- /// Guaranteed to be set for transfers in a terminal state.
- /// </remarks>
- public DateTime? EndedAt { get; set; }
- public long BytesTransferred { get; set; }
- public double AverageSpeed { get; set; }
-
- public int? PlaceInQueue { get; set; }
- public string Exception { get; set; }
-
- public int Attempts { get; set; } = 0;
-
- public DateTime? NextAttemptAt { get; set; } = null;
-
- [JsonIgnore]
- public bool Removed { get; set; }
-
- [NotMapped]
- public long BytesRemaining => Size - BytesTransferred;
- [NotMapped]
- public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
- [NotMapped]
- public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
- [NotMapped]
- public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
- }
+ /// <summary>
+ /// Gets the associated <see cref="Batch.Id"/>, if one was specified when the Transfer was created.
+ /// </summary>
+ public Guid? BatchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Transfer.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the remote username associated with the Transfer.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Transfer direction (Upload, Download).
+ /// </summary>
+ public TransferDirection Direction { get; init; }
+
+ /// <summary>
+ /// Gets the remote filename of the file.
+ /// </summary>
+ /// <remarks>
+ /// Exactly as it appeared in the originating Search, Browse, or file directory contents response.
+ /// </remarks>
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// Gets or sets the remote size of the file.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state of the Transfer.
+ /// </summary>
+ public TransferStates State { get; set; } = TransferStates.None;
+
+ /// <summary>
+ /// Gets or sets the string representation of the transfer <see cref="State"/>.
+ /// </summary>
+ /// <remarks>
+ /// This is a hack to get the string into the database. *DO NOT* use this property in code
+ /// and especially **DO NOT** set the value. The getter and setter can't be protected because
+ /// EF Core needs them to be public.
+ /// </remarks>
+ [Obsolete("Use State isntead; this is a hack for EF")]
+ [JsonIgnore]
+ public string StateDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was requested from the remote peer.
+ /// </summary>
+ public DateTime RequestedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued.
+ /// </summary>
+ /// <remarks>
+ /// For downloads, this is the time at which the remote peer responded to our enqueue request. For uploads this
+ /// is the time at which the transfer was made available for scheduling by the upload queue, after we have
+ /// responded to the remote peer's request to enqueue.
+ /// </remarks>
+ public DateTime? EnqueuedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer connection was established and data transfer began, or null if the
+ /// Transfer has not yet been started.
+ /// </summary>
+ public DateTime? StartedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress.
+ /// </summary>
+ /// <remarks>
+ /// Guaranteed to be set for transfers in a terminal state.
+ /// </remarks>
+ public DateTime? EndedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of bytes transferred.
+ /// </summary>
+ public long BytesTransferred { get; set; }
+
+ /// <summary>
+ /// Gets or sets the average speed of the Transfer over the duration.
+ /// </summary>
+ public double AverageSpeed { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current place in line in the remote peer's queue, if place has been requested.
+ /// </summary>
+ /// <remarks>
+ /// May be wildly innacurate to the point of uselessness.
+ /// </remarks>
+ public int? PlaceInQueue { get; set; }
+
+ /// <summary>
+ /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did.
+ /// </summary>
+ public string Exception { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of attempts. Incremented each time the Transfer is retried.
+ /// </summary>
+ /// <remarks>
+ /// Applicable to downloads only.
+ /// </remarks>
+ public int Attempts { get; set; } = 0;
+
+ /// <summary>
+ /// Gets or sets the time at which the next retry attempt will be made, if applicable.
+ /// </summary>
+ public DateTime? NextAttemptAt { get; set; } = null;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the Transfer has been removed from the UI.
+ /// </summary>
+ public bool Removed { get; set; }
+
+ [NotMapped]
+ public long BytesRemaining => Size - BytesTransferred;
+ [NotMapped]
+ public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
+ [NotMapped]
+ public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
+ [NotMapped]
+ public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
index 603c669a..333ae525 100644
--- a/src/slskd/Transfers/Types/TransferStateCategories.cs
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -111,6 +111,7 @@ public static class TransferStateCategories
/// </list>
/// </summary>
public static readonly HashSet<TransferStates> Queued = [
+ TransferStates.Requested, // optimistically assume that we will be allowed to enqueue
TransferStates.Queued, // 2, in case of some sort of a malfunction or regression
TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050
TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 72e3c0ef..9bb09f66 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -101,16 +101,6 @@ namespace slskd.Transfers.Uploads
Transfer Find(Expression<Func<Transfer, bool>> expression);
/// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
-
- /// <summary>
/// Gets upload statistics for the specified <paramref name="username"/>.
/// </summary>
/// <param name="username">The username of the user.</param>
@@ -632,7 +622,6 @@ namespace slskd.Transfers.Uploads
Direction = TransferDirection.Upload,
Filename = filename, // important! use the remote filename
Size = localFileLength,
- StartOffset = 0, // potentially updated later during handshaking
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
@@ -731,51 +720,12 @@ namespace slskd.Transfers.Uploads
return context.Transfers
.AsNoTracking()
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(expression).FirstOrDefault();
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
- throw;
- }
- }
-
- /// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- public (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression)
- {
- expression ??= t => true;
-
- try
- {
- using var context = ContextFactory.CreateDbContext();
-
- var query = context.Transfers
- .AsNoTracking()
- .Where(t => t.Direction == TransferDirection.Upload)
.Where(expression)
- .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group.
- .Select(t => new
- {
- Files = t.Count(),
- Bytes = t.Sum(x => x.Size),
- });
-
- Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString());
-
- var stats = query.FirstOrDefault();
-
- return (stats?.Files ?? 0, stats?.Bytes ?? 0);
+ .SingleOrDefault();
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to list uploads: {Message}", ex.Message);
+ Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
throw;
}
}
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 74a35dc1..22d9c714 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -13,7 +13,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^1.15.2",
+ "axios": "^1.15.0",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
@@ -83,20 +83,89 @@
}
},
"node_modules/@babel/code-frame": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
- "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
+ "version": "7.23.5",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz",
+ "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/helper-validator-identifier": "^7.28.5",
- "js-tokens": "^4.0.0",
- "picocolors": "^1.1.1"
+ "@babel/highlight": "^7.23.4",
+ "chalk": "^2.4.2"
},
"engines": {
"node": ">=6.9.0"
}
},
+ "node_modules/@babel/code-frame/node_modules/ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "dev": true,
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/code-frame/node_modules/chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
+ "dev": true,
+ "dependencies": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/code-frame/node_modules/color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "dev": true,
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/@babel/code-frame/node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "dev": true
+ },
+ "node_modules/@babel/code-frame/node_modules/escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/@babel/code-frame/node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/code-frame/node_modules/supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/@babel/compat-data": {
"version": "7.23.5",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz",
@@ -204,17 +273,15 @@
}
},
"node_modules/@babel/generator": {
- "version": "7.29.1",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
- "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",
+ "version": "7.23.6",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz",
+ "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/parser": "^7.29.0",
- "@babel/types": "^7.29.0",
- "@jridgewell/gen-mapping": "^0.3.12",
- "@jridgewell/trace-mapping": "^0.3.28",
- "jsesc": "^3.0.2"
+ "@babel/types": "^7.23.6",
+ "@jridgewell/gen-mapping": "^0.3.2",
+ "@jridgewell/trace-mapping": "^0.3.17",
+ "jsesc": "^2.5.1"
},
"engines": {
"node": ">=6.9.0"
@@ -375,12 +442,14 @@
"node": ">=6.9.0"
}
},
- "node_modules/@babel/helper-globals": {
- "version": "7.28.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
- "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
+ "node_modules/@babel/helper-hoist-variables": {
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz",
+ "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==",
"dev": true,
- "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.22.5"
+ },
"engines": {
"node": ">=6.9.0"
}
@@ -398,29 +467,28 @@
}
},
"node_modules/@babel/helper-module-imports": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",
- "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",
+ "version": "7.22.15",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz",
+ "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/traverse": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/types": "^7.22.15"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-transforms": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",
- "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",
+ "version": "7.23.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz",
+ "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/helper-module-imports": "^7.28.6",
- "@babel/helper-validator-identifier": "^7.28.5",
- "@babel/traverse": "^7.28.6"
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-module-imports": "^7.22.15",
+ "@babel/helper-simple-access": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/helper-validator-identifier": "^7.22.20"
},
"engines": {
"node": ">=6.9.0"
@@ -442,11 +510,10 @@
}
},
"node_modules/@babel/helper-plugin-utils": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz",
- "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==",
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz",
+ "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==",
"dev": true,
- "license": "MIT",
"engines": {
"node": ">=6.9.0"
}
@@ -523,21 +590,19 @@
}
},
"node_modules/@babel/helper-string-parser": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
- "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz",
+ "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==",
"dev": true,
- "license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
- "version": "7.28.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
- "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "version": "7.22.20",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
+ "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
"dev": true,
- "license": "MIT",
"engines": {
"node": ">=6.9.0"
}
@@ -580,15 +645,96 @@
"node": ">=6.9.0"
}
},
- "node_modules/@babel/parser": {
- "version": "7.29.3",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz",
- "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==",
+ "node_modules/@babel/highlight": {
+ "version": "7.23.4",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz",
+ "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==",
+ "dev": true,
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "chalk": "^2.4.2",
+ "js-tokens": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "dev": true,
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.0"
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
},
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "dev": true,
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "dev": true
+ },
+ "node_modules/@babel/highlight/node_modules/escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/highlight/node_modules/supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "dev": true,
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.23.9",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.9.tgz",
+ "integrity": "sha512-9tcKgqKbs3xGJ+NtKF2ndOBBLVwPjl1SHxPQkd36r3Dlirw3xWUeGaTbqr7uGZcTaxkVNwc+03SVP7aCdWrTlA==",
+ "dev": true,
"bin": {
"parser": "bin/babel-parser.js"
},
@@ -1468,16 +1614,15 @@
}
},
"node_modules/@babel/plugin-transform-modules-systemjs": {
- "version": "7.29.4",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.4.tgz",
- "integrity": "sha512-N7QmZ0xRZfjHOfZeQLJjwgX2zS9pdGHSVl/cjSGlo4dXMqvurfxXDMKY4RqEKzPozV78VMcd0lxyG13mlbKc4w==",
+ "version": "7.22.5",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.22.5.tgz",
+ "integrity": "sha512-emtEpoaTMsOs6Tzz+nbmcePl6AKVtS1yC4YNAeMun9U8YCsgadPNxnOPQ8GhHFB2qdx+LZu9LgoC0Lthuu05DQ==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/helper-module-transforms": "^7.28.6",
- "@babel/helper-plugin-utils": "^7.28.6",
- "@babel/helper-validator-identifier": "^7.28.5",
- "@babel/traverse": "^7.29.0"
+ "@babel/helper-hoist-variables": "^7.22.5",
+ "@babel/helper-module-transforms": "^7.22.5",
+ "@babel/helper-plugin-utils": "^7.22.5",
+ "@babel/helper-validator-identifier": "^7.22.5"
},
"engines": {
"node": ">=6.9.0"
@@ -2208,48 +2353,58 @@
"license": "MIT"
},
"node_modules/@babel/template": {
- "version": "7.28.6",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
- "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
+ "version": "7.23.9",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.23.9.tgz",
+ "integrity": "sha512-+xrD2BWLpvHKNmX2QbpdpsBaWnRxahMwJjO+KZk2JOElj5nSmKezyS1B4u+QbHMTX69t4ukm6hh9lsYQ7GHCKA==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.28.6",
- "@babel/parser": "^7.28.6",
- "@babel/types": "^7.28.6"
+ "@babel/code-frame": "^7.23.5",
+ "@babel/parser": "^7.23.9",
+ "@babel/types": "^7.23.9"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",
- "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",
+ "version": "7.23.9",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.9.tgz",
+ "integrity": "sha512-I/4UJ9vs90OkBtY6iiiTORVMyIhJ4kAVmsKo9KFc8UOxMeUfi2hvtIBsET5u9GizXE6/GFSuKCTNfgCswuEjRg==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.0",
- "@babel/generator": "^7.29.0",
- "@babel/helper-globals": "^7.28.0",
- "@babel/parser": "^7.29.0",
- "@babel/template": "^7.28.6",
- "@babel/types": "^7.29.0",
- "debug": "^4.3.1"
+ "@babel/code-frame": "^7.23.5",
+ "@babel/generator": "^7.23.6",
+ "@babel/helper-environment-visitor": "^7.22.20",
+ "@babel/helper-function-name": "^7.23.0",
+ "@babel/helper-hoist-variables": "^7.22.5",
+ "@babel/helper-split-export-declaration": "^7.22.6",
+ "@babel/parser": "^7.23.9",
+ "@babel/types": "^7.23.9",
+ "debug": "^4.3.1",
+ "globals": "^11.1.0"
},
"engines": {
"node": ">=6.9.0"
}
},
+ "node_modules/@babel/traverse/node_modules/globals": {
+ "version": "11.12.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz",
+ "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/@babel/types": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
- "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "version": "7.23.9",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.9.tgz",
+ "integrity": "sha512-dQjSq/7HaSjRM43FFGnv5keM2HsxpmyV1PfaSVm0nzzjwwTmjOe6J4bC8e3+pTEIgHaHj+1ZlLThRJ2auc/w1Q==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@babel/helper-string-parser": "^7.27.1",
- "@babel/helper-validator-identifier": "^7.28.5"
+ "@babel/helper-string-parser": "^7.23.4",
+ "@babel/helper-validator-identifier": "^7.22.20",
+ "to-fast-properties": "^2.0.0"
},
"engines": {
"node": ">=6.9.0"
@@ -3672,14 +3827,17 @@
}
},
"node_modules/@jridgewell/gen-mapping": {
- "version": "0.3.13",
- "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
- "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
+ "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
"dev": true,
- "license": "MIT",
"dependencies": {
- "@jridgewell/sourcemap-codec": "^1.5.0",
- "@jridgewell/trace-mapping": "^0.3.24"
+ "@jridgewell/set-array": "^1.0.1",
+ "@jridgewell/sourcemap-codec": "^1.4.10",
+ "@jridgewell/trace-mapping": "^0.3.9"
+ },
+ "engines": {
+ "node": ">=6.0.0"
}
},
"node_modules/@jridgewell/resolve-uri": {
@@ -3691,6 +3849,15 @@
"node": ">=6.0.0"
}
},
+ "node_modules/@jridgewell/set-array": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
+ "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
+ "dev": true,
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/@jridgewell/source-map": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz",
@@ -3702,18 +3869,16 @@
}
},
"node_modules/@jridgewell/sourcemap-codec": {
- "version": "1.5.5",
- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
- "dev": true,
- "license": "MIT"
+ "version": "1.4.15",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
+ "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
+ "dev": true
},
"node_modules/@jridgewell/trace-mapping": {
- "version": "0.3.31",
- "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
- "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "version": "0.3.25",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz",
+ "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==",
"dev": true,
- "license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
@@ -5819,9 +5984,9 @@
}
},
"node_modules/axios": {
- "version": "1.15.2",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.2.tgz",
- "integrity": "sha512-wLrXxPtcrPTsNlJmKjkPnNPK2Ihe0hn0wGSaTEiHRPxwjvJwT3hKmXF4dpqxmPO9SoNb2FsYXj/xEo0gHN+D5A==",
+ "version": "1.15.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz",
+ "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.11",
@@ -9716,6 +9881,18 @@
"eslint": ">=8.44.0"
}
},
+ "node_modules/eslint-plugin-unicorn/node_modules/jsesc": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz",
+ "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==",
+ "dev": true,
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/eslint-plugin-unicorn/node_modules/regjsparser": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.10.0.tgz",
@@ -10464,9 +10641,9 @@
}
},
"node_modules/fast-uri": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
- "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",
+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
"dev": true,
"funding": [
{
@@ -13980,16 +14157,15 @@
}
},
"node_modules/jsesc": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
- "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz",
+ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==",
"dev": true,
- "license": "MIT",
"bin": {
"jsesc": "bin/jsesc"
},
"engines": {
- "node": ">=6"
+ "node": ">=4"
}
},
"node_modules/json-parse-even-better-errors": {
@@ -19766,6 +19942,15 @@
"integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==",
"dev": true
},
+ "node_modules/to-fast-properties": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",
+ "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
+ "dev": true,
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
diff --git a/src/web/package.json b/src/web/package.json
index 57bb8d70..00491c52 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -18,7 +18,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^1.15.2",
+ "axios": "^1.15.0",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
index f6264661..eff24587 100644
--- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
+++ b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs
@@ -141,4 +141,4 @@ namespace slskd.Tests.Unit.Common.Extensions
Assert.EndsWith("after", result);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
index ae1efccf..a37e9e74 100644
--- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
+++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
@@ -542,4 +542,4 @@ public class FileSafetyTests
Assert.NotNull(result);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
index 5013ec3a..bc8601c5 100644
--- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
+++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
@@ -171,39 +171,6 @@ public class AbsolutePathAttributeTests
}
}
- // Paths containing . or .. segments, which are valid directory names in isolation
- // but indicate traversal or ambiguity and must be rejected regardless of whether
- // the path is otherwise absolute or relative.
- public class Traversal_Fails
- {
- [Theory]
- // Windows-style traversal
- [InlineData("C:\\Music\\..\\Windows")] // traversal to sibling via backslash
- [InlineData("C:\\Music\\.\\Artist")] // current-dir segment via backslash
- [InlineData("C:/Music/../Windows")] // traversal via forward slash
- [InlineData("C:/Music/./Artist")] // current-dir via forward slash
- [InlineData("C:\\..")] // traversal at drive root
- [InlineData("D:\\a\\b\\..\\c")] // traversal deep in path
- // Unix-style traversal
- [InlineData("/../etc")] // traversal at Unix root
- [InlineData("/home/user/../etc")] // traversal to sibling on Unix
- [InlineData("/home/user/./Music")] // current-dir on Unix
- [InlineData("/home/../../etc")] // double traversal on Unix
- // UNC traversal (backslash)
- [InlineData("\\\\server\\..\\Windows")] // traversal past UNC server
- [InlineData("\\\\server\\share\\..\\other")] // traversal within UNC share
- [InlineData("\\\\server\\share\\.\\folder")] // current-dir within UNC share
- // UNC traversal (forward slash)
- [InlineData("//server/../share")] // traversal past server, forward slash
- [InlineData("//server/share/../other")] // traversal within share, forward slash
- public void TraversalSegment_Fails(string value)
- {
- var (isValid, errorMessage) = Validate(value);
- Assert.False(isValid);
- Assert.Contains("traversal segments", errorMessage);
- }
- }
-
public class Relative_Fails
{
[Theory]
@@ -226,4 +193,4 @@ public class AbsolutePathAttributeTests
Assert.Equal("The Field field must be an absolute file path.", errorMessage);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs
deleted file mode 100644
index f430c181..00000000
--- a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs
+++ /dev/null
@@ -1,254 +0,0 @@
-using System.ComponentModel.DataAnnotations;
-using slskd.Validation;
-using Xunit;
-
-namespace slskd.Tests.Unit.Common.Validation;
-
-public class DisallowedCharactersAttributeTests
-{
- private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
- {
- var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase };
- var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
- var result = attribute.GetValidationResult(value, context);
- return (result == null, result?.ErrorMessage);
- }
-
- // null and empty pass — [Required] handles presence; this attribute only checks content
- [Fact]
- public void Null_Passes()
- {
- var (isValid, _) = Validate(null, ['!']);
- Assert.True(isValid);
- }
-
- [Fact]
- public void EmptyString_Passes()
- {
- var (isValid, _) = Validate(string.Empty, ['!']);
- Assert.True(isValid);
- }
-
- public class Passes
- {
- private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
- => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
-
- // Punctuation has no case variants — IgnoreCase must not affect the result either way
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase);
- Assert.True(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hello!@#", [], ignoreCase);
- Assert.True(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase);
- Assert.True(isValid);
- }
-
- [Fact]
- public void NonString_Passes()
- {
- var attribute = new DisallowedCharactersAttribute('!');
- var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
- var result = attribute.GetValidationResult(42, context);
- Assert.Equal(ValidationResult.Success, result);
- }
-
- // IgnoreCase = false only: a disallowed letter in one case does not block the other case
- [Fact]
- public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase()
- {
- var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false);
- Assert.True(isValid);
- }
-
- [Fact]
- public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase()
- {
- var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false);
- Assert.True(isValid);
- }
- }
-
- public class Fails
- {
- private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
- => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
-
- // Punctuation has no case variants — IgnoreCase must not affect the result either way
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hello!", ['!'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("!hello", ['!'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hello!", ['!'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase);
- Assert.False(isValid);
- }
-
- [Theory]
- [InlineData(true)]
- [InlineData(false)]
- public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase)
- {
- var (isValid, _) = Validate("пользователь", ['е'], ignoreCase);
- Assert.False(isValid);
- }
-
- // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent
- [Fact]
- public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase()
- {
- var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true);
- Assert.False(isValid);
- }
-
- [Fact]
- public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase()
- {
- var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true);
- Assert.False(isValid);
- }
-
- [Fact]
- public void CaseSensitive_ExactMatch_Fails()
- {
- var (isValid, _) = Validate("hello", ['h'], ignoreCase: false);
- Assert.False(isValid);
- }
- }
-
- public class ErrorMessage_Contains
- {
- private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true)
- => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase);
-
- [Fact]
- public void DisplayName()
- {
- var (_, errorMessage) = Validate("hello!", ['!']);
- Assert.Contains("Field", errorMessage);
- }
-
- [Fact]
- public void TheDisallowedChar()
- {
- var (_, errorMessage) = Validate("hello!", ['!']);
- Assert.Contains("'!'", errorMessage);
- }
-
- [Fact]
- public void AllPresentDisallowedChars()
- {
- var (_, errorMessage) = Validate("h!@l", ['!', '@']);
- Assert.Contains("'!'", errorMessage);
- Assert.Contains("'@'", errorMessage);
- }
-
- [Fact]
- public void EachOccurrenceOfRepeatedChar()
- {
- // "he!lo!" has two '!' — both occurrences are listed
- var (_, errorMessage) = Validate("he!lo!", ['!']);
- Assert.Equal(2, errorMessage.Split("'!'").Length - 1);
- }
-
- [Fact]
- public void OnlyCharsActuallyPresent_NotAllDisallowedChars()
- {
- // '@' is disallowed but not in the value — must not appear in the message
- var (_, errorMessage) = Validate("hello!", ['!', '@']);
- Assert.Contains("'!'", errorMessage);
- Assert.DoesNotContain("'@'", errorMessage);
- }
-
- [Fact]
- public void IgnoreCase_ShowsActualChar_NotDisallowedChar()
- {
- // 'a' is disallowed (lowercase); value contains 'A' (uppercase).
- // The message reports what the user supplied ('A'), not the disallowed definition ('a').
- var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true);
- Assert.Contains("'A'", errorMessage);
- Assert.DoesNotContain("'a'", errorMessage);
- }
- }
-} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs
new file mode 100644
index 00000000..a26bb160
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs
@@ -0,0 +1,106 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class GuidAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false)
+ {
+ var attribute = new GuidAttribute(allowEmpty);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ // null is allowed; [Required] dictates whether the field must be defined
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_String_Fails_If_AllowEmpty_False()
+ {
+ var (isValid, message) = Validate("00000000-0000-0000-0000-000000000000", allowEmpty: false);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void Empty_Guid_Fails_If_AllowEmpty_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty, allowEmpty: false);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void AllowEmpty_Guid_Defaults_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty);
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void AllowEmpty_String_Defaults_False()
+ {
+ var (isValid, message) = Validate(Guid.Empty.ToString());
+ Assert.False(isValid);
+ Assert.Contains("empty", message);
+ }
+
+ [Fact]
+ public void Empty_String_Passes_If_AllowEmpty_True()
+ {
+ var (isValid, _) = Validate(Guid.Empty.ToString(), allowEmpty: true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_Guid_Passes_If_AllowEmpty_True()
+ {
+ var (isValid, _) = Validate(Guid.Empty, allowEmpty: true);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens
+ [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens
+ [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format)
+ [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format
+ [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format
+ [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's
+ public void ValidGuidString_Passes(string value)
+ {
+ var (isValid, _) = Validate(value);
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("not-a-guid")] // arbitrary string
+ [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short
+ [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z
+ [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long
+ [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g
+ [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens
+ public void InvalidGuidString_Fails(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.False(isValid);
+ Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage);
+ }
+
+ [Fact]
+ public void NonStringValue_Fails()
+ {
+ var (isValid, errorMessage) = Validate(42);
+ Assert.False(isValid);
+ Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage);
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs
new file mode 100644
index 00000000..12efb899
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs
@@ -0,0 +1,94 @@
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class NonTraversingPathAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(string value)
+ {
+ var attribute = new NonTraversingPathAttribute();
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attribute.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ // paths can be null or empty; [Required] dictates whether they must be defined
+ [Fact]
+ public void Null_Passes()
+ {
+ var (isValid, _) = Validate(null);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyString_Passes()
+ {
+ var (isValid, _) = Validate(string.Empty);
+ Assert.True(isValid);
+ }
+
+ public class NonTraversal_Passes
+ {
+ [Theory]
+ // Windows-style
+ [InlineData("C:\\Music\\foo\\Windows")]
+ [InlineData("C:/Music/foo/Windows")]
+ // Unix-style
+ [InlineData("/home/user/foo/etc")]
+ [InlineData("\\home\\user\\foo\\etc")]
+ // UNC (backslash)
+ [InlineData("\\\\server\\share\\foo\\folder")]
+ // UNC (forward slash)
+ [InlineData("//server/foo/share")]
+ // soulseek
+ [InlineData("@foo/bar/baz")]
+ [InlineData("@foo\\bar\\baz")]
+ // filenames
+ [InlineData("@foo/bar/baz/baz../..qux/file.ext")]
+ public void NonTraversalSegment_Passes(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.True(isValid);
+ Assert.Null(errorMessage);
+ }
+ }
+
+ // Paths containing . or .. segments, which are valid directory names in isolation
+ // but indicate traversal or ambiguity and must be rejected regardless of whether
+ // the path is otherwise absolute or relative.
+ public class Traversal_Fails
+ {
+ [Theory]
+ // Windows-style
+ [InlineData("C:\\Music\\..\\Windows")]
+ [InlineData("C:\\Music\\.\\Artist")]
+ [InlineData("C:/Music/../Windows")]
+ [InlineData("C:/Music/./Artist")]
+ [InlineData("C:\\..")]
+ [InlineData("D:\\a\\b\\..\\c")]
+ // Unix-style
+ [InlineData("/../etc")]
+ [InlineData("/home/user/../etc")]
+ [InlineData("/home/user/./Music")]
+ [InlineData("/home/../../etc")]
+ // UNC (backslash)
+ [InlineData("\\\\server\\..\\Windows")]
+ [InlineData("\\\\server\\share\\..\\other")]
+ [InlineData("\\\\server\\share\\.\\folder")]
+ // UNC (forward slash)
+ [InlineData("//server/../share")]
+ [InlineData("//server/share/../other")]
+ // soulseek
+ [InlineData("@foo/bar/baz/baz/../file.ext")]
+ [InlineData("@foo/bar/baz/./../file.ext")]
+ [InlineData("@foo/bar/baz/./baz/file.ext")]
+ public void TraversalSegment_Fails(string value)
+ {
+ var (isValid, errorMessage) = Validate(value);
+ Assert.False(isValid);
+ Assert.Contains("traversal segments", errorMessage);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
index 647bc05f..bc581bf1 100644
--- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
+++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs
@@ -66,32 +66,6 @@ public class RelativePathAttributeTests
}
}
- public class Traversal_Fails
- {
- [Theory]
- [InlineData("..")] // bare traversal
- [InlineData(".")] // bare current-dir
- [InlineData("../music")] // traversal prefix, forward slash
- [InlineData("./music")] // current-dir prefix
- [InlineData("music/../other")] // traversal in middle
- [InlineData("music/./other")] // current-dir in middle
- [InlineData("sub/../../escape")] // double traversal
- [InlineData("music\\..")] // traversal via backslash
- [InlineData("music\\.")] // current-dir via backslash
- [InlineData("music/dir/..")] // traversal at end
- [InlineData("a/b/c/../../d")] // multi-level traversal
- [InlineData("Ünïcödé/../escape")] // latin extended with traversal
- [InlineData("пользователь/../etc")] // Cyrillic with traversal
- [InlineData("用户/音乐/../../escape")] // Chinese with deep traversal
- [InlineData("ユーザー\\..\\escape")] // Japanese with backslash traversal
- public void TraversalSegment_Fails(string value)
- {
- var (isValid, errorMessage) = Validate(value);
- Assert.False(isValid);
- Assert.Contains("traversal segments", errorMessage);
- }
- }
-
public class Absolute_Fails
{
[Theory]
@@ -128,4 +102,4 @@ public class RelativePathAttributeTests
Assert.Equal("The Field field must be a relative path.", errorMessage);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs
new file mode 100644
index 00000000..dbc82736
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs
@@ -0,0 +1,422 @@
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.Text.RegularExpressions;
+using slskd.Validation;
+using Xunit;
+
+namespace slskd.Tests.Unit.Common.Validation;
+
+public class StringAttributeTests
+{
+ private static (bool IsValid, string ErrorMessage) Validate(string value, Action<StringAttribute> configure = null)
+ {
+ var attr = new StringAttribute();
+ configure?.Invoke(attr);
+ var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" };
+ var result = attr.GetValidationResult(value, context);
+ return (result == null, result?.ErrorMessage);
+ }
+
+ public class Null
+ {
+ [Fact]
+ public void Passes_When_AllowNull()
+ {
+ var (isValid, message) = Validate(null, a => a.AllowNull = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Fails_When_Not_AllowNull()
+ {
+ var (isValid, message) = Validate(null, a => a.AllowNull = false);
+ Assert.False(isValid);
+ Assert.Contains("must not be null", message);
+ }
+
+ [Fact]
+ public void NonNull_Passes_Regardless()
+ {
+ var (isValid, message) = Validate("foo", a => a.AllowNull = true);
+ Assert.True(isValid);
+
+ var (isValid2, message2) = Validate("foo", a => a.AllowNull = false);
+ Assert.True(isValid);
+ }
+ }
+
+ public class Empty
+ {
+ [Fact]
+ public void Empty_Passes_When_AllowEmpty_Is_True()
+ {
+ var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Empty_Fails_When_AllowEmpty_Is_False()
+ {
+ var (isValid, message) = Validate(string.Empty, a => a.AllowEmpty = false);
+ Assert.False(isValid);
+ Assert.Contains("at least one character", message);
+ }
+
+ [Fact]
+ public void NonEmpty_Passes_Regardless()
+ {
+ var (isValid, _) = Validate("hello", a => a.AllowEmpty = false);
+ Assert.True(isValid);
+
+ var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true);
+ Assert.True(isValid);
+ }
+ }
+
+ public class WhiteSpace
+ {
+ [Fact]
+ public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True()
+ {
+ var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = true);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False()
+ {
+ var (isValid, message) = Validate(" ", a => a.AllowWhiteSpace = false);
+ Assert.False(isValid);
+ Assert.Contains("whitespace", message);
+ }
+
+ [Fact]
+ public void NonWhiteSpace_Passes_Regardless()
+ {
+ var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false);
+ Assert.True(isValid);
+
+ var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true);
+ Assert.True(isValid);
+ }
+ }
+
+ public class DisallowedCharacters
+ {
+ public class Passes
+ {
+ [Fact]
+ public void EmptyString_Passes()
+ {
+ var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NoDisallowedCharsPresent_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void EmptyDisallowedSet_Passes()
+ {
+ var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void Unicode_AllowedChars_Pass()
+ {
+ var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.True(isValid);
+ }
+
+ // Case-insensitive matching only folds the declared disallowed chars, not all letters;
+ // a disallowed lower-case letter does not block an entirely different upper-case letter.
+ [Fact]
+ public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter()
+ {
+ var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']);
+ Assert.True(isValid);
+ }
+ }
+
+ public class Fails
+ {
+ [Fact]
+ public void SingleDisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtStart_Fails()
+ {
+ var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharAtEnd_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharInMiddle_Fails()
+ {
+ var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void OneOfMultipleDisallowedCharsPresent_Fails()
+ {
+ var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void MultipleDisallowedCharsAllPresent_Fails()
+ {
+ var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void DisallowedCharRepeated_Fails()
+ {
+ var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void AllCharsDisallowed_Fails()
+ {
+ var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void Unicode_DisallowedChar_Fails()
+ {
+ var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']);
+ Assert.False(isValid);
+ }
+
+ // character matching is always case-insensitive
+ [Fact]
+ public void LowerCaseDisallowed_Blocks_UpperCase()
+ {
+ var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void UpperCaseDisallowed_Blocks_LowerCase()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ExactMatch_Fails()
+ {
+ var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']);
+ Assert.False(isValid);
+ }
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void TheDisallowedChar()
+ {
+ var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']);
+ Assert.Contains("'!'", errorMessage);
+ }
+
+ [Fact]
+ public void AllPresentDisallowedChars()
+ {
+ var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.Contains("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void EachOccurrenceOfRepeatedChar()
+ {
+ // "he!lo!" has two '!' — both occurrences are listed
+ var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']);
+ Assert.Equal(2, errorMessage.Split("'!'").Length - 1);
+ }
+
+ [Fact]
+ public void OnlyCharsActuallyPresent_NotAllDisallowedChars()
+ {
+ // '@' is disallowed but not in the value — must not appear in the message
+ var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']);
+ Assert.Contains("'!'", errorMessage);
+ Assert.DoesNotContain("'@'", errorMessage);
+ }
+
+ [Fact]
+ public void ShowsActualChar_NotDisallowedChar()
+ {
+ // 'a' is disallowed (lowercase); value contains 'A' (uppercase).
+ // The message reports what the user supplied ('A'), not the disallowed definition ('a').
+ var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']);
+ Assert.Contains("'A'", errorMessage);
+ Assert.DoesNotContain("'a'", errorMessage);
+ }
+ }
+ }
+
+ public class Length
+ {
+ [Fact]
+ public void Within_Range_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => { a.MinimumLength = 3; a.MaximumLength = 10; });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ExactlyAtMinimumLength_Passes()
+ {
+ var (isValid, _) = Validate("hi", a => a.MinimumLength = 2);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ExactlyAtMaximumLength_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.MaximumLength = 5);
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void BelowMinimumLength_Fails()
+ {
+ var (isValid, _) = Validate("hi", a => a.MinimumLength = 5);
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ExceedsMaximumLength_Fails()
+ {
+ var (isValid, _) = Validate("hello world", a => a.MaximumLength = 5);
+ Assert.False(isValid);
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void MinimumLength_Value()
+ {
+ var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; });
+ Assert.Contains("5", message);
+ }
+
+ [Fact]
+ public void MaximumLength_Value()
+ {
+ var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; });
+ Assert.Contains("20", message);
+ }
+ }
+ }
+
+ public class Pattern
+ {
+ [Fact]
+ public void NullPattern_Passes()
+ {
+ // Pattern defaults to null; any value passes the pattern check
+ var (isValid, _) = Validate("hello");
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void ValueMatchingPattern_Fails()
+ {
+ var (isValid, _) = Validate("hello1", a => a.Pattern = new Regex("[0-9]"));
+ Assert.False(isValid);
+ }
+
+ [Fact]
+ public void ValueNotMatchingPattern_Passes()
+ {
+ var (isValid, _) = Validate("hello", a => a.Pattern = new Regex("[0-9]"));
+ Assert.True(isValid);
+ }
+
+ public class ErrorMessage_Contains
+ {
+ [Fact]
+ public void RegularExpression_Keyword()
+ {
+ var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]"));
+ Assert.Contains("regular expression", message);
+ }
+ }
+ }
+
+ public class CheckOrdering
+ {
+ // AllowNull is checked before AllowEmpty:
+ // null with both disabled returns the null error, not the empty error.
+ [Fact]
+ public void Null_ReturnsNullError_Not_EmptyError()
+ {
+ var (_, message) = Validate(null, a => { a.AllowNull = false; a.AllowEmpty = false; });
+ Assert.Contains("null", message);
+ Assert.DoesNotContain("character", message);
+ }
+
+ // AllowEmpty is checked before AllowWhiteSpace:
+ // "" with both disabled returns the empty error, not the whitespace error.
+ [Fact]
+ public void Empty_ReturnsEmptyError_Not_WhitespaceError()
+ {
+ var (_, message) = Validate(string.Empty, a => { a.AllowEmpty = false; a.AllowWhiteSpace = false; });
+ Assert.Contains("character", message);
+ Assert.DoesNotContain("whitespace", message);
+ }
+
+ // AllowWhiteSpace is checked before the length check:
+ // a whitespace string that is also below MinimumLength returns the whitespace error.
+ [Fact]
+ public void Whitespace_ReturnsWhitespaceError_Not_LengthError()
+ {
+ var (_, message) = Validate(" ", a => { a.AllowWhiteSpace = false; a.MinimumLength = 10; });
+ Assert.Contains("whitespace", message);
+ Assert.DoesNotContain("between", message);
+ }
+
+ // Length is checked before DisallowedCharacters:
+ // a too-short string that also contains a disallowed character returns the length error.
+ [Fact]
+ public void TooShort_ReturnsLengthError_Not_DisallowedCharsError()
+ {
+ var (_, message) = Validate("hi!", a => { a.MinimumLength = 10; a.DisallowedCharacters = ['!']; });
+ Assert.Contains("between", message);
+ Assert.DoesNotContain("disallowed", message);
+ }
+
+ // DisallowedCharacters is checked before Pattern:
+ // a string with a disallowed character that also matches the pattern returns the disallowed-chars error.
+ [Fact]
+ public void DisallowedChar_ReturnsDisallowedError_Not_PatternError()
+ {
+ var (_, message) = Validate("hello!1", a => { a.DisallowedCharacters = ['!']; a.Pattern = new Regex("[0-9]"); });
+ Assert.Contains("disallowed", message);
+ Assert.DoesNotContain("expression", message);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs
new file mode 100644
index 00000000..7eacb95d
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs
@@ -0,0 +1,40 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Xunit;
+using static slskd.Options;
+
+namespace slskd.Tests.Unit.Core.Options;
+
+public class SharesOptionsTests
+{
+ private static List<ValidationResult> Validate(SharesOptions options)
+ {
+ var context = new ValidationContext(options);
+ var results = new List<ValidationResult>();
+ Validator.TryValidateObject(options, context, results, validateAllProperties: true);
+ return results;
+ }
+
+ public class Directories
+ {
+ public class Digest
+ {
+ [Fact]
+ public void Alias_Uses_First_Closing_Bracket_When_Path_Contains_Brackets()
+ {
+ // [foo]/bar/[baz]/ should digest to alias "foo" and path "/bar/[baz]"
+ var options = new SharesOptions
+ {
+ Directories = [@"[foo]/bar/[baz]/"]
+ };
+
+ // todo: fix this so that it fully validates on all platforms; currently this fails
+ // validation on Windows and would fail on Linux if i were to use backslashes
+ // the assertion for the alias proves we have fixed an aliasing bug so it's fine for now
+ var results = Validate(options);
+
+ Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true);
+ }
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs
new file mode 100644
index 00000000..a9f30129
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs
@@ -0,0 +1,304 @@
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using slskd.Transfers.API;
+using Xunit;
+
+namespace slskd.Tests.Unit.Transfers.API.DTO;
+
+public class QueueDownloadBatchRequestTests
+{
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ {
+ var results = new List<ValidationResult>();
+ var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true);
+ return (isValid, results);
+ }
+
+ private static QueueDownloadBatchRequest ValidRequest() => new()
+ {
+ Username = "testuser",
+ Files = [new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }],
+ };
+
+ public class Id_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Id = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("not-a-guid")]
+ [InlineData("b5bde3d1-4aba-4d64-b64a")]
+ public void NonGuid_Fails(string value)
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Id = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The Id field must be a valid GUID/UUID", results[0].ErrorMessage);
+ }
+
+ [Theory]
+ [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")]
+ [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")]
+ [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")]
+ public void ValidGuid_Passes(string value)
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Id = value });
+ Assert.True(isValid);
+ }
+ }
+
+ public class SearchId_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { SearchId = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("not-a-guid")]
+ [InlineData("b5bde3d1-4aba-4d64-b64a")]
+ public void NonGuid_Fails(string value)
+ {
+ var (isValid, results) = Validate(ValidRequest() with { SearchId = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The SearchId field must be a valid GUID/UUID", results[0].ErrorMessage);
+ }
+
+ [Theory]
+ [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")]
+ [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")]
+ [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")]
+ public void ValidGuid_Passes(string value)
+ {
+ var (isValid, _) = Validate(ValidRequest() with { SearchId = value });
+ Assert.True(isValid);
+ }
+ }
+
+ public class Username_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = null });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void Empty_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = "" });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void Whitespace_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = " " });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Username field is required.");
+ }
+
+ [Fact]
+ public void OneChar_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Username = "a" });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void FiveHundredChars_Passes()
+ {
+ var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 500) });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void FiveHundredOneChars_Fails()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage);
+ }
+ }
+
+ public class Files_Field
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Fails_WithRequiredMessage()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Files = null });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The Files field is required.", results[0].ErrorMessage);
+ }
+
+ [Fact]
+ public void EmptyList_Fails_WithMinLengthMessage()
+ {
+ var (isValid, results) = Validate(ValidRequest() with { Files = [] });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("minimum length of '1'", results[0].ErrorMessage);
+ }
+ }
+
+ public class Files_Item
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void NullFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void EmptyFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void WhitespaceFilename_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = " ", Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required.");
+ }
+
+ [Fact]
+ public void ValidFilename_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void NegativeSize_Fails()
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The field Size must be between 0 and 9.223372036854776E+18.", results[0].ErrorMessage);
+ }
+
+ [Fact]
+ public void ZeroSize_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 });
+ Assert.True(isValid);
+ }
+
+ [Fact]
+ public void PositiveSize_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("@foo/bar/../baz/file.mp3")]
+ [InlineData("@foo/bar/./baz/file.mp3")]
+ [InlineData("@foo\\bar\\..\\baz\\file.mp3")]
+ public void TraversalSegmentInFilename_Fails(string value)
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 });
+ Assert.False(isValid);
+ Assert.Contains(results, r => r.ErrorMessage != null && r.ErrorMessage.Contains("traversal segments"));
+ }
+
+ [Theory]
+ [InlineData("@foo/bar/baz/file.mp3")]
+ [InlineData("@foo/bar/baz/file..ext")]
+ [InlineData("@foo\\bar\\baz\\file.mp3")]
+ public void NonTraversalFilename_Passes(string value)
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 });
+ Assert.True(isValid);
+ }
+ }
+
+ public class Options_Destination
+ {
+ private static (bool IsValid, List<ValidationResult> Results) Validate(object obj)
+ => QueueDownloadBatchRequestTests.Validate(obj);
+
+ [Fact]
+ public void Omitted_Passes()
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = null });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("Artist\\Album")]
+ public void RelativePath_Passes(string value)
+ {
+ var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.True(isValid);
+ }
+
+ [Theory]
+ [InlineData("C:\\Music")] // Windows absolute
+ [InlineData("C:/Music")] // Windows absolute, forward slash
+ [InlineData("/music")] // Unix absolute
+ [InlineData("/home/user/Music")] // Unix absolute, deep
+ [InlineData("\\\\server\\share")] // UNC
+ public void AbsolutePath_Fails(string value)
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage);
+ }
+
+ [Theory]
+ [InlineData("../escape")] // traversal prefix
+ [InlineData("./music")] // current-dir prefix
+ [InlineData("music/../other")] // traversal in middle
+ [InlineData("sub/../../escape")] // double traversal
+ [InlineData("music\\..")] // traversal via backslash
+ public void TraversalSegment_Fails(string value)
+ {
+ var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value });
+ Assert.False(isValid);
+ Assert.Single(results);
+ Assert.Contains("traversal segments", results[0].ErrorMessage);
+ }
+ }
+}