From f12d89de3381c59393444b602e762ae5d8146984 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 19:11:42 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 494ee722..ad537dfb 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,6 +216,66 @@ namespace slskd.Transfers.API } } + [HttpPost("downloads")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + // todo, check: username null or whitespace + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetReadableString()); + } + + if ((request.Files?.Count ?? 0) == 0) + { + return BadRequest("At least one file is required"); + } + + // todo, check: + // * filename null or whitespace + // * size -1 + if (request.Files.Any(r => r is null)) + { + return BadRequest("One or more files in the request are invalid"); + } + + 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"); + } + + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); + + return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); + return StatusCode(500, ex.Message); + } + finally + { + DownloadRequestLimiter.Release(); + } + } + /// /// Enqueues the specified download. /// -- cgit v1.2.3 From 11f4fe864ac67cd6cba54845afc1ab943cdaa564 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 12:43:27 -0500 Subject: add Batch type --- src/slskd/Transfers/Types/Batch.cs | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/slskd/Transfers/Types/Batch.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs new file mode 100644 index 00000000..820db66e --- /dev/null +++ b/src/slskd/Transfers/Types/Batch.cs @@ -0,0 +1,49 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +public class Batch +{ + public Guid? SearchId { get; init; } = null; + + [Key] + public Guid Id { get; init; } + public string Destination { get; init; } + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + + public ICollection Transfers { get; set; } +} \ No newline at end of file -- cgit v1.2.3 From 003b291e20788bba6229bd043688d208eb6261fe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 12:44:20 -0500 Subject: add Batch to dbcontext --- src/slskd/Transfers/TransfersDbContext.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index be312e8e..063253cf 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -43,6 +43,7 @@ namespace slskd.Transfers { } + public DbSet Batches { get; set; } public DbSet Transfers { get; set; } public override int SaveChanges(bool acceptAllChangesOnSuccess) @@ -113,6 +114,18 @@ namespace slskd.Transfers .Entity() .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); + + modelBuilder + .Entity() + .Property(e => e.CreatedAt) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder + .Entity() + .HasMany(b => b.Transfers) + .WithOne() + .HasForeignKey(t => t.BatchId) + .IsRequired(false); } } } -- cgit v1.2.3 From da732237ce6e87b40ccd0b042255e19e40d27682 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 13:16:32 -0500 Subject: remove deprecated Summarize method from UploadService --- src/slskd/Transfers/Uploads/UploadService.cs | 50 ---------------------------- 1 file changed, 50 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 72e3c0ef..e0d11a11 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -100,16 +100,6 @@ namespace slskd.Transfers.Uploads /// The found transfer, or default if not found. Transfer Find(Expression> expression); - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the number of files and total size in bytes. - /// - (int Files, long Bytes) Summarize(Expression> expression); - /// /// Gets upload statistics for the specified . /// @@ -740,46 +730,6 @@ namespace slskd.Transfers.Uploads } } - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the number of files and total size in bytes. - /// - public (int Files, long Bytes) Summarize(Expression> 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); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); - throw; - } - } - /// /// Returns a list of all uploads matching the optional . /// -- cgit v1.2.3 From 169cd154ba14c97073899b3b6db947419ecf267e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:19:12 -0500 Subject: rough in Batch --- src/slskd/Transfers/Types/Batch.cs | 72 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 820db66e..30633cc9 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -35,6 +35,9 @@ namespace slskd.Transfers; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using Soulseek; public class Batch { @@ -42,8 +45,73 @@ public class Batch [Key] public Guid Id { get; init; } - public string Destination { get; init; } + public string Username { get; init; } + public TransferDirection Direction { get; } = TransferDirection.Download; + + [NotMapped] + public TransferStates State => ComputeState(); + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - public ICollection Transfers { get; set; } + [NotMapped] + public DateTime? EndedAt => Transfers.Max(t => t.EndedAt); + + public ICollection Transfers { get; set; } = []; + + public string Destination { get; init; } + + [NotMapped] + public long BytesTransferred => Transfers.Sum(t => t.BytesTransferred); + [NotMapped] + public int Files => Transfers.Count; + [NotMapped] + public long Size => Transfers.Sum(t => t.Size); + [NotMapped] + public long BytesRemaining => Size - BytesTransferred; + [NotMapped] + public TimeSpan ElapsedTime => DateTime.UtcNow - CreatedAt; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + + [NotMapped] + public double AverageSpeed => Transfers + .Where(t => TransferStateCategories.Successful.Contains(t.State)) + .Select(t => t.AverageSpeed) + .DefaultIfEmpty(0) + .Average(); + + [NotMapped] + public bool Removed => Transfers.All(t => t.Removed); + + private TransferStates ComputeState() + { + // if there's a transfer in progress, the batch is in progress + if (Transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) + { + return TransferStates.InProgress; + } + + // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), + // the batch is queued. it doesn't matter if one or more are errored, they might be retried + if (Transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) + { + return TransferStates.Queued; + } + + // if all transfers completed successfully, the batch did too + if (Transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) + { + return TransferStates.Completed | TransferStates.Succeeded; + } + + // if one or more transfers failed and there are no more enqueued files, + // the batch errored and it will not recover on its own + if (Transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) + { + return TransferStates.Completed | TransferStates.Errored; + } + + // unclear how we would get here + return TransferStates.None; + } } \ No newline at end of file -- cgit v1.2.3 From da6c14ad62fc201eaf7c24470b5da972dd861ace Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:19:29 -0500 Subject: add Requested to Queued category (optimistically) --- src/slskd/Transfers/Types/TransferStateCategories.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Transfers') 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 /// /// public static readonly HashSet 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 -- cgit v1.2.3 From 96fda39aeb290524c00a24846c448bdfd2527663 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:21:34 -0500 Subject: prevent downloads from transitioning into terminal state while retries are available (but not if the Soulseek.NET transfer is not dead) --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d4d8004a..0ccf52c3 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -973,9 +973,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 -- cgit v1.2.3 From a5e624121469cd84a4b197ad204c2ac5c2d7274d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:21:58 -0500 Subject: improve readability of TransfersDbContext --- src/slskd/Transfers/TransfersDbContext.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 063253cf..ce2d9f52 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -61,6 +61,12 @@ namespace slskd.Transfers } protected override void OnModelCreating(ModelBuilder modelBuilder) + { + ConfigureTransfers(modelBuilder); + ConfigureBatches(modelBuilder); + } + + private void ConfigureTransfers(ModelBuilder modelBuilder) { modelBuilder .Entity() @@ -114,7 +120,10 @@ namespace slskd.Transfers .Entity() .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() .Property(e => e.CreatedAt) -- cgit v1.2.3 From 920d11fffbecf84d737781037992fdfc06ffa1cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:23:46 -0500 Subject: rough in batch service --- src/slskd/Transfers/Batches/BatchService.cs | 179 ++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 src/slskd/Transfers/Batches/BatchService.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs new file mode 100644 index 00000000..515201c9 --- /dev/null +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -0,0 +1,179 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Serilog; + + /// + /// Manages transfer batches. + /// + public interface IBatchService + { + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + Batch Create(Batch batch); + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + Task FindAsync(Expression> expression); + + /// + /// Returns a list of all batches matching the optional . + /// + /// An optional expression used to match batches. + /// The list of batches matching the specified expression, or all batches if no expression is specified. + Task> ListAsync(Expression> expression = null); + + /// + /// Marks all transfers associated with the specified batch as removed. + /// + /// The unique identifier of the batch. + /// Thrown when the batch does not exist. + void Remove(Guid id); + } + + /// + /// Manages transfer batches. + /// + public class BatchService : IBatchService + { + /// + /// Initializes a new instance of the class. + /// + /// The database context factory to use. + public BatchService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + public Batch Create(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Batches.Add(batch); + context.SaveChanges(); + + Log.Debug("Created batch {Id}", batch.Id); + + return batch; + } + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + public Task FindAsync(Expression> expression) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + return context.Batches + .AsNoTracking() + .Where(expression) + .Include(b => b.Transfers) + .FirstOrDefaultAsync(); + } + + /// + /// Returns a list of all batches matching the optional . + /// + /// An optional expression used to match batches. + /// The list of batches matching the specified expression, or all batches if no expression is specified. + public Task> ListAsync(Expression> expression = null) + { + expression ??= b => true; + + using var context = ContextFactory.CreateDbContext(); + + return context.Batches + .AsNoTracking() + .Where(expression) + .Include(b => b.Transfers) + .ToListAsync(); + } + + /// + /// Marks all transfers associated with the specified batch as removed. + /// + /// The unique identifier of the batch. + /// Thrown when the batch does not exist. + public void Remove(Guid id) + { + using var context = ContextFactory.CreateDbContext(); + + var exists = context.Batches.Any(b => b.Id == id); + + if (!exists) + { + throw new NotFoundException($"No batch with id {id}"); + } + + context.Transfers + .Where(t => t.BatchId == id) + .ExecuteUpdate(s => s.SetProperty(t => t.Removed, true)); + + Log.Debug("Marked transfers for batch {Id} as removed", id); + } + } +} -- cgit v1.2.3 From 59e2e9de29de2dea134c5fbaf3a518b2fe0d82b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:23:58 -0500 Subject: wip transferscontroller --- .../API/Controllers/TransfersController.cs | 118 ++++++++++----------- 1 file changed, 59 insertions(+), 59 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ad537dfb..9f2fba6d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,65 +216,65 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) - { - if (Program.IsRelayAgent) - { - return Forbid(); - } - - // todo, check: username null or whitespace - if (!ModelState.IsValid) - { - return BadRequest(ModelState.GetReadableString()); - } - - if ((request.Files?.Count ?? 0) == 0) - { - return BadRequest("At least one file is required"); - } - - // todo, check: - // * filename null or whitespace - // * size -1 - if (request.Files.Any(r => r is null)) - { - return BadRequest("One or more files in the request are invalid"); - } - - 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"); - } - - var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); - - return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); - return StatusCode(500, ex.Message); - } - finally - { - DownloadRequestLimiter.Release(); - } - } + // [HttpPost("downloads")] + // [Authorize(Policy = AuthPolicy.Any)] + // [ProducesResponseType(201)] + // [ProducesResponseType(typeof(string), 403)] + // [ProducesResponseType(typeof(string), 500)] + // public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + // { + // if (Program.IsRelayAgent) + // { + // return Forbid(); + // } + + // // todo, check: username null or whitespace + // if (!ModelState.IsValid) + // { + // return BadRequest(ModelState.GetReadableString()); + // } + + // if ((request.Files?.Count ?? 0) == 0) + // { + // return BadRequest("At least one file is required"); + // } + + // // todo, check: + // // * filename null or whitespace + // // * size -1 + // if (request.Files.Any(r => r is null)) + // { + // return BadRequest("One or more files in the request are invalid"); + // } + + // 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"); + // } + + // var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); + + // return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); + // } + // catch (Exception ex) + // { + // Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); + // return StatusCode(500, ex.Message); + // } + // finally + // { + // DownloadRequestLimiter.Release(); + // } + // } /// /// Enqueues the specified download. -- cgit v1.2.3 From 9507e547dd68f1142b0b7a455a52ce5b6ad3d50e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:12:51 -0500 Subject: tweak Batch more --- src/slskd/Transfers/Types/Batch.cs | 43 +++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 21 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 30633cc9..aa61f069 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -37,6 +37,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Text.Json.Serialization; using Soulseek; public class Batch @@ -47,41 +48,41 @@ public class Batch public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; } = TransferDirection.Download; + public string Destination { get; init; } + public int Files { get; init; } + public long Size { get; init; } [NotMapped] public TransferStates State => ComputeState(); public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons - [NotMapped] - public DateTime? EndedAt => Transfers.Max(t => t.EndedAt); - - public ICollection Transfers { get; set; } = []; + /// + /// The transfers associated with the batch. + /// + /// + /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. + /// + public ICollection Transfers { get; set; } - public string Destination { get; init; } - - [NotMapped] - public long BytesTransferred => Transfers.Sum(t => t.BytesTransferred); [NotMapped] - public int Files => Transfers.Count; - [NotMapped] - public long Size => Transfers.Sum(t => t.Size); - [NotMapped] - public long BytesRemaining => Size - BytesTransferred; + public long BytesTransferred { get; set; } + [NotMapped] - public TimeSpan ElapsedTime => DateTime.UtcNow - CreatedAt; + public long BytesRemaining { get; set; } + [NotMapped] - public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; [NotMapped] - public double AverageSpeed => Transfers - .Where(t => TransferStateCategories.Successful.Contains(t.State)) - .Select(t => t.AverageSpeed) - .DefaultIfEmpty(0) - .Average(); + public double PercentComplete { get; set; } [NotMapped] - public bool Removed => Transfers.All(t => t.Removed); + public double AverageSpeed { get; set; } + + [JsonIgnore] + public bool Removed { get; set; } private TransferStates ComputeState() { -- cgit v1.2.3 From 3eec5bd5d1f6ebd48ce183435cca4a96740c35ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:50:19 -0500 Subject: optimized list and find --- src/slskd/Transfers/Batches/BatchService.cs | 83 ++++++++++++++++++++++++++--- src/slskd/Transfers/Types/Batch.cs | 18 +++---- 2 files changed, 86 insertions(+), 15 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index 515201c9..565e715e 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -39,6 +39,7 @@ namespace slskd.Transfers using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using Soulseek; /// /// Manages transfer batches. @@ -119,7 +120,7 @@ namespace slskd.Transfers /// The expression to use to match batches. /// The found batch, or default if not found. /// Thrown when an expression is not supplied. - public Task FindAsync(Expression> expression) + public async Task FindAsync(Expression> expression) { if (expression == default) { @@ -128,11 +129,32 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - return context.Batches + var batch = await context.Batches .AsNoTracking() .Where(expression) - .Include(b => b.Transfers) .FirstOrDefaultAsync(); + + if (batch is null) + { + return null; + } + + var transfers = await context.Transfers + .AsNoTracking() + .Where(t => t.BatchId == batch.Id) + .ToListAsync(); + + var bytesTransferred = transfers.Sum(t => t.BytesTransferred); + + return batch with + { + Transfers = transfers, + BytesTransferred = bytesTransferred, + BytesRemaining = transfers.Sum(t => t.BytesRemaining), + PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, + AverageSpeed = transfers.Average(t => t.AverageSpeed), + Removed = transfers.All(t => t.Removed), + }; } /// @@ -140,17 +162,66 @@ namespace slskd.Transfers /// /// An optional expression used to match batches. /// The list of batches matching the specified expression, or all batches if no expression is specified. - public Task> ListAsync(Expression> expression = null) + public async Task> ListAsync(Expression> expression = null) { expression ??= b => true; using var context = ContextFactory.CreateDbContext(); - return context.Batches + var batches = await context.Batches .AsNoTracking() .Where(expression) - .Include(b => b.Transfers) .ToListAsync(); + + if (batches.Count == 0) + { + return batches; + } + + var batchIds = batches.Select(b => b.Id).ToList(); + + var stats = (await context.Transfers + .AsNoTracking() + .Where(t => t.BatchId.HasValue && batchIds.Contains(t.BatchId.Value)) + .GroupBy(t => t.BatchId) + .Select(g => new + { + BatchId = g.Key, + BytesTransferred = g.Sum(t => t.BytesTransferred), + BytesRemaining = g.Sum(t => t.BytesRemaining), + AverageSpeed = g.Average(t => t.AverageSpeed), + Removed = g.All(t => t.Removed), + AnyInProgress = g.Any(t => TransferStateCategories.InProgress.Contains(t.State)), + AnyQueued = g.Any(t => TransferStateCategories.Queued.Contains(t.State)), + AllSuccessful = g.All(t => TransferStateCategories.Successful.Contains(t.State)), + AnyFailed = g.Any(t => TransferStateCategories.Failed.Contains(t.State)), + }) + .ToListAsync()) + .ToDictionary(s => s.BatchId); + + return batches.Select(b => + { + if (!stats.TryGetValue(b.Id, out var s)) + { + return b; + } + + var state = s.AnyInProgress ? TransferStates.InProgress + : s.AnyQueued ? TransferStates.Queued + : s.AllSuccessful ? TransferStates.Completed | TransferStates.Succeeded + : s.AnyFailed ? TransferStates.Completed | TransferStates.Errored + : TransferStates.None; + + return b with + { + BytesTransferred = s.BytesTransferred, + BytesRemaining = s.BytesRemaining, + PercentComplete = b.Size == 0 ? 0 : s.BytesTransferred / (double)b.Size, + AverageSpeed = s.AverageSpeed, + Removed = s.Removed, + State = state, + }; + }).ToList(); } /// diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index aa61f069..e15ecde3 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -40,20 +40,20 @@ using System.Linq; using System.Text.Json.Serialization; using Soulseek; -public class Batch +public record Batch { public Guid? SearchId { get; init; } = null; [Key] public Guid Id { get; init; } public string Username { get; init; } - public TransferDirection Direction { get; } = TransferDirection.Download; + public TransferDirection Direction { get; init; } = TransferDirection.Download; public string Destination { get; init; } public int Files { get; init; } public long Size { get; init; } [NotMapped] - public TransferStates State => ComputeState(); + public TransferStates State { get; init; } public DateTime CreatedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons @@ -64,25 +64,25 @@ public class Batch /// /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. /// - public ICollection Transfers { get; set; } + public ICollection Transfers { get; init; } [NotMapped] - public long BytesTransferred { get; set; } + public long BytesTransferred { get; init; } [NotMapped] - public long BytesRemaining { get; set; } + public long BytesRemaining { get; init; } [NotMapped] public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; [NotMapped] - public double PercentComplete { get; set; } + public double PercentComplete { get; init; } [NotMapped] - public double AverageSpeed { get; set; } + public double AverageSpeed { get; init; } [JsonIgnore] - public bool Removed { get; set; } + public bool Removed { get; init; } private TransferStates ComputeState() { -- cgit v1.2.3 From 6daeed10807243ca98718eefe6eeb70e952e553c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:56:28 -0500 Subject: use single or default for find --- src/slskd/Transfers/Batches/BatchService.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index 565e715e..a19ada98 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -132,7 +132,7 @@ namespace slskd.Transfers var batch = await context.Batches .AsNoTracking() .Where(expression) - .FirstOrDefaultAsync(); + .SingleOrDefaultAsync(); if (batch is null) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index e0d11a11..13915e82 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -721,7 +721,8 @@ namespace slskd.Transfers.Uploads return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression).FirstOrDefault(); + .Where(expression) + .SingleOrDefault(); } catch (Exception ex) { -- cgit v1.2.3 From 2b39b7ee61610ca4526269d321f0ece0be6bb521 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Apr 2026 22:13:30 -0500 Subject: make state derivation static --- src/slskd/Transfers/Types/Batch.cs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index e15ecde3..6b3cf15c 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -48,14 +48,19 @@ public record Batch public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; init; } = TransferDirection.Download; - public string Destination { get; init; } public int Files { get; init; } public long Size { get; init; } + public string Destination { get; init; } + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - [NotMapped] - public TransferStates State { get; init; } + /// + /// Gets the current batch state. + /// + /// + /// If the database value is null, value must be derived from the associated transfers. + /// + public TransferStates? State { get; set; } // todo: set when the last file is completed - public DateTime CreatedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons /// @@ -84,30 +89,30 @@ public record Batch [JsonIgnore] public bool Removed { get; init; } - private TransferStates ComputeState() + public static TransferStates DeriveState(IEnumerable transfers) { // if there's a transfer in progress, the batch is in progress - if (Transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) { return TransferStates.InProgress; } // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), // the batch is queued. it doesn't matter if one or more are errored, they might be retried - if (Transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) { return TransferStates.Queued; } // if all transfers completed successfully, the batch did too - if (Transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) + if (transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) { return TransferStates.Completed | TransferStates.Succeeded; } // if one or more transfers failed and there are no more enqueued files, // the batch errored and it will not recover on its own - if (Transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) { return TransferStates.Completed | TransferStates.Errored; } -- cgit v1.2.3 From c502e5fa4595c6db45386aaf210019d56ce20171 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Apr 2026 22:16:19 -0500 Subject: set state in findasync --- src/slskd/Transfers/Batches/BatchService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index a19ada98..ac547d1e 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -146,9 +146,19 @@ namespace slskd.Transfers var bytesTransferred = transfers.Sum(t => t.BytesTransferred); + // if the batch record has a non-null state, it has ended and it is safe to use the + // stored value. otherwise we must compute it from the associated transfers + var state = batch.State ?? ( + transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State)) ? TransferStates.InProgress + : transfers.Any(t => TransferStateCategories.Queued.Contains(t.State)) ? TransferStates.Queued + : transfers.All(t => TransferStateCategories.Successful.Contains(t.State)) ? TransferStates.Completed | TransferStates.Succeeded + : transfers.Any(t => TransferStateCategories.Failed.Contains(t.State)) ? TransferStates.Completed | TransferStates.Errored + : TransferStates.None); + return batch with { Transfers = transfers, + State = state, BytesTransferred = bytesTransferred, BytesRemaining = transfers.Sum(t => t.BytesRemaining), PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, -- cgit v1.2.3 From b70f0ce9fcaf122ae25d19779ee3cd195e73e3d6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 29 Apr 2026 22:16:34 -0500 Subject: tweak queries --- src/slskd/Transfers/Batches/BatchService.cs | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index ac547d1e..daedbdc6 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -131,6 +131,7 @@ namespace slskd.Transfers var batch = await context.Batches .AsNoTracking() + .Include(b => b.Transfers) .Where(expression) .SingleOrDefaultAsync(); @@ -139,31 +140,21 @@ namespace slskd.Transfers return null; } - var transfers = await context.Transfers - .AsNoTracking() - .Where(t => t.BatchId == batch.Id) - .ToListAsync(); - - var bytesTransferred = transfers.Sum(t => t.BytesTransferred); - - // if the batch record has a non-null state, it has ended and it is safe to use the + // if the batch record State has a non-null state, it has ended and it is safe to use the // stored value. otherwise we must compute it from the associated transfers - var state = batch.State ?? ( - transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State)) ? TransferStates.InProgress - : transfers.Any(t => TransferStateCategories.Queued.Contains(t.State)) ? TransferStates.Queued - : transfers.All(t => TransferStateCategories.Successful.Contains(t.State)) ? TransferStates.Completed | TransferStates.Succeeded - : transfers.Any(t => TransferStateCategories.Failed.Contains(t.State)) ? TransferStates.Completed | TransferStates.Errored - : TransferStates.None); + var state = batch.State ?? Batch.DeriveState(batch.Transfers); + var endedAt = batch.EndedAt ?? batch.Transfers.Max(t => t.EndedAt); + + var bytesTransferred = batch.Transfers.Sum(t => t.BytesTransferred); return batch with { - Transfers = transfers, State = state, BytesTransferred = bytesTransferred, - BytesRemaining = transfers.Sum(t => t.BytesRemaining), + BytesRemaining = batch.Transfers.Sum(t => t.BytesRemaining), PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, - AverageSpeed = transfers.Average(t => t.AverageSpeed), - Removed = transfers.All(t => t.Removed), + AverageSpeed = batch.Transfers.Average(t => t.AverageSpeed), + Removed = batch.Transfers.All(t => t.Removed), }; } @@ -197,6 +188,7 @@ namespace slskd.Transfers .Select(g => new { BatchId = g.Key, + EndedAt = g.Max(t => t.EndedAt), BytesTransferred = g.Sum(t => t.BytesTransferred), BytesRemaining = g.Sum(t => t.BytesRemaining), AverageSpeed = g.Average(t => t.AverageSpeed), -- cgit v1.2.3 From ff430b438a6498c1f26e318d6d850de41a3634b4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 22:11:16 -0500 Subject: document Batch --- src/slskd/Transfers/Types/Batch.cs | 137 ++++++++++++++++++++----------------- 1 file changed, 73 insertions(+), 64 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 6b3cf15c..3fe692f2 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -35,89 +35,98 @@ namespace slskd.Transfers; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Text.Json.Serialization; using Soulseek; +/// +/// +/// 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. +/// +/// +/// 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 is complete, +/// but otherwise a Batch serves no functional purpose within the application. +/// +/// public record Batch { + /// + /// Gets the associated , if one was specified when the + /// Batch was enqueued. + /// public Guid? SearchId { get; init; } = null; + /// + /// Gets the unique identifier for the Batch. + /// [Key] public Guid Id { get; init; } - public string Username { get; init; } - public TransferDirection Direction { get; init; } = TransferDirection.Download; - public int Files { get; init; } - public long Size { get; init; } - public string Destination { get; init; } - public DateTime CreatedAt { get; init; } = DateTime.UtcNow; /// - /// Gets the current batch state. + /// Gets the username associated with the Batch. /// - /// - /// If the database value is null, value must be derived from the associated transfers. - /// - public TransferStates? State { get; set; } // todo: set when the last file is completed - - public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons + public string Username { get; init; } /// - /// The transfers associated with the batch. + /// Gets the Batch direction (Upload, Download). /// /// - /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. + /// We don't have, and likely will never be able to implement, upload batches, + /// nor are they of any particular use. /// - public ICollection Transfers { get; init; } - - [NotMapped] - public long BytesTransferred { get; init; } - - [NotMapped] - public long BytesRemaining { get; init; } - - [NotMapped] - public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; - - [NotMapped] - public double PercentComplete { get; init; } - - [NotMapped] - public double AverageSpeed { get; init; } - - [JsonIgnore] - public bool Removed { get; init; } + public TransferDirection Direction { get; init; } = TransferDirection.Download; - public static TransferStates DeriveState(IEnumerable transfers) - { - // if there's a transfer in progress, the batch is in progress - if (transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) - { - return TransferStates.InProgress; - } + /// + /// Gets the number of files included in the Batch. + /// + public int FileCount { get; init; } - // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), - // the batch is queued. it doesn't matter if one or more are errored, they might be retried - if (transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) - { - return TransferStates.Queued; - } + /// + /// Gets the sum of the included file's sizes. + /// + public long FileSize { get; init; } - // if all transfers completed successfully, the batch did too - if (transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) - { - return TransferStates.Completed | TransferStates.Succeeded; - } + /// + /// Gets the timestamp at which the Batch was created. + /// + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - // if one or more transfers failed and there are no more enqueued files, - // the batch errored and it will not recover on its own - if (transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) - { - return TransferStates.Completed | TransferStates.Errored; - } + /// + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. + /// + /// + /// If specified, takes precedence over other configured placement rules. + /// + public string DestinationDirectory { get; init; } - // unclear how we would get here - return TransferStates.None; - } + /// + /// Gets the Transfer records associated with the batch. + /// + /// + /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and + /// all of the (future?) statistics will be null. + /// + public ICollection Transfers { get; init; } = null; + + /* + 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. + + 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 -- cgit v1.2.3 From 3abaadcd87383c22bc380d6c2fd9b05e38e7d353 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:43:50 -0500 Subject: remove StartOffset from Transfers table (unused) --- ...Z2026_04_30_DropTransferStartOffsetMigration.cs | 101 +++++++++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 1 - src/slskd/Transfers/Types/Transfer.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs (limited to 'src/slskd/Transfers') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to drop the unused StartOffset column. +/// +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(); + 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/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0ccf52c3..aba6ca9d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -435,7 +435,6 @@ namespace slskd.Transfers.Downloads 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, }; diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 93a23380..90fbe612 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -30,7 +30,7 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // -namespace slskd.Transfers +namespace slskd.Transfers; { using System; using System.ComponentModel.DataAnnotations; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 13915e82..9bb09f66 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -622,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, }; -- cgit v1.2.3 From 4323178f7e795e26bc3906411c6403746f2f8bb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:44:03 -0500 Subject: straggling StartOffset --- src/slskd/Transfers/Extensions.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/slskd/Transfers') 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, -- cgit v1.2.3 From eba232fe9de343359b96ca4686c5414912d4b276 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:44:56 -0500 Subject: finalize batchservice --- src/slskd/Transfers/Batches/BatchService.cs | 79 ++--------------------------- src/slskd/Transfers/Types/Batch.cs | 18 +++---- 2 files changed, 12 insertions(+), 85 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index daedbdc6..aadaa820 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -39,7 +39,6 @@ namespace slskd.Transfers using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; - using Soulseek; /// /// Manages transfer batches. @@ -129,33 +128,11 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - var batch = await context.Batches + return await context.Batches .AsNoTracking() .Include(b => b.Transfers) .Where(expression) .SingleOrDefaultAsync(); - - if (batch is null) - { - return null; - } - - // if the batch record State has a non-null state, it has ended and it is safe to use the - // stored value. otherwise we must compute it from the associated transfers - var state = batch.State ?? Batch.DeriveState(batch.Transfers); - var endedAt = batch.EndedAt ?? batch.Transfers.Max(t => t.EndedAt); - - var bytesTransferred = batch.Transfers.Sum(t => t.BytesTransferred); - - return batch with - { - State = state, - BytesTransferred = bytesTransferred, - BytesRemaining = batch.Transfers.Sum(t => t.BytesRemaining), - PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, - AverageSpeed = batch.Transfers.Average(t => t.AverageSpeed), - Removed = batch.Transfers.All(t => t.Removed), - }; } /// @@ -169,61 +146,11 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - var batches = await context.Batches + return await context.Batches .AsNoTracking() + .Include(b => b.Transfers) .Where(expression) .ToListAsync(); - - if (batches.Count == 0) - { - return batches; - } - - var batchIds = batches.Select(b => b.Id).ToList(); - - var stats = (await context.Transfers - .AsNoTracking() - .Where(t => t.BatchId.HasValue && batchIds.Contains(t.BatchId.Value)) - .GroupBy(t => t.BatchId) - .Select(g => new - { - BatchId = g.Key, - EndedAt = g.Max(t => t.EndedAt), - BytesTransferred = g.Sum(t => t.BytesTransferred), - BytesRemaining = g.Sum(t => t.BytesRemaining), - AverageSpeed = g.Average(t => t.AverageSpeed), - Removed = g.All(t => t.Removed), - AnyInProgress = g.Any(t => TransferStateCategories.InProgress.Contains(t.State)), - AnyQueued = g.Any(t => TransferStateCategories.Queued.Contains(t.State)), - AllSuccessful = g.All(t => TransferStateCategories.Successful.Contains(t.State)), - AnyFailed = g.Any(t => TransferStateCategories.Failed.Contains(t.State)), - }) - .ToListAsync()) - .ToDictionary(s => s.BatchId); - - return batches.Select(b => - { - if (!stats.TryGetValue(b.Id, out var s)) - { - return b; - } - - var state = s.AnyInProgress ? TransferStates.InProgress - : s.AnyQueued ? TransferStates.Queued - : s.AllSuccessful ? TransferStates.Completed | TransferStates.Succeeded - : s.AnyFailed ? TransferStates.Completed | TransferStates.Errored - : TransferStates.None; - - return b with - { - BytesTransferred = s.BytesTransferred, - BytesRemaining = s.BytesRemaining, - PercentComplete = b.Size == 0 ? 0 : s.BytesTransferred / (double)b.Size, - AverageSpeed = s.AverageSpeed, - Removed = s.Removed, - State = state, - }; - }).ToList(); } /// diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 3fe692f2..ac7025fb 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -87,27 +87,27 @@ public record Batch public long FileSize { get; init; } /// - /// Gets the timestamp at which the Batch was created. + /// Gets the time at which the Batch was created. /// public DateTime CreatedAt { get; init; } = DateTime.UtcNow; /// - /// Gets the optional destination directory for the files in the Batch, relative to the configured - /// download directory. + /// Gets the Transfer records associated with the batch. /// /// - /// If specified, takes precedence over other configured placement rules. + /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and + /// all of the (future?) statistics will be null. /// - public string DestinationDirectory { get; init; } + public ICollection Transfers { get; init; } = null; /// - /// Gets the Transfer records associated with the batch. + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. /// /// - /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and - /// all of the (future?) statistics will be null. + /// If specified, takes precedence over other configured placement rules. /// - public ICollection Transfers { get; init; } = null; + public string DestinationDirectory { get; init; } /* future: [NotMapped] properties that aggregate values from the associated Transfer records. -- cgit v1.2.3 From e3f6063d841933c3dcc6b16674613458a95c8c6f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:45:02 -0500 Subject: fix up transfer --- src/slskd/Transfers/Types/Transfer.cs | 205 +++++++++++++++++++++++----------- 1 file changed, 139 insertions(+), 66 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 90fbe612..8d1afa25 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -31,71 +31,144 @@ // namespace slskd.Transfers; + +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using Soulseek; + +/// +/// A file Transfer between network peers. +/// +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; } - - /// - /// Gets the remote filename. - /// - public string Filename { get; init; } - public long Size { get; set; } - public long StartOffset { get; init; } - - public TransferStates State { get; set; } = TransferStates.None; - - /// - /// Gets the string representation of the transfer . - /// - /// - /// 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. - /// - public string StateDescription { get; set; } - public DateTime RequestedAt { get; set; } - public DateTime? EnqueuedAt { get; set; } - public DateTime? StartedAt { get; set; } - - /// - /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress. - /// - /// - /// Guaranteed to be set for transfers in a terminal state. - /// - 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); - } + /// + /// Gets the associated , if one was specified when the Transfer was created. + /// + public Guid? BatchId { get; init; } = null; + + /// + /// Gets the unique identifier for the Transfer. + /// + [Key] + public Guid Id { get; init; } + + /// + /// Gets the remote username associated with the Transfer. + /// + public string Username { get; init; } + + /// + /// Gets the Transfer direction (Upload, Download). + /// + public TransferDirection Direction { get; init; } + + /// + /// Gets the remote filename of the file. + /// + /// + /// Exactly as it appeared in the originating Search, Browse, or file directory contents response. + /// + public string Filename { get; init; } + + /// + /// Gets or sets the remote size of the file. + /// + public long Size { get; set; } + + /// + /// Gets or sets the state of the Transfer. + /// + public TransferStates State { get; set; } = TransferStates.None; + + /// + /// Gets or sets the string representation of the transfer . + /// + /// + /// 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. + /// + public string StateDescription { get; set; } + + /// + /// Gets or sets the time at which the Transfer was requested from the remote peer. + /// + public DateTime RequestedAt { get; set; } + + /// + /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued. + /// + /// + /// 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. + /// + public DateTime? EnqueuedAt { get; set; } + + /// + /// 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. + /// + public DateTime? StartedAt { get; set; } + + /// + /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress. + /// + /// + /// Guaranteed to be set for transfers in a terminal state. + /// + public DateTime? EndedAt { get; set; } + + /// + /// Gets or sets the number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets or sets the average speed of the Transfer over the duration. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets or sets the current place in line in the remote peer's queue, if place has been requested. + /// + /// + /// May be wildly innacurate to the point of uselessness. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did. + /// + public string Exception { get; set; } + + /// + /// Gets or sets the number of attempts. Incremented each time the Transfer is retried. + /// + /// + /// Applicable to downloads only. + /// + public int Attempts { get; set; } = 0; + + /// + /// Gets or sets the time at which the next retry attempt will be made, if applicable. + /// + public DateTime? NextAttemptAt { get; set; } = null; + + /// + /// Gets or sets a value indicating whether the Transfer has been removed from the UI. + /// + [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); } \ No newline at end of file -- cgit v1.2.3 From c935b990b7979491b03d7b5d861d75a67ad6f3f9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:02:25 -0500 Subject: remove file counts and size --- src/slskd/Transfers/Types/Batch.cs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index ac7025fb..3da583f3 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -76,16 +76,6 @@ public record Batch /// public TransferDirection Direction { get; init; } = TransferDirection.Download; - /// - /// Gets the number of files included in the Batch. - /// - public int FileCount { get; init; } - - /// - /// Gets the sum of the included file's sizes. - /// - public long FileSize { get; init; } - /// /// Gets the time at which the Batch was created. /// @@ -115,6 +105,10 @@ public record Batch 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 -- cgit v1.2.3 From 08380a1a150f58839798ca3289aa8b5542f41086 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:37:00 -0500 Subject: shuffle some things around --- src/slskd/Program.cs | 1 + src/slskd/Transfers/Batches/BatchService.cs | 179 ----------------------- src/slskd/Transfers/Downloads/BatchService.cs | 122 +++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++ 4 files changed, 135 insertions(+), 179 deletions(-) delete mode 100644 src/slskd/Transfers/Batches/BatchService.cs create mode 100644 src/slskd/Transfers/Downloads/BatchService.cs (limited to 'src/slskd/Transfers') 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(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs deleted file mode 100644 index aadaa820..00000000 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ /dev/null @@ -1,179 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Linq.Expressions; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Serilog; - - /// - /// Manages transfer batches. - /// - public interface IBatchService - { - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - Batch Create(Batch batch); - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - Task FindAsync(Expression> expression); - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - Task> ListAsync(Expression> expression = null); - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - void Remove(Guid id); - } - - /// - /// Manages transfer batches. - /// - public class BatchService : IBatchService - { - /// - /// Initializes a new instance of the class. - /// - /// The database context factory to use. - public BatchService(IDbContextFactory contextFactory) - { - ContextFactory = contextFactory; - } - - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - public Batch Create(Batch batch) - { - if (batch == default) - { - throw new ArgumentNullException(nameof(batch)); - } - - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - context.SaveChanges(); - - Log.Debug("Created batch {Id}", batch.Id); - - return batch; - } - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - public async Task FindAsync(Expression> 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(); - } - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - public async Task> ListAsync(Expression> expression = null) - { - expression ??= b => true; - - using var context = ContextFactory.CreateDbContext(); - - return await context.Batches - .AsNoTracking() - .Include(b => b.Transfers) - .Where(expression) - .ToListAsync(); - } - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - public void Remove(Guid id) - { - using var context = ContextFactory.CreateDbContext(); - - var exists = context.Batches.Any(b => b.Id == id); - - if (!exists) - { - throw new NotFoundException($"No batch with id {id}"); - } - - context.Transfers - .Where(t => t.BatchId == id) - .ExecuteUpdate(s => s.SetProperty(t => t.Removed, true)); - - Log.Debug("Marked transfers for batch {Id} as removed", id); - } - } -} diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs new file mode 100644 index 00000000..7a4ba055 --- /dev/null +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -0,0 +1,122 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers.Downloads; + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// +/// Manages transfer batches. +/// +public interface IBatchService +{ + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + Batch Create(Batch batch); + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + Task FindAsync(Expression> expression); +} + +/// +/// Manages transfer batches. +/// +public class BatchService : IBatchService +{ + /// + /// Initializes a new instance of the class. + /// + /// The database context factory to use. + public BatchService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + public Batch Create(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Batches.Add(batch); + context.SaveChanges(); + + Log.Debug("Created batch {Id}", batch.Id); + + return batch; + } + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + public async Task FindAsync(Expression> 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 aba6ca9d..9e898570 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -55,6 +55,11 @@ namespace slskd.Transfers.Downloads /// public interface IDownloadService { + /// + /// Gets download batch service. + /// + IBatchService Batches { get; } + /// /// Adds the specified . Supersedes any existing record for the same file and username. /// @@ -158,6 +163,7 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( + IBatchService batchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory, @@ -166,6 +172,7 @@ namespace slskd.Transfers.Downloads IFTPService ftpClient, EventBus eventBus) { + Batches = batchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -177,6 +184,11 @@ namespace slskd.Transfers.Downloads Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } + /// + /// Gets download batch service. + /// + public IBatchService Batches { get; } + /// /// These tokens give users the ability to cancel transfers via the UI (or API). /// -- cgit v1.2.3 From d45e33185daf1e0320ce60e3c324dbf3efae49ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:44:16 -0500 Subject: rough in options json support --- src/slskd/Transfers/TransfersDbContext.cs | 9 ++++++ src/slskd/Transfers/Types/Batch.cs | 8 ++---- src/slskd/Transfers/Types/BatchOptions.cs | 48 +++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 src/slskd/Transfers/Types/BatchOptions.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index ce2d9f52..699eed6c 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; @@ -135,6 +136,14 @@ namespace slskd.Transfers .WithOne() .HasForeignKey(t => t.BatchId) .IsRequired(false); + + modelBuilder + .Entity() + .Property(b => b.Options) + .HasConversion( + convertToProviderExpression: v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default), + convertFromProviderExpression: v => JsonSerializer.Deserialize(v, JsonSerializerOptions.Default)) + .HasColumnType("TEXT"); } } } diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 3da583f3..d4234e30 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -91,13 +91,9 @@ public record Batch public ICollection Transfers { get; init; } = null; /// - /// Gets the optional destination directory for the files in the Batch, relative to the configured - /// download directory. + /// Gets the options for the batch. /// - /// - /// If specified, takes precedence over other configured placement rules. - /// - public string DestinationDirectory { get; init; } + public BatchOptions Options { get; init; } /* future: [NotMapped] properties that aggregate values from the associated Transfer records. 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Options for es. +/// +public record BatchOptions +{ + /// + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. + /// + /// + /// If specified, takes precedence over other configured placement rules. + /// + public string Destination { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 3371921f4897dbff370c91b3171df4f953bfe21f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:44:35 -0500 Subject: move destination to options --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index ce3331ca..28cc7859 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -45,6 +45,7 @@ public record EnqueueDownloadBatchRequest [StringLength(500, MinimumLength = 1)] public string Username { get; init; } public List Files { get; init; } = []; + public EnqueueDownloadBatchOptions Options { get; init; } = new(); } public record EnqueueDownloadBatchItem @@ -54,4 +55,9 @@ public record EnqueueDownloadBatchItem [Range(0, int.MaxValue)] public long Size { get; set; } +} + +public record EnqueueDownloadBatchOptions +{ + public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 6585216de3a191b3260c1960f4a0f29daab6b04a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:14 -0500 Subject: populate batchid if supplied --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9e898570..184acb5d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -76,12 +76,13 @@ namespace slskd.Transfers.Downloads /// /// The username of remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); + Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -261,12 +262,13 @@ namespace slskd.Transfers.Downloads /// /// The username of the remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -443,6 +445,7 @@ 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 -- cgit v1.2.3 From 89b6bdc087db0fc442492fcc52d0ca7d68e415aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:24 -0500 Subject: rough in batch endpoints --- .../API/Controllers/TransfersController.cs | 173 +++++++++++++-------- 1 file changed, 112 insertions(+), 61 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 9f2fba6d..2e42c6cf 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,68 +216,8 @@ namespace slskd.Transfers.API } } - // [HttpPost("downloads")] - // [Authorize(Policy = AuthPolicy.Any)] - // [ProducesResponseType(201)] - // [ProducesResponseType(typeof(string), 403)] - // [ProducesResponseType(typeof(string), 500)] - // public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) - // { - // if (Program.IsRelayAgent) - // { - // return Forbid(); - // } - - // // todo, check: username null or whitespace - // if (!ModelState.IsValid) - // { - // return BadRequest(ModelState.GetReadableString()); - // } - - // if ((request.Files?.Count ?? 0) == 0) - // { - // return BadRequest("At least one file is required"); - // } - - // // todo, check: - // // * filename null or whitespace - // // * size -1 - // if (request.Files.Any(r => r is null)) - // { - // return BadRequest("One or more files in the request are invalid"); - // } - - // 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"); - // } - - // var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); - - // return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); - // } - // catch (Exception ex) - // { - // Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); - // return StatusCode(500, ex.Message); - // } - // finally - // { - // DownloadRequestLimiter.Release(); - // } - // } - /// - /// Enqueues the specified download. + /// (Obsolete) Enqueues the specified download. /// /// The username of the download source. /// The list of download requests. @@ -285,6 +225,7 @@ namespace slskd.Transfers.API /// The download was successfully enqueued. /// The download was rejected. /// An unexpected error was encountered. + [Obsolete("Will be phased out in future versions; use batches")] [HttpPost("downloads/{username}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] @@ -341,6 +282,75 @@ namespace slskd.Transfers.API } } + [HttpPost("downloads/batches")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetReadableString()); + } + + if ((request.Files?.Count ?? 0) == 0) + { + return BadRequest("At least one file is required"); + } + + if (request.Files.Any( + r => r is null + || string.IsNullOrWhiteSpace(r.Filename) + || r.Size < 0)) + { + return BadRequest("One or more files in the request are invalid"); + } + + 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"); + } + + // todo: finish this + // await Transfers.Downloads.Batches.Create(new() + // { + // Id = request.BatchId, + // SearchId = request.SearchId, + // Options = request.Options, + // }); + + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, request.Files.Select(r => (r.Filename, r.Size))); + + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.BatchId); + + return StatusCode(201, batch); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count(), request.Username, ex.Message); + return StatusCode(500, ex.Message); + } + finally + { + DownloadRequestLimiter.Release(); + } + } + /// /// Gets all downloads. /// @@ -372,6 +382,47 @@ namespace slskd.Transfers.API return Ok(response); } + /// + /// Gets the specified batch and associated transfers. + /// + /// The id of the batch. + /// + /// The specified id is not valid. + /// The request completed successfully. + /// The specified batch was not found. + [HttpGet("downloads/batches/{id}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(200)] + public async Task Get([FromRoute, Required] string id) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + 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); + } + } + /// /// Gets all downloads for the specified username. /// -- cgit v1.2.3 From 8508606e16aa5ed00ca9d3e19d85e576e383aa63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 22:21:00 -0500 Subject: use standard json options --- src/slskd/Transfers/TransfersDbContext.cs | 4 ++-- src/slskd/Transfers/Types/Batch.cs | 6 +----- 2 files changed, 3 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 699eed6c..912c1ada 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -141,8 +141,8 @@ namespace slskd.Transfers .Entity() .Property(b => b.Options) .HasConversion( - convertToProviderExpression: v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default), - convertFromProviderExpression: v => JsonSerializer.Deserialize(v, JsonSerializerOptions.Default)) + convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()), + convertFromProviderExpression: v => JsonSerializer.Deserialize(v, new JsonSerializerOptions().WithStandardOptions())) .HasColumnType("TEXT"); } } diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index d4234e30..a0d71bef 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -44,7 +44,7 @@ using Soulseek; /// /// /// 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 is complete, +/// 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. /// /// @@ -84,10 +84,6 @@ public record Batch /// /// Gets the Transfer records associated with the batch. /// - /// - /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and - /// all of the (future?) statistics will be null. - /// public ICollection Transfers { get; init; } = null; /// -- cgit v1.2.3 From 16aeb34e118ee2d4770bcace3aa06a7615a2eae6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:44 -0500 Subject: tweak dto --- .../API/DTO/EnqueueDownloadBatchRequest.cs | 63 --------------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 93 ++++++++++++++++++++++ 2 files changed, 93 insertions(+), 63 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs deleted file mode 100644 index 28cc7859..00000000 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace slskd.Transfers.API; - -public record EnqueueDownloadBatchRequest -{ - public Guid? BatchId { get; init; } - public Guid? SearchId { get; init; } - - [Required] - [StringLength(500, MinimumLength = 1)] - public string Username { get; init; } - public List Files { get; init; } = []; - public EnqueueDownloadBatchOptions Options { get; init; } = new(); -} - -public record EnqueueDownloadBatchItem -{ - [Required] - public string Filename { get; set; } - - [Range(0, int.MaxValue)] - public long Size { get; set; } -} - -public record EnqueueDownloadBatchOptions -{ - public string Destination { get; init; } -} \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs new file mode 100644 index 00000000..0aaf1034 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -0,0 +1,93 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace slskd.Transfers.API; + +public record QueueDownloadBatchRequest +{ + /// + /// The ID of the Batch. + /// + /// + /// If not supplied, one will be randomly generated. + /// + public Guid? Id { get; init; } = Guid.NewGuid(); + + /// + /// The ID of the associated Search, if applicable. + /// + public Guid? SearchId { get; init; } + + /// + /// The username of the user from which to download. + /// + [Required] + [StringLength(500, MinimumLength = 1)] + public string Username { get; init; } + + /// + /// The list of files to download. + /// + public List Files { get; init; } = []; + + /// + /// Options for the Batch. + /// + public EnqueueDownloadBatchOptions Options { get; init; } = new(); +} + +public record EnqueueDownloadBatchItem +{ + /// + /// The name of the file. + /// + [Required] + public string Filename { get; set; } + + /// + /// The file size. + /// + [Range(0, int.MaxValue)] + public long Size { get; set; } +} + +public record EnqueueDownloadBatchOptions +{ + /// + /// The destination directory for the files, relative to the configured download directory. + /// + public string Destination { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 7e61670105fdb1efd164b2d89194a1699a9943db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:53 -0500 Subject: make create async --- src/slskd/Transfers/Downloads/BatchService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 7a4ba055..29de8e14 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -49,7 +49,7 @@ public interface IBatchService /// /// The batch to create. /// The created batch. - Batch Create(Batch batch); + Task CreateAsync(Batch batch); /// /// Finds a single batch matching the specified . @@ -82,7 +82,7 @@ public class BatchService : IBatchService /// /// The batch to create. /// The created batch. - public Batch Create(Batch batch) + public async Task CreateAsync(Batch batch) { if (batch == default) { @@ -91,7 +91,7 @@ public class BatchService : IBatchService using var context = ContextFactory.CreateDbContext(); context.Batches.Add(batch); - context.SaveChanges(); + await context.SaveChangesAsync(); Log.Debug("Created batch {Id}", batch.Id); -- cgit v1.2.3 From 22cc518863f5f2f0169e5fcbd83a91ebda15a5ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:14:03 -0500 Subject: finish endpoint --- .../API/Controllers/TransfersController.cs | 44 ++++++++++++++++------ 1 file changed, 33 insertions(+), 11 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 2e42c6cf..44f7a146 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -282,12 +282,13 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads/batches")] + [HttpPost("downloads")] [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(200)] [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { if (Program.IsRelayAgent) { @@ -326,17 +327,38 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } - // todo: finish this - // await Transfers.Downloads.Batches.Create(new() - // { - // Id = request.BatchId, - // SearchId = request.SearchId, - // Options = request.Options, - // }); + var batchId = request.Id ?? Guid.NewGuid(); - var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, request.Files.Select(r => (r.Filename, r.Size))); + await Transfers.Downloads.Batches.CreateAsync(new() + { + Id = batchId, + SearchId = request.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' + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync( + username: request.Username, + files: request.Files.Select(r => (r.Filename, r.Size)), + batchId: batchId); + + if (failed.Count > 0) + { + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already in progress", failed.Count, request.Files.Count); + } - var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.BatchId); + // the returned batch will have whatever Transfers were successfully inserted attached + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.Id); + + if (batch.Transfers.Count == 0) + { + return Ok(batch); + } return StatusCode(201, batch); } -- cgit v1.2.3 From eec45b7ddaa7fb33cc3831af4d4c849a5c39ca40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:28:01 -0500 Subject: size is a long, not an int --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 0aaf1034..21a77e83 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -80,7 +80,7 @@ public record EnqueueDownloadBatchItem /// /// The file size. /// - [Range(0, int.MaxValue)] + [Range(0, long.MaxValue)] public long Size { get; set; } } -- cgit v1.2.3 From 666bdeaea28e2f3a5fdea9d2404a8aa6ffc076da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:25:28 -0500 Subject: add cascade deletes for batches, add index on SearchId --- src/slskd/Transfers/TransfersDbContext.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 912c1ada..13d0984d 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -135,7 +135,8 @@ namespace slskd.Transfers .HasMany(b => b.Transfers) .WithOne() .HasForeignKey(t => t.BatchId) - .IsRequired(false); + .IsRequired(false) + .OnDelete(DeleteBehavior.Cascade); modelBuilder .Entity() @@ -144,6 +145,11 @@ namespace slskd.Transfers convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()), convertFromProviderExpression: v => JsonSerializer.Deserialize(v, new JsonSerializerOptions().WithStandardOptions())) .HasColumnType("TEXT"); + + modelBuilder + .Entity() + .HasIndex(b => b.SearchId) + .HasDatabaseName("IDX_Batches_SearchId"); } } } -- cgit v1.2.3 From 3afb1123087a03e15c23a75602b8f91094964e79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:15:49 -0500 Subject: destination must be relative (to the configured download directory) --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 21a77e83..4a1d32f1 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -33,6 +33,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using slskd.Validation; namespace slskd.Transfers.API; @@ -89,5 +90,6 @@ public record EnqueueDownloadBatchOptions /// /// The destination directory for the files, relative to the configured download directory. /// + [RelativePath] public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From a61917f50b3874640b1bcd3c536a5ca4f38f10e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:16:19 -0500 Subject: handle conflicts/PK violations, validate more properties --- .../API/Controllers/TransfersController.cs | 9 +++++-- src/slskd/Transfers/Downloads/BatchService.cs | 28 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 44f7a146..b1275c52 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -282,7 +282,7 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads")] + [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] @@ -362,9 +362,14 @@ namespace slskd.Transfers.API return StatusCode(201, batch); } + 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(); + } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count(), request.Username, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); return StatusCode(500, ex.Message); } finally diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 29de8e14..7ea9a70a 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -36,6 +36,7 @@ using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Serilog; @@ -89,13 +90,30 @@ public class BatchService : IBatchService throw new ArgumentNullException(nameof(batch)); } - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - await context.SaveChangesAsync(); + 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); - Log.Debug("Created batch {Id}", batch.Id); + await context.SaveChangesAsync(); - return batch; + 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; + } } /// -- cgit v1.2.3 From f70c670e1dfbc6e6642365f57ba138501a8826fa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:33:24 -0500 Subject: parse guids from strings --- .../API/Controllers/TransfersController.cs | 23 +++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index b1275c52..50ff7199 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -313,6 +313,21 @@ namespace slskd.Transfers.API return BadRequest("One or more files in the request are invalid"); } + Guid? batchId; + Guid? searchId; + + // validation rules should prevent any problems here, but we have a backstop just in case + 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/UUIDv4"); + } + if (!DownloadRequestLimiter.Wait(0)) { return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); @@ -327,12 +342,10 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } - var batchId = request.Id ?? Guid.NewGuid(); - await Transfers.Downloads.Batches.CreateAsync(new() { - Id = batchId, - SearchId = request.SearchId, + Id = batchId ?? Guid.NewGuid(), + SearchId = searchId, Username = request.Username, Options = new() { @@ -353,7 +366,7 @@ namespace slskd.Transfers.API } // the returned batch will have whatever Transfers were successfully inserted attached - var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.Id); + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); if (batch.Transfers.Count == 0) { -- cgit v1.2.3 From b3041a9daffa98a0acda701e5e6b26345a185bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:41:23 -0500 Subject: add validation and tests for batch request DTO --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 212 +++++++++++++++++++++ 2 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 4a1d32f1..6d08f8f3 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -45,12 +45,14 @@ public record QueueDownloadBatchRequest /// /// If not supplied, one will be randomly generated. /// - public Guid? Id { get; init; } = Guid.NewGuid(); + [Guid] + public string Id { get; init; } /// /// The ID of the associated Search, if applicable. /// - public Guid? SearchId { get; init; } + [Guid] + public string SearchId { get; init; } /// /// The username of the user from which to download. @@ -76,6 +78,7 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] + [StringLength(int.MaxValue, MinimumLength = 1)] public string Filename { get; set; } /// 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..3863c649 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -0,0 +1,212 @@ +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 Results) Validate(object obj) + { + var results = new List(); + var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true); + return (isValid, results); + } + + private static QueueDownloadBatchRequest ValidRequest() => new() + { + Username = "testuser", + }; + + public class Id_Field + { + private static (bool IsValid, List 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, _) = Validate(ValidRequest() with { Id = value }); + Assert.False(isValid); + } + + [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 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, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.False(isValid); + } + + [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 Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = null }); + Assert.False(isValid); + } + + [Fact] + public void Empty_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + Assert.False(isValid); + } + + [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, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + } + } + + public class Files_Item + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void NullFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void EmptyFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + Assert.False(isValid); + } + + [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, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + Assert.False(isValid); + } + + [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); + } + } + + public class Options_Destination + { + private static (bool IsValid, List 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")] + [InlineData("/music")] + [InlineData("\\\\server\\share")] + public void AbsolutePath_Fails(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + } + } +} -- cgit v1.2.3 From c86fbec378b42dbd5ae6133c8ac706669f5709bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:59:32 -0500 Subject: require at least 1 file --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 + .../API/DTO/QueueDownloadBatchRequestTests.cs | 61 ++++++++++++++++++---- 2 files changed, 54 insertions(+), 9 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 6d08f8f3..823a4e40 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -64,6 +64,8 @@ public record QueueDownloadBatchRequest /// /// The list of files to download. /// + [Required] + [MinLength(1)] public List Files { get; init; } = []; /// diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 3863c649..1f12d787 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -17,6 +17,7 @@ public class QueueDownloadBatchRequestTests private static QueueDownloadBatchRequest ValidRequest() => new() { Username = "testuser", + Files = [new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }], }; public class Id_Field @@ -38,8 +39,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { Id = 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/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -72,8 +75,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { SearchId = 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/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -95,15 +100,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void Omitted_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = null }); + var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] public void Empty_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] @@ -123,8 +132,34 @@ public class QueueDownloadBatchRequestTests [Fact] public void FiveHundredOneChars_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + } + } + + public class Files_Field + { + private static (bool IsValid, List 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); } } @@ -136,15 +171,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void NullFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Filename field is required.", results[0].ErrorMessage); } [Fact] public void EmptyFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -157,8 +196,10 @@ public class QueueDownloadBatchRequestTests [Fact] public void NegativeSize_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + 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] @@ -205,8 +246,10 @@ public class QueueDownloadBatchRequestTests [InlineData("\\\\server\\share")] public void AbsolutePath_Fails(string value) { - var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = 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); } } } -- cgit v1.2.3 From 3fb834ecb2afb7c112e191d03b20f7ae39f7a62e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:20 -0500 Subject: use CombineSafely --- src/slskd/Common/CommonExtensions.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 33e59382..5ff3e519 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -393,7 +393,7 @@ namespace slskd [Obsolete("Find something more intelligent to do instead of this")] public static string ToLocalFilename(this string remoteFilename, string baseDirectory) { - return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); + return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); } /// @@ -467,7 +467,7 @@ namespace slskd var file = parts.Last().ReplaceInvalidFileNameCharacters(); var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - return Path.Combine(directory, file); + return FileSafety.CombineSafely(directory, file); } /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 184acb5d..7d9d9521 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1046,10 +1046,11 @@ namespace slskd.Transfers.Downloads // 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) + // if there is no batch id, sanitize the username and use that var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: System.IO.Path.Combine( + baseDirectory: FileSafety.CombineSafely( OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1144,7 +1145,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 { -- cgit v1.2.3 From 7cd70a730b6cd57952f2e233378cd6bb244f56b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:35 -0500 Subject: block downloads of files with traversal segments --- .../Transfers/API/Controllers/TransfersController.cs | 17 ++++++++++++++++- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 50ff7199..1d748f35 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -250,7 +250,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)) @@ -313,6 +318,16 @@ namespace slskd.Transfers.API return BadRequest("One or more files in the request are invalid"); } + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + { + return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + } + + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + { + return BadRequest("One or more files in the request are duplicates"); + } + Guid? batchId; Guid? searchId; diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 7d9d9521..14048fac 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -287,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)); -- cgit v1.2.3 From d4c06cba98911c1fdad4ba65a6450180c0df9684 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 19:03:04 -0500 Subject: tweaks --- src/slskd/Common/Validation/GuidAttribute.cs | 2 +- .../Z2026_05_06_AddBatchesTableMigration.cs | 2 +- .../API/Controllers/TransfersController.cs | 41 +++++++++++++++------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 +-- 4 files changed, 32 insertions(+), 17 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 9139ffef..5728b8f6 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -51,7 +51,7 @@ namespace slskd.Validation return ValidationResult.Success; } - return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUIDv4"); + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID"); } } } diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index be56bfed..9b373f71 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -46,7 +46,7 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration ConnectionString = connectionStrings[Database.Transfers]; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); private string ConnectionString { get; } public bool NeedsToBeApplied() diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 1d748f35..4fcb8d5a 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -287,11 +287,22 @@ namespace slskd.Transfers.API } } + /// + /// Enqueues a batch of downloads. + /// + /// The batch details. + /// + /// One or more downloads were successfully enqueued. + /// The request succeeded, but all downloads were already enqueued. + /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 409)] + [ProducesResponseType(typeof(string), 429)] [ProducesResponseType(typeof(string), 500)] public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { @@ -310,22 +321,22 @@ namespace slskd.Transfers.API return BadRequest("At least one file is required"); } - if (request.Files.Any( - r => r is null - || string.IsNullOrWhiteSpace(r.Filename) - || r.Size < 0)) + if (request.Files.Any(r => r is null)) { - return BadRequest("One or more files in the request are invalid"); + return BadRequest("One or more files in the request are null"); } - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) { - return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + return BadRequest("Two or more files in the request are repeated"); } - if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + // a user would have to deliberately fake this, as no OS and no client are capable of scanning + // such a file into configured shares + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) { - return BadRequest("One or more files in the request are duplicates"); + Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); + return BadRequest("One or more files in the request contain an unsafe path traversal segment"); } Guid? batchId; @@ -343,6 +354,8 @@ namespace slskd.Transfers.API return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); } + batchId ??= Guid.NewGuid(); + if (!DownloadRequestLimiter.Wait(0)) { return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); @@ -357,9 +370,10 @@ namespace slskd.Transfers.API 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 ?? Guid.NewGuid(), + Id = batchId.Value, SearchId = searchId, Username = request.Username, Options = new() @@ -377,12 +391,13 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); } - // the returned batch will have whatever Transfers were successfully inserted attached + // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); + // all of the files were already queued; list of transfers should be empty if (batch.Transfers.Count == 0) { return Ok(batch); @@ -393,7 +408,7 @@ namespace slskd.Transfers.API 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(); + return Conflict($"A batch with ID {batchId} already exists"); } catch (Exception ex) { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 823a4e40..fe539ce7 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -81,13 +81,13 @@ public record EnqueueDownloadBatchItem /// [Required] [StringLength(int.MaxValue, MinimumLength = 1)] - public string Filename { get; set; } + public string Filename { get; init; } /// /// The file size. /// [Range(0, long.MaxValue)] - public long Size { get; set; } + public long Size { get; init; } } public record EnqueueDownloadBatchOptions -- cgit v1.2.3 From c2055a762d3d5df2ac26845ca7a45a292cc6b6e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 22:04:37 -0500 Subject: fix tests --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 2 +- tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs | 6 +++--- .../Transfers/API/DTO/QueueDownloadBatchRequestTests.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 4fcb8d5a..ee3dfe2d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -351,7 +351,7 @@ namespace slskd.Transfers.API 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/UUIDv4"); + return BadRequest("One or more provided identifiers is not a valid GUID/UUID"); } batchId ??= Guid.NewGuid(); diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index 85522c18..e574c130 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -46,7 +46,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(string.Empty); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Theory] @@ -60,7 +60,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(value); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Fact] @@ -68,7 +68,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(42); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } } diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 9fa4d304..019e8cd5 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -42,7 +42,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Id = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Id field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The Id field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] @@ -78,7 +78,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { SearchId = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The SearchId field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The SearchId field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] -- cgit v1.2.3 From 8dc86c07d7e3c0ad82ad8e1c1c64b26a460774ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:14 -0500 Subject: tweak validation on batch request --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +++- .../API/DTO/QueueDownloadBatchRequestTests.cs | 47 ++++++++++++++++++---- 2 files changed, 45 insertions(+), 9 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index fe539ce7..05a913bd 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -58,7 +58,8 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [StringLength(500, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [StringLength(maximumLength: 500)] public string Username { get; init; } /// @@ -80,7 +81,8 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] - [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [NonTraversingPath] public string Filename { get; init; } /// @@ -96,5 +98,6 @@ public record EnqueueDownloadBatchOptions /// The destination directory for the files, relative to the configured download directory. /// [RelativePath] + [NonTraversingPath] public string Destination { get; init; } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 019e8cd5..2440291c 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -102,8 +102,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -111,8 +110,15 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + 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] @@ -173,8 +179,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Filename field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -182,7 +187,14 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); - Assert.Single(results); + 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."); } @@ -215,6 +227,27 @@ public class QueueDownloadBatchRequestTests 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 -- cgit v1.2.3 From b59d4b6b9b497c9c9c767e11da2af30dfd41983a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:22 -0500 Subject: add response --- .../API/DTO/QueueDownloadBatchResponse.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs new file mode 100644 index 00000000..8e134c29 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -0,0 +1,41 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System.Collections.Generic; + +namespace slskd.Transfers.API; + +public record QueueDownloadBatchResponse +{ + public Batch Batch { get; init; } + public Dictionary Failures { get; init; } = []; +} -- cgit v1.2.3 From d8bebbbe1ead96b99246c88816f846747eed5bb7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:42 -0500 Subject: return a message when failing a file --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 14048fac..89b8a6a7 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -82,7 +82,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); + Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -268,7 +268,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) + public async Task<(List 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)) { @@ -325,7 +325,7 @@ namespace slskd.Transfers.Downloads } List enqueued = []; - List failed = []; + List<(string Filename, string Message)> failed = []; SemaphoreSlim userSemaphore; Task userSemaphoreWaitTask; @@ -423,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; } @@ -435,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; } @@ -626,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)) { -- cgit v1.2.3 From 147aad8cca088734587c144434044a02d9ec7a96 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 17:40:44 -0500 Subject: tweak endpoint, docs, annotation. obsolete StateDescription to avoid usage --- .../Z2025_04_01_TransferStateMigration.cs | 3 + .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 13 +- src/slskd/Transfers/API/DTO/Transfer.cs | 169 --------------------- src/slskd/Transfers/TransfersDbContext.cs | 6 + src/slskd/Transfers/Types/Transfer.cs | 3 +- 5 files changed, 23 insertions(+), 171 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs (limited to 'src/slskd/Transfers') 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/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 05a913bd..77f7e7a9 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -37,6 +37,9 @@ using slskd.Validation; namespace slskd.Transfers.API; +/// +/// Enqueue a batch of downloads. +/// public record QueueDownloadBatchRequest { /// @@ -75,6 +78,9 @@ public record QueueDownloadBatchRequest public EnqueueDownloadBatchOptions Options { get; init; } = new(); } +/// +/// An item in a download batch. +/// public record EnqueueDownloadBatchItem { /// @@ -88,10 +94,14 @@ public record EnqueueDownloadBatchItem /// /// The file size. /// + [Required] [Range(0, long.MaxValue)] - public long Size { get; init; } + public long? Size { get; init; } } +/// +/// Download batch options. +/// public record EnqueueDownloadBatchOptions { /// @@ -99,5 +109,6 @@ public record EnqueueDownloadBatchOptions /// [RelativePath] [NonTraversingPath] + [MinLength(1)] public string Destination { get; init; } } \ No newline at end of file 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 (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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers.API -{ - using System; - using System.Net; - using Soulseek; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Compute.Sha1Hash(Filename); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - public string Username { get; set; } - - /// - /// Gets the Exception that caused the failure of the transfer, if applicable. - /// - 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/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 13d0984d..b25e7663 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -50,11 +50,17 @@ namespace slskd.Transfers 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()) { 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 } } diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 8d1afa25..d33a5efc 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -90,6 +90,8 @@ public class Transfer /// and especially **DO NOT** set the value. The getter and setter can't be protected because /// EF Core needs them to be public. /// + [Obsolete("Use State isntead; this is a hack for EF")] + [JsonIgnore] public string StateDescription { get; set; } /// @@ -160,7 +162,6 @@ public class Transfer /// /// Gets or sets a value indicating whether the Transfer has been removed from the UI. /// - [JsonIgnore] public bool Removed { get; set; } [NotMapped] -- cgit v1.2.3 From 21167d26a62add9ba54c50faa9b93970a478d27b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:53:38 -0500 Subject: failures as objects to avoid dictionary keys containing crap --- src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs index 8e134c29..84b570bc 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -37,5 +37,11 @@ namespace slskd.Transfers.API; public record QueueDownloadBatchResponse { public Batch Batch { get; init; } - public Dictionary Failures { get; init; } = []; + public IReadOnlyCollection Failures { get; init; } = []; +} + +public record QueueDownloadBatchResponseFailure +{ + public string Filename { get; init; } + public string Message { get; init; } } -- cgit v1.2.3 From aee67635e0c1048b890bc98812678086407d3b92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:54:15 -0500 Subject: readonly fils, validatie destination --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 77f7e7a9..53f5290f 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -70,7 +70,7 @@ public record QueueDownloadBatchRequest /// [Required] [MinLength(1)] - public List Files { get; init; } = []; + public IReadOnlyCollection Files { get; init; } = []; /// /// Options for the Batch. @@ -109,6 +109,6 @@ public record EnqueueDownloadBatchOptions /// [RelativePath] [NonTraversingPath] - [MinLength(1)] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 5d16f6f9cccf72c29b8bbf206c851005e3375d79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 19:02:40 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 84 +++++++++++++--------- 1 file changed, 50 insertions(+), 34 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ee3dfe2d..01dd61bd 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; @@ -292,18 +293,24 @@ namespace slskd.Transfers.API /// /// The batch details. /// - /// One or more downloads were successfully enqueued. - /// The request succeeded, but all downloads were already enqueued. + /// All downloads were successfully enqueued. + /// The request succeeded, but all downloads failed to be enqueued. + /// Some downloads were successfully enqueued, while some failed. + /// Bad request. + /// The request was forbidden. + /// A batch with the same ID already exists. + /// Request throttled. /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(200)] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 400)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 409)] - [ProducesResponseType(typeof(string), 429)] - [ProducesResponseType(typeof(string), 500)] + [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 EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { if (Program.IsRelayAgent) @@ -316,11 +323,6 @@ namespace slskd.Transfers.API return BadRequest(ModelState.GetReadableString()); } - if ((request.Files?.Count ?? 0) == 0) - { - return BadRequest("At least one file is required"); - } - if (request.Files.Any(r => r is null)) { return BadRequest("One or more files in the request are null"); @@ -331,18 +333,9 @@ namespace slskd.Transfers.API return BadRequest("Two or more files in the request are repeated"); } - // a user would have to deliberately fake this, as no OS and no client are capable of scanning - // such a file into configured shares - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) - { - Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); - return BadRequest("One or more files in the request contain an unsafe path traversal segment"); - } - Guid? batchId; Guid? searchId; - // validation rules should prevent any problems here, but we have a backstop just in case try { batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id); @@ -383,27 +376,50 @@ namespace slskd.Transfers.API }); // 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' + // 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)), + 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 for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, 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); - // all of the files were already queued; list of transfers should be empty - if (batch.Transfers.Count == 0) + 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 Ok(batch); + return StatusCode(StatusCodes.Status200OK, response); } - return StatusCode(201, batch); + // 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) { @@ -412,8 +428,8 @@ namespace slskd.Transfers.API } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); - return StatusCode(500, ex.Message); + 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 { @@ -532,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) { @@ -567,7 +583,7 @@ namespace slskd.Transfers.API /// The specified download was not found. [HttpGet("downloads/{username}/{id}/position")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { -- cgit v1.2.3 From 946333991d4f06aa139e9659952b2ce2ca9e988d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 13:40:48 -0500 Subject: mess with tests and validation --- .../Common/Validation/AbsolutePathAttribute.cs | 6 - src/slskd/Common/Validation/GuidAttribute.cs | 26 +- .../Common/Validation/RelativePathAttribute.cs | 6 - src/slskd/Core/Options.cs | 3 + .../API/Controllers/TransfersController.cs | 4 +- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 3 +- .../Validation/AbsolutePathAttributeTests.cs | 33 --- .../Common/Validation/GuidAttributeTests.cs | 120 +++++--- .../Validation/RelativePathAttributeTests.cs | 26 -- .../Common/Validation/StringAttributeTests.cs | 308 +++++++-------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- 11 files changed, 211 insertions(+), 326 deletions(-) (limited to 'src/slskd/Transfers') 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 index 5728b8f6..f61527a4 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -32,6 +32,8 @@ namespace slskd.Validation { + using System; + using System.ComponentModel.DataAnnotations; /// @@ -39,6 +41,13 @@ namespace slskd.Validation /// 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) @@ -46,8 +55,23 @@ namespace slskd.Validation return ValidationResult.Success; } - if (value is string str && System.Guid.TryParse(str, out _)) + 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; } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index e8865554..64e418b1 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ 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; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..3d9c8fb2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -766,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; @@ -777,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; @@ -2013,6 +2015,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/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 01dd61bd..3191e3a8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -385,7 +385,7 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); + 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()) @@ -488,7 +488,7 @@ namespace slskd.Transfers.API if (!Guid.TryParse(id, out var guid)) { - return BadRequest(); + return BadRequest($"The specified id {id} is not a valid GUID/UUID"); } try diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 53f5290f..c1b7d725 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -61,8 +61,7 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [NotNullOrWhiteSpace] - [StringLength(maximumLength: 500)] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] public string Username { get; init; } /// diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 53e25ac6..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] diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index e574c130..a26bb160 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel.DataAnnotations; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class GuidAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(object value) + private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false) { - var attribute = new GuidAttribute(); + 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); @@ -22,53 +23,84 @@ public class GuidAttributeTests Assert.True(isValid); } - public class Passes + [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() { - [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("00000000-0000-0000-0000-000000000000")] // all zeros - [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's - public void ValidGuidString_Passes(string value) - { - var (isValid, _) = Validate(value); - Assert.True(isValid); - } + var (isValid, message) = Validate(Guid.Empty, allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); } - public class Fails + [Fact] + public void AllowEmpty_Guid_Defaults_False() { - [Fact] - public void EmptyString_Fails() - { - var (isValid, errorMessage) = Validate(string.Empty); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + var (isValid, message) = Validate(Guid.Empty); + Assert.False(isValid); + Assert.Contains("empty", message); + } - [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 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 NonStringValue_Fails() - { - var (isValid, errorMessage) = Validate(42); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [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/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 1692bceb..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] diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index 71e6ce8b..dbc82736 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -17,49 +17,119 @@ public class StringAttributeTests return (result == null, result?.ErrorMessage); } - // empty string passes all default checks — [Required] handles presence - [Fact] - public void EmptyString_Passes() + public class Null { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [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 DisallowedCharacters + public class Empty { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true); + Assert.True(isValid); + } - public class Passes + [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() { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); + 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, ['!']); + var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']); Assert.True(isValid); } [Fact] public void NoDisallowedCharsPresent_Passes() { - var (isValid, _) = Validate("hello", ['!', '@']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } [Fact] public void EmptyDisallowedSet_Passes() { - var (isValid, _) = Validate("hello!@#", []); + var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []); Assert.True(isValid); } [Fact] public void Unicode_AllowedChars_Pass() { - var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } @@ -68,76 +138,73 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() { - var (isValid, _) = Validate("B", ['a']); + var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']); Assert.True(isValid); } } public class Fails { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void SingleDisallowedChar_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtStart_Fails() { - var (isValid, _) = Validate("!hello", ['!']); + var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtEnd_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharInMiddle_Fails() { - var (isValid, _) = Validate("hel!lo", ['!']); + var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void OneOfMultipleDisallowedCharsPresent_Fails() { - var (isValid, _) = Validate("hello!", ['!', '@', '#']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void MultipleDisallowedCharsAllPresent_Fails() { - var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void DisallowedCharRepeated_Fails() { - var (isValid, _) = Validate("he!lo!", ['!']); + var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void AllCharsDisallowed_Fails() { - var (isValid, _) = Validate("!@#", ['!', '@', '#']); + var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void Unicode_DisallowedChar_Fails() { - var (isValid, _) = Validate("пользователь", ['е']); + var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']); Assert.False(isValid); } @@ -145,41 +212,38 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_Blocks_UpperCase() { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']); Assert.False(isValid); } [Fact] public void UpperCaseDisallowed_Blocks_LowerCase() { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']); Assert.False(isValid); } [Fact] public void ExactMatch_Fails() { - var (isValid, _) = Validate("hello", ['h']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']); Assert.False(isValid); } } public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void TheDisallowedChar() { - var (_, errorMessage) = Validate("hello!", ['!']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.Contains("'!'", errorMessage); } [Fact] public void AllPresentDisallowedChars() { - var (_, errorMessage) = Validate("h!@l", ['!', '@']); + var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.Contains("'@'", errorMessage); } @@ -188,7 +252,7 @@ public class StringAttributeTests public void EachOccurrenceOfRepeatedChar() { // "he!lo!" has two '!' — both occurrences are listed - var (_, errorMessage) = Validate("he!lo!", ['!']); + var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.Equal(2, errorMessage.Split("'!'").Length - 1); } @@ -196,7 +260,7 @@ public class StringAttributeTests public void OnlyCharsActuallyPresent_NotAllDisallowedChars() { // '@' is disallowed but not in the value — must not appear in the message - var (_, errorMessage) = Validate("hello!", ['!', '@']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.DoesNotContain("'@'", errorMessage); } @@ -206,159 +270,15 @@ public class StringAttributeTests { // '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']); + var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']); Assert.Contains("'A'", errorMessage); Assert.DoesNotContain("'a'", errorMessage); } } } - // ----------------------------------------------------------------------- - // AllowNull - // ----------------------------------------------------------------------- - public class AllowNull - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Null_Passes_When_AllowNull_Is_True() - { - var (isValid, _) = Validate(null); - Assert.True(isValid); - } - - [Fact] - public void Null_Fails_When_AllowNull_Is_False() - { - var (isValid, _) = Validate(null, a => a.AllowNull = false); - Assert.False(isValid); - } - - [Fact] - public void NonNull_Passes_When_AllowNull_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowNull = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowNull.Validate(value, configure); - - [Fact] - public void Null_Keyword() - { - var (_, message) = Validate(null, a => a.AllowNull = false); - Assert.Contains("null", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowEmpty - // ----------------------------------------------------------------------- - public class AllowEmpty - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Empty_Passes_When_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); - } - - [Fact] - public void Empty_Fails_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.False(isValid); - } - - [Fact] - public void NonEmpty_Passes_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowEmpty.Validate(value, configure); - - [Fact] - public void Character_Keyword() - { - var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.Contains("character", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowWhiteSpace - // ----------------------------------------------------------------------- - public class AllowWhiteSpace - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() - { - var (isValid, _) = Validate(" "); - Assert.True(isValid); - } - - [Fact] - public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - [Fact] - public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); - Assert.True(isValid); - } - - // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check - // when AllowEmpty=true (default) and AllowWhiteSpace=false - [Fact] - public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowWhiteSpace.Validate(value, configure); - - [Fact] - public void Whitespace_Keyword() - { - var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.Contains("whitespace", message); - } - } - } - - // ----------------------------------------------------------------------- - // Length (MinimumLength / MaximumLength) - // ----------------------------------------------------------------------- public class Length { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void Within_Range_Passes() { @@ -396,9 +316,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Length.Validate(value, configure); - [Fact] public void MinimumLength_Value() { @@ -415,16 +332,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Pattern - // ----------------------------------------------------------------------- - // The Pattern check fails validation when the value *matches* the regex — - // Pattern acts as a "disallowed pattern" rather than a "required pattern". public class Pattern { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void NullPattern_Passes() { @@ -449,9 +358,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Pattern.Validate(value, configure); - [Fact] public void RegularExpression_Keyword() { @@ -461,16 +367,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Check ordering - // ----------------------------------------------------------------------- - // Validation checks run in declaration order; when a value violates multiple - // conditions the error from the first check in code is the one returned. public class CheckOrdering { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - // AllowNull is checked before AllowEmpty: // null with both disabled returns the null error, not the empty error. [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 2440291c..a9f30129 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -141,7 +141,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage); } } -- cgit v1.2.3 From 33c37b535d4ce68313b77d3a466933c8b047e825 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 May 2026 18:44:38 -0500 Subject: fix bug handling incomplete filenames --- src/slskd/Transfers/Downloads/DownloadService.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 89b8a6a7..83e91ced 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1049,13 +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) - // if there is no batch id, sanitize the username and use that + // 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: FileSafety.CombineSafely( - OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); + 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; @@ -1163,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, -- cgit v1.2.3