aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Transfers
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
committerJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
commit294fcabd3928b420a4dfbd7ddd0dc38ada523165 (patch)
treebcc92e42c71f2a9b67f7750c5ecd0a396b5897e5 /src/slskd/Transfers
parent60bc0c0c2ea6d9c80a7f091f022567b1d5e3240a (diff)
parent8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff)
downloadslskd-294fcabd3928b420a4dfbd7ddd0dc38ada523165.tar.gz
Merge remote-tracking branch 'origin/master' into reports
Diffstat (limited to 'src/slskd/Transfers')
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs205
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs118
-rw-r--r--src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (renamed from src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs)26
-rw-r--r--src/slskd/Transfers/API/DTO/Transfer.cs169
-rw-r--r--src/slskd/Transfers/Downloads/BatchService.cs140
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs288
-rw-r--r--src/slskd/Transfers/Extensions.cs1
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs43
-rw-r--r--src/slskd/Transfers/Types/Batch.cs118
-rw-r--r--src/slskd/Transfers/Types/BatchOptions.cs53
-rw-r--r--src/slskd/Transfers/Types/DestinationConflictStrategy.cs49
-rw-r--r--src/slskd/Transfers/Types/DestinationExistsStrategy.cs49
-rw-r--r--src/slskd/Transfers/Types/RetryPartialStrategy.cs (renamed from src/slskd/Transfers/Types/RetryIncompleteStrategy.cs)8
-rw-r--r--src/slskd/Transfers/Types/Transfer.cs208
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs54
16 files changed, 1179 insertions, 351 deletions
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 494ee722..3191e3a8 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -42,6 +42,7 @@ namespace slskd.Transfers.API
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using slskd.Users;
@@ -217,7 +218,7 @@ namespace slskd.Transfers.API
}
/// <summary>
- /// Enqueues the specified download.
+ /// (Obsolete) Enqueues the specified download.
/// </summary>
/// <param name="username">The username of the download source.</param>
/// <param name="requests">The list of download requests.</param>
@@ -225,6 +226,7 @@ namespace slskd.Transfers.API
/// <response code="201">The download was successfully enqueued.</response>
/// <response code="403">The download was rejected.</response>
/// <response code="500">An unexpected error was encountered.</response>
+ [Obsolete("Will be phased out in future versions; use batches")]
[HttpPost("downloads/{username}")]
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(201)]
@@ -249,7 +251,12 @@ namespace slskd.Transfers.API
if (requests.Any(r => r is null))
{
- return BadRequest("One or more records in the request are null");
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (requests.Any(r => FileSafety.ContainsTraversalSegments(r.Filename)))
+ {
+ return BadRequest("One or more files in the request contain a dangerous path traversal segment");
}
if (!DownloadRequestLimiter.Wait(0))
@@ -282,6 +289,155 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Enqueues a batch of downloads.
+ /// </summary>
+ /// <param name="request">The batch details.</param>
+ /// <returns></returns>
+ /// <response code="201">All downloads were successfully enqueued.</response>
+ /// <response code="200">The request succeeded, but all downloads failed to be enqueued.</response>
+ /// <response code="207">Some downloads were successfully enqueued, while some failed.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="403">The request was forbidden.</response>
+ /// <response code="409">A batch with the same ID already exists.</response>
+ /// <response code="429">Request throttled.</response>
+ /// <response code="500">An unexpected error was encountered.</response>
+ [HttpPost("downloads/batches")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)]
+ [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)]
+ [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)]
+ public async Task<IActionResult> EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!ModelState.IsValid)
+ {
+ return BadRequest(ModelState.GetReadableString());
+ }
+
+ if (request.Files.Any(r => r is null))
+ {
+ return BadRequest("One or more files in the request are null");
+ }
+
+ if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count)
+ {
+ return BadRequest("Two or more files in the request are repeated");
+ }
+
+ Guid? batchId;
+ Guid? searchId;
+
+ try
+ {
+ batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id);
+ searchId = string.IsNullOrWhiteSpace(request.SearchId) ? null : Guid.Parse(request.SearchId);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message);
+ return BadRequest("One or more provided identifiers is not a valid GUID/UUID");
+ }
+
+ batchId ??= Guid.NewGuid();
+
+ if (!DownloadRequestLimiter.Wait(0))
+ {
+ return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes");
+ }
+
+ try
+ {
+ var endpoint = await Users.GetIPEndPointAsync(request.Username);
+
+ if (Users.IsBlacklisted(request.Username, endpoint.Address))
+ {
+ throw new UserOfflineException($"User {request.Username} appears to be offline");
+ }
+
+ // throws DuplicateException if a record already exists
+ await Transfers.Downloads.Batches.CreateAsync(new()
+ {
+ Id = batchId.Value,
+ SearchId = searchId,
+ Username = request.Username,
+ Options = new()
+ {
+ Destination = request.Options.Destination,
+ },
+ });
+
+ // Transfer records will have been inserted before this returns, unless they were rejected
+ // because they were already in progress, in which case they will show up in 'failed'. or maybe they
+ // failed with an error. either way this complicates the return code
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(
+ username: request.Username,
+ files: request.Files.Select(r => (r.Filename, r.Size.Value)),
+ batchId: batchId);
+
+ if (failed.Count > 0)
+ {
+ Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed);
+ }
+
+ // the returned batch will have whatever Transfers were successfully inserted attached (via Include())
+ // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been
+ // properly finalized and marked as a failure
+ var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId);
+
+ var response = new QueueDownloadBatchResponse
+ {
+ Batch = batch,
+ Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(),
+ };
+
+ // basically a no-op, but we did create the batch record (and it's useless, but it's there)
+ // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me,
+ // but it doesn't allow a body and without it the caller will never know the id unless they supplied it
+ if (response.Failures.Count == request.Files.Count)
+ {
+ return StatusCode(StatusCodes.Status200OK, response);
+ }
+
+ // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code
+ // along with the batch and list of failures; the caller will have to pick through it and decide what to do
+ if (response.Failures.Count > 0)
+ {
+ return StatusCode(StatusCodes.Status207MultiStatus, response);
+ }
+
+ // everything passed and we are now (or will eventually be) downloading asynchronously
+ return StatusCode(StatusCodes.Status201Created, response);
+ }
+ catch (UserOfflineException ex)
+ {
+ return StatusCode(StatusCodes.Status404NotFound, ex.Message);
+ }
+ catch (DuplicateException ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id);
+ return Conflict($"A batch with ID {batchId} already exists");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message);
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ finally
+ {
+ DownloadRequestLimiter.Release();
+ }
+ }
+
+ /// <summary>
/// Gets all downloads.
/// </summary>
/// <returns></returns>
@@ -313,6 +469,47 @@ namespace slskd.Transfers.API
}
/// <summary>
+ /// Gets the specified batch and associated transfers.
+ /// </summary>
+ /// <param name="id">The id of the batch.</param>
+ /// <returns></returns>
+ /// <response code="400">The specified id is not valid.</response>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="404">The specified batch was not found.</response>
+ [HttpGet("downloads/batches/{id}")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(200)]
+ public async Task<IActionResult> Get([FromRoute, Required] string id)
+ {
+ if (Program.IsRelayAgent)
+ {
+ return Forbid();
+ }
+
+ if (!Guid.TryParse(id, out var guid))
+ {
+ return BadRequest($"The specified id {id} is not a valid GUID/UUID");
+ }
+
+ try
+ {
+ var found = await Transfers.Downloads.Batches.FindAsync(b => b.Id == guid);
+
+ if (found is null)
+ {
+ return NotFound();
+ }
+
+ return Ok(found);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to get batch with ID {Id}: {Message}", guid, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
/// Gets all downloads for the specified username.
/// </summary>
/// <param name="username"></param>
@@ -351,7 +548,7 @@ namespace slskd.Transfers.API
[HttpGet("downloads/{username}/{id}")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
@@ -386,7 +583,7 @@ namespace slskd.Transfers.API
/// <response code="404">The specified download was not found.</response>
[HttpGet("downloads/{username}/{id}/position")]
[Authorize(Policy = AuthPolicy.Any)]
- [ProducesResponseType(typeof(API.Transfer), 200)]
+ [ProducesResponseType(typeof(Transfer), 200)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id)
{
diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
new file mode 100644
index 00000000..fe34bfec
--- /dev/null
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs
@@ -0,0 +1,118 @@
+// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using slskd.Validation;
+
+namespace slskd.Transfers.API;
+
+/// <summary>
+/// Enqueue a batch of downloads.
+/// </summary>
+public record QueueDownloadBatchRequest
+{
+ /// <summary>
+ /// The ID of the Batch.
+ /// </summary>
+ /// <remarks>
+ /// If not supplied, one will be randomly generated.
+ /// </remarks>
+ [Guid]
+ public string Id { get; init; }
+
+ /// <summary>
+ /// The ID of the associated Search, if applicable.
+ /// </summary>
+ [Guid]
+ public string SearchId { get; init; }
+
+ /// <summary>
+ /// The username of the user from which to download.
+ /// </summary>
+ [Required]
+ [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)]
+ public string Username { get; init; }
+
+ /// <summary>
+ /// The list of files to download.
+ /// </summary>
+ [Required]
+ [MinLength(1)]
+ public IReadOnlyCollection<EnqueueDownloadBatchItem> Files { get; init; } = [];
+
+ /// <summary>
+ /// Options for the Batch.
+ /// </summary>
+ public EnqueueDownloadBatchOptions Options { get; init; } = new();
+}
+
+/// <summary>
+/// An item in a download batch.
+/// </summary>
+public record EnqueueDownloadBatchItem
+{
+ /// <summary>
+ /// The name of the file.
+ /// </summary>
+ [Required]
+ [NotNullOrWhiteSpace]
+ [NonTraversingPath]
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// The file size.
+ /// </summary>
+ [Required]
+ [Range(0, long.MaxValue)]
+ public long? Size { get; init; }
+}
+
+/// <summary>
+/// Download batch options.
+/// </summary>
+public record EnqueueDownloadBatchOptions
+{
+ /// <summary>
+ /// The destination directory for the files, relative to the configured download directory.
+ /// </summary>
+ [RelativePath(OperatingSystem.All)]
+ [NonTraversingPath]
+ [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
+ public string Destination { get; init; }
+
+ /// <summary>
+ /// An optional external ID for the batch.
+ /// </summary>
+ public string ExternalId { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
index ce3331ca..84b570bc 100644
--- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
+++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs
@@ -1,4 +1,4 @@
-// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
+// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -30,28 +30,18 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-using System;
using System.Collections.Generic;
-using System.ComponentModel.DataAnnotations;
namespace slskd.Transfers.API;
-public record EnqueueDownloadBatchRequest
+public record QueueDownloadBatchResponse
{
- public Guid? BatchId { get; init; }
- public Guid? SearchId { get; init; }
-
- [Required]
- [StringLength(500, MinimumLength = 1)]
- public string Username { get; init; }
- public List<EnqueueDownloadBatchItem> Files { get; init; } = [];
+ public Batch Batch { get; init; }
+ public IReadOnlyCollection<QueueDownloadBatchResponseFailure> Failures { get; init; } = [];
}
-public record EnqueueDownloadBatchItem
+public record QueueDownloadBatchResponseFailure
{
- [Required]
- public string Filename { get; set; }
-
- [Range(0, int.MaxValue)]
- public long Size { get; set; }
-} \ No newline at end of file
+ public string Filename { get; init; }
+ public string Message { get; init; }
+}
diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs
deleted file mode 100644
index 949f15d4..00000000
--- a/src/slskd/Transfers/API/DTO/Transfer.cs
+++ /dev/null
@@ -1,169 +0,0 @@
-// <copyright file="Transfer.cs" company="JP Dillingham">
-// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
-// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
-// █__ --█ █__ --█ ◄█ - █
-// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
-// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
-// │ Copyright (c) JP Dillingham.
-// │
-// │ This program is free software: you can redistribute it and/or modify
-// │ it under the terms of the GNU Affero General Public License as published
-// │ by the Free Software Foundation, version 3.
-// │
-// │ This program is distributed in the hope that it will be useful,
-// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
-// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// │ GNU Affero General Public License for more details.
-// │
-// │ You should have received a copy of the GNU Affero General Public License
-// │ along with this program. If not, see https://www.gnu.org/licenses/.
-// │
-// │ This program is distributed with Additional Terms pursuant to Section 7
-// │ of the AGPLv3. See the LICENSE file in the root directory of this
-// │ project for the complete terms and conditions.
-// │
-// │ https://slskd.org
-// │
-// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
-// │ SPDX-FileCopyrightText: JP Dillingham
-// │ SPDX-License-Identifier: AGPL-3.0-only
-// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
-// </copyright>
-
-namespace slskd.Transfers.API
-{
- using System;
- using System.Net;
- using Soulseek;
-
- /// <summary>
- /// A single file transfer.
- /// </summary>
- public class Transfer
- {
- /// <summary>
- /// Gets the current average transfer speed.
- /// </summary>
- public double AverageSpeed { get; set; }
-
- /// <summary>
- /// Gets the number of remaining bytes to be transferred.
- /// </summary>
- public long BytesRemaining { get; set; }
-
- /// <summary>
- /// Gets the total number of bytes transferred.
- /// </summary>
- public long BytesTransferred { get; set; }
-
- /// <summary>
- /// Gets the transfer direction.
- /// </summary>
- public TransferDirection Direction { get; set; }
-
- /// <summary>
- /// Gets the current duration of the transfer, if it has been started.
- /// </summary>
- public double? ElapsedTime { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.Completed"/> state.
- /// </summary>
- public DateTime? EndTime { get; set; }
-
- /// <summary>
- /// Gets the filename of the file to be transferred.
- /// </summary>
- public string Filename { get; set; }
-
- /// <summary>
- /// Gets the transfer id.
- /// </summary>
- public string Id => Compute.Sha1Hash(Filename);
-
- /// <summary>
- /// Gets the ip endpoint of the remote transfer connection, if one has been established.
- /// </summary>
- public IPEndPoint IPEndPoint { get; set; }
-
- /// <summary>
- /// Gets the current progress in percent.
- /// </summary>
- public double PercentComplete { get; set; }
-
- /// <summary>
- /// Gets the current place in queue, if it has been fetched.
- /// </summary>
- public int? PlaceInQueue { get; set; }
-
- /// <summary>
- /// Gets the projected remaining duration of the transfer.
- /// </summary>
- public double? RemainingTime { get; set; }
-
- /// <summary>
- /// Gets the remote unique token for the transfer.
- /// </summary>
- public int? RemoteToken { get; set; }
-
- /// <summary>
- /// Gets the size of the file to be transferred, in bytes.
- /// </summary>
- public long Size { get; set; }
-
- /// <summary>
- /// Gets the starting offset of the transfer, in bytes.
- /// </summary>
- public long StartOffset { get; set; }
-
- /// <summary>
- /// Gets the UTC time at which the transfer transitioned into the <see cref="TransferStates.InProgress"/> state.
- /// </summary>
- public DateTime? StartTime { get; set; }
-
- /// <summary>
- /// Gets the state of the transfer.
- /// </summary>
- public TransferStates State { get; set; }
-
- /// <summary>
- /// Gets the unique token for the transfer.
- /// </summary>
- public int Token { get; set; }
-
- /// <summary>
- /// Gets the username of the peer to or from which the file is to be transferred.
- /// </summary>
- public string Username { get; set; }
-
- /// <summary>
- /// Gets the Exception that caused the failure of the transfer, if applicable.
- /// </summary>
- public string Exception { get; set; }
-
- public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer)
- {
- return new Transfer()
- {
- AverageSpeed = transfer.AverageSpeed,
- BytesRemaining = transfer.BytesRemaining,
- BytesTransferred = transfer.BytesTransferred,
- Direction = transfer.Direction,
- ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds,
- EndTime = transfer.EndTime,
- Filename = transfer.Filename,
- IPEndPoint = transfer.IPEndPoint,
- PercentComplete = transfer.PercentComplete,
- RemainingTime = transfer.RemainingTime?.TotalMilliseconds,
- RemoteToken = transfer.RemoteToken,
- Size = transfer.Size,
- StartOffset = transfer.StartOffset,
- StartTime = transfer.StartTime,
- State = transfer.State,
- Token = transfer.Token,
- Username = transfer.Username,
- Exception = transfer.Exception?.Message,
- };
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs
new file mode 100644
index 00000000..7ea9a70a
--- /dev/null
+++ b/src/slskd/Transfers/Downloads/BatchService.cs
@@ -0,0 +1,140 @@
+// <copyright file="BatchService.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers.Downloads;
+
+using System;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Threading.Tasks;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using Serilog;
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public interface IBatchService
+{
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ Task<Batch> CreateAsync(Batch batch);
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression);
+}
+
+/// <summary>
+/// Manages transfer batches.
+/// </summary>
+public class BatchService : IBatchService
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BatchService"/> class.
+ /// </summary>
+ /// <param name="contextFactory">The database context factory to use.</param>
+ public BatchService(IDbContextFactory<TransfersDbContext> contextFactory)
+ {
+ ContextFactory = contextFactory;
+ }
+
+ private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<BatchService>();
+
+ /// <summary>
+ /// Creates a new batch record.
+ /// </summary>
+ /// <param name="batch">The batch to create.</param>
+ /// <returns>The created batch.</returns>
+ public async Task<Batch> CreateAsync(Batch batch)
+ {
+ if (batch == default)
+ {
+ throw new ArgumentNullException(nameof(batch));
+ }
+
+ if (batch.Id == Guid.Empty)
+ {
+ throw new ArgumentOutOfRangeException(nameof(batch.Id), message: $"Batch ID may not be an empty uuid ({Guid.Empty})");
+ }
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ context.Batches.Add(batch);
+
+ await context.SaveChangesAsync();
+
+ return batch;
+ }
+ catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19 })
+ {
+ throw new DuplicateException($"A Batch with ID {batch.Id} already exists.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Failed to create Batch: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Finds a single batch matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match batches.</param>
+ /// <returns>The found batch, or default if not found.</returns>
+ /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception>
+ public async Task<Batch> FindAsync(Expression<Func<Batch, bool>> expression)
+ {
+ if (expression == default)
+ {
+ throw new ArgumentException("An expression must be supplied.", nameof(expression));
+ }
+
+ using var context = ContextFactory.CreateDbContext();
+
+ return await context.Batches
+ .AsNoTracking()
+ .Include(b => b.Transfers)
+ .Where(expression)
+ .SingleOrDefaultAsync();
+ }
+}
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index d4d8004a..7c794e55 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -38,9 +38,11 @@ namespace slskd.Transfers.Downloads
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+ using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
+ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
@@ -49,6 +51,7 @@ namespace slskd.Transfers.Downloads
using slskd.Files;
using slskd.Integrations.FTP;
using slskd.Relay;
+ using slskd.Search;
/// <summary>
/// Manages downloads.
@@ -56,6 +59,11 @@ namespace slskd.Transfers.Downloads
public interface IDownloadService
{
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ IBatchService Batches { get; }
+
+ /// <summary>
/// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
/// </summary>
/// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
@@ -63,6 +71,26 @@ namespace slskd.Transfers.Downloads
void AddOrSupersede(Transfer transfer);
/// <summary>
+ /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and batch
+ /// configuration.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
+ /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
+ /// </para>
+ /// <para>
+ /// Empty segments may be present in the output, which more closely aligns with user intent. The
+ /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
+ /// </para>
+ /// </remarks>
+ /// <param name="transfer">The transfer.</param>
+ /// <returns>The derived destination directory.</returns>
+ /// <exception cref="NotFoundException">Thrown if the specified download doesn't exist.</exception>
+ /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
+ Task<string> DeriveDestination(Transfer transfer);
+
+ /// <summary>
/// Enqueues the requested list of <paramref name="files"/>.
/// </summary>
/// <remarks>
@@ -71,12 +99,13 @@ namespace slskd.Transfers.Downloads
/// </remarks>
/// <param name="username">The username of remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
+ Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single download matching the specified <paramref name="expression"/>.
@@ -158,6 +187,8 @@ namespace slskd.Transfers.Downloads
public class DownloadService : IDownloadService
{
public DownloadService(
+ IBatchService batchService,
+ ISearchService searchService,
IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient soulseekClient,
IDbContextFactory<TransfersDbContext> contextFactory,
@@ -166,6 +197,8 @@ namespace slskd.Transfers.Downloads
IFTPService ftpClient,
EventBus eventBus)
{
+ Batches = batchService;
+ Searches = searchService;
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
ContextFactory = contextFactory;
@@ -178,6 +211,11 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Gets download batch service.
+ /// </summary>
+ public IBatchService Batches { get; }
+
+ /// <summary>
/// These tokens give users the ability to cancel transfers via the UI (or API).
///
/// The lifecycle is:
@@ -200,10 +238,12 @@ namespace slskd.Transfers.Downloads
private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
private IFTPService FTP { get; }
private FileService Files { get; }
+ private ISearchService Searches { get; }
private IRelayService Relay { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private EventBus EventBus { get; }
+ private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they
@@ -249,12 +289,13 @@ namespace slskd.Transfers.Downloads
/// </summary>
/// <param name="username">The username of the remote user.</param>
/// <param name="files">The list of files to enqueue.</param>
+ /// <param name="batchId">The optional batch id for the transfers.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- public async Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
+ public async Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
@@ -273,6 +314,11 @@ namespace slskd.Transfers.Downloads
throw new ArgumentException("At least one filename is null or empty", nameof(files));
}
+ if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename)))
+ {
+ throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files));
+ }
+
if (fileList.Count != fileList.Distinct().Count())
{
throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
@@ -306,7 +352,7 @@ namespace slskd.Transfers.Downloads
}
List<Transfer> enqueued = [];
- List<string> failed = [];
+ List<(string Filename, string Message)> failed = [];
SemaphoreSlim userSemaphore;
Task userSemaphoreWaitTask;
@@ -404,7 +450,7 @@ namespace slskd.Transfers.Downloads
if (existingInProgressRecord is not null)
{
Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -416,7 +462,7 @@ namespace slskd.Transfers.Downloads
if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false)
{
Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username);
- failed.Add(file.Filename);
+ failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
@@ -431,11 +477,11 @@ namespace slskd.Transfers.Downloads
var transfer = new Transfer()
{
Id = transferId,
+ BatchId = batchId,
Username = username,
Direction = TransferDirection.Download,
Filename = file.Filename, // important! use the remote filename
Size = file.Size,
- StartOffset = 0, // todo: maybe implement resumeable downloads?
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
@@ -607,7 +653,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))
{
@@ -689,6 +735,152 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and
+ /// batch configuration.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
+ /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
+ /// </para>
+ /// <para>
+ /// Empty segments may be present in the output, which more closely aligns with user intent. The
+ /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
+ /// </para>
+ /// </remarks>
+ /// <param name="transfer">The transfer.</param>
+ /// <returns>The derived destination directory.</returns>
+ /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
+ public async Task<string> DeriveDestination(Transfer transfer)
+ {
+ // validation should ensure this is a relative path and that it contains no traversal segments
+ // we accept any type of slash in the pattern and convert it to the correct variant for the local OS
+ var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory;
+
+ // users can enter '{}' if they want the files to go directly into the root of the downloads directory
+ if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase))
+ {
+ return string.Empty;
+ }
+
+ string source_username;
+ string source_path;
+ string source_directory;
+ string batch_id;
+ string batch_external_id;
+ string search_id;
+ string search_text;
+
+ /*
+ fetch/extract/derive and sanitize each of the values we're going to replace
+
+ when flow leaves this block we can expect that all of the string values
+ defined above have a value that can be safely substituted for its placeholder
+ */
+ try
+ {
+ Batch batch = null;
+
+ if (transfer.BatchId is not null)
+ {
+ batch = await Batches.FindAsync(b => b.Id == transfer.BatchId);
+ }
+
+ // destination supplied with the batch enqueue request takes precedence over all; return early
+ if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination))
+ {
+ var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_');
+
+ // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
+ // properly sanitizing user input both via the API and in the logic above
+ if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination))
+ {
+ throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub.");
+ }
+
+ return explicitDestination;
+ }
+
+ Search search = null;
+
+ if (batch?.SearchId is not null)
+ {
+ search = await Searches.FindAsync(s => s.Id == batch.SearchId);
+ }
+
+ source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_');
+
+ var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_');
+
+ // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz'
+ // retains the path root, if there is one (Soulseek NS does this), which may not be what
+ // people want, so possibly revisit and add StripPathRoot()
+ source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\');
+
+ // name of the remote parent directory, so using the example above, 'Baz'
+ source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\');
+
+ batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString();
+
+ // the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination,
+ // except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended
+ batch_external_id = FileSafety.SanitizeFilename(
+ filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId,
+ replacement: '_');
+
+ search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString();
+ search_text = FileSafety.SanitizeFilename(
+ filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText,
+ replacement: '_');
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message);
+ throw;
+ }
+
+ var args = new Dictionary<string, string>(
+ StringComparer.OrdinalIgnoreCase) // important!
+ {
+ ["SOURCE_USERNAME"] = source_username,
+ ["SOURCE_PATH"] = source_path,
+ ["SOURCE_DIRECTORY"] = source_directory,
+ ["BATCH_ID"] = batch_id,
+ ["BATCH_EXTERNAL_ID"] = batch_external_id,
+ ["SEARCH_ID"] = search_id,
+ ["SEARCH_TEXT"] = search_text,
+ };
+
+ // use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could
+ // cascade into others and produce unintended results
+ var destination = SubdirectoryPatternTokenRegex.Replace(
+ input: pattern,
+ evaluator: match =>
+ {
+ if (args.TryGetValue(match.Groups[1].Value, out var value))
+ {
+ return value;
+ }
+
+ return match.Value;
+ });
+
+ destination = FileSafety.SanitizePath(destination, replacement: '_');
+
+ Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });
+
+ // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
+ // properly sanitizing the final output to strip leading slashes and replace traversal segments
+ if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination))
+ {
+ Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });
+ throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub.");
+ }
+
+ return destination;
+ }
+
+ /// <summary>
/// Returns a list of all downloads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match downloads.</param>
@@ -973,9 +1165,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
@@ -1024,16 +1218,42 @@ namespace slskd.Transfers.Downloads
}),
disposeOutputStreamOnCompletion: true);
- System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode)
- ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
+ UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode)
+ ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.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)
- var incompleteFilename = transfer.Filename.ToLocalFilename(
- baseDirectory: System.IO.Path.Combine(
- OptionsMonitor.CurrentValue.Directories.Incomplete,
- transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty));
+ /*
+ 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.
+
+ we're going to store the file as:
+
+ <incomplete directory>/<username>/<full path to file on remote client>/<filename>
+
+ so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes:
+
+ linux: incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext
+ windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext
+
+ slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _.
+ this mitigates the risk of an improper partial resume to a great extent.
+
+ if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because
+ the size we send originates from the original file, and there will be a mismatch.
+
+ the only remaining risk is in a case where the file contents have changed but the size remains the same.
+ the resulting file will be corrupted in that case, and there's nothing we can really do about it. users
+ that are concerned about this (extremely unlikely) case should configure slskd to always overwrite
+ partial files.
+ */
+ var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete;
+ var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username);
+ var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true);
+ var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty;
+
+ var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename);
+
+ Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename);
Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
transfer.Attempts = 1;
@@ -1042,14 +1262,14 @@ namespace slskd.Transfers.Downloads
var completedTransfer = await Retry.Do(() =>
{
var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename);
- var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>();
+ var incompleteStrategy = retryOptions.Partial.ToEnum<RetryPartialStrategy>();
var shouldResume = false;
var startOffset = 0L;
if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0)
{
- if (incompleteStrategy == RetryIncompleteStrategy.Resume)
+ if (incompleteStrategy == RetryPartialStrategy.Resume)
{
shouldResume = true;
startOffset = incompleteFileInfo.Length;
@@ -1121,33 +1341,29 @@ namespace slskd.Transfers.Downloads
move the file from incomplete to complete
users have a lot of strong opinions about this!
+
+ the destination is always rooted in the configured download directory. we derive the subdirectory
+ for this file based on either the Destination property defined for the Batch that contains this transfer,
+ or by applying replacements to the user's configured Destination.Subdirectory string.
+
+ what we get back will be a relative path (or perhaps an empty string if that's what the user wanted)
+ that has sanitized and checked for safety against traversal
*/
- string destinationDirectory;
+ var subdirectory = await DeriveDestination(transfer);
+ var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory);
- if (transfer.BatchId is not null)
- {
- // 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());
- }
- else
- {
- // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so:
- // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext
- // this is "legacy" behavior that will be familiar to most Soulseek users
- destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads));
- }
+ var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>();
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,
+ overwrite: existsStrategy == DestinationExistsStrategy.Overwrite,
deleteSourceDirectoryIfEmptyAfterMove: true);
- Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename);
+ Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename);
if (OptionsMonitor.CurrentValue.Relay.Enabled)
{
diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs
index 48179ff2..3180dbd9 100644
--- a/src/slskd/Transfers/Extensions.cs
+++ b/src/slskd/Transfers/Extensions.cs
@@ -44,7 +44,6 @@ namespace slskd.Transfers
Direction = transfer.Direction,
Filename = transfer.Filename,
Size = transfer.Size,
- StartOffset = t.StartOffset,
State = t.State,
RequestedAt = transfer.RequestedAt,
EnqueuedAt = transfer.EnqueuedAt,
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index be312e8e..b25e7663 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -33,6 +33,7 @@
namespace slskd.Transfers
{
using System;
+ using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@@ -43,16 +44,23 @@ namespace slskd.Transfers
{
}
+ public DbSet<Batch> Batches { get; set; }
public DbSet<Transfer> Transfers { get; set; }
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// this is absolutely NOT IDEAL and will accellerate the move away from EF
+ // we have to do this to store both the integer and the string value in the database
+ // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history
+ // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries,
+ // which is the main driver for this.
foreach (var entry in ChangeTracker.Entries<Transfer>())
{
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
+#pragma warning disable CS0618 // Type or member is obsolete
entry.Entity.StateDescription = entry.Entity.State.ToString();
+#pragma warning restore CS0618 // Type or member is obsolete
}
}
@@ -61,6 +69,12 @@ namespace slskd.Transfers
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
+ ConfigureTransfers(modelBuilder);
+ ConfigureBatches(modelBuilder);
+ }
+
+ private void ConfigureTransfers(ModelBuilder modelBuilder)
+ {
modelBuilder
.Entity<Transfer>()
.Property(e => e.StartedAt)
@@ -114,5 +128,34 @@ namespace slskd.Transfers
.HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size })
.HasDatabaseName("IDX_Transfers_UserUploadStatistics");
}
+
+ private void ConfigureBatches(ModelBuilder modelBuilder)
+ {
+ modelBuilder
+ .Entity<Batch>()
+ .Property(e => e.CreatedAt)
+ .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasMany(b => b.Transfers)
+ .WithOne()
+ .HasForeignKey(t => t.BatchId)
+ .IsRequired(false)
+ .OnDelete(DeleteBehavior.Cascade);
+
+ modelBuilder
+ .Entity<Batch>()
+ .Property(b => b.Options)
+ .HasConversion(
+ convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()),
+ convertFromProviderExpression: v => JsonSerializer.Deserialize<BatchOptions>(v, new JsonSerializerOptions().WithStandardOptions()))
+ .HasColumnType("TEXT");
+
+ modelBuilder
+ .Entity<Batch>()
+ .HasIndex(b => b.SearchId)
+ .HasDatabaseName("IDX_Batches_SearchId");
+ }
}
}
diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs
new file mode 100644
index 00000000..a0d71bef
--- /dev/null
+++ b/src/slskd/Transfers/Types/Batch.cs
@@ -0,0 +1,118 @@
+// <copyright file="Batch.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations;
+using Soulseek;
+
+/// <summary>
+/// <para>
+/// A Transfer Batch is a lightweight association between a number of related Transfer
+/// records and optionally the associated Search the Transfers are intended to fulfil.
+/// </para>
+/// <para>
+/// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the
+/// available API(s) to determine whether all of the Transfers within the Batch are complete,
+/// but otherwise a Batch serves no functional purpose within the application.
+/// </para>
+/// </summary>
+public record Batch
+{
+ /// <summary>
+ /// Gets the associated <see cref="slskd.Search.Search.Id"/>, if one was specified when the
+ /// Batch was enqueued.
+ /// </summary>
+ public Guid? SearchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Batch.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the username associated with the Batch.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Batch direction (Upload, Download).
+ /// </summary>
+ /// <remarks>
+ /// We don't have, and likely will never be able to implement, upload batches,
+ /// nor are they of any particular use.
+ /// </remarks>
+ public TransferDirection Direction { get; init; } = TransferDirection.Download;
+
+ /// <summary>
+ /// Gets the time at which the Batch was created.
+ /// </summary>
+ public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
+
+ /// <summary>
+ /// Gets the Transfer records associated with the batch.
+ /// </summary>
+ public ICollection<Transfer> Transfers { get; init; } = null;
+
+ /// <summary>
+ /// Gets the options for the batch.
+ /// </summary>
+ public BatchOptions Options { get; init; }
+
+ /*
+ future: [NotMapped] properties that aggregate values from the associated Transfer records.
+ there's no use for these now, but if we ever decide to leverage Batch records for anything
+ but determining whether a Search has been fulfilled, allowing a user to override a download directory,
+ or to handle an event when a batch is completed, we can add them and figure out how persistence should work.
+
+ file count and size are also not included because of the transfer deduplication that takes place during
+ the enqueue; if a batch is created and some or all of the files within are already in progress, they are
+ dropped and no new transfer records are created. this would create data inconsistency, and for no reason (for now)
+
+ loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer
+ records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works,
+ but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches
+ from results (as this must be aggregated on the fly for each batch.. forever)
+
+ my thinking (and reason for punting on this for now); add the interesting properties (Removed, BytesTransferred,
+ AverageSpeed, etc) to this class as nullable, and don't set a value until all of the associated Transfer
+ records have been finalized, then update the columns. when fetching batches we can deduce that any Batch
+ record missing those properties is still in progress, and we can aggregate the data on the fly. for historical
+ records that have completed, the data is all in the database and is quick to query.
+
+ this can sit until/if we have further use for Batch records, i want to get this out and don't want to sit
+ and go back and forth trying to speculate on how this might need to work in the future.
+ */
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs
new file mode 100644
index 00000000..2ea22997
--- /dev/null
+++ b/src/slskd/Transfers/Types/BatchOptions.cs
@@ -0,0 +1,53 @@
+// <copyright file="BatchOptions.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Options for <see cref="Batch"/>es.
+/// </summary>
+public record BatchOptions
+{
+ /// <summary>
+ /// Gets the optional destination directory for the files in the Batch, relative to the configured
+ /// download directory.
+ /// </summary>
+ /// <remarks>
+ /// If specified, takes precedence over other configured placement rules.
+ /// </remarks>
+ public string Destination { get; init; }
+
+ /// <summary>
+ /// Gets an optional external ID for the batch.
+ /// </summary>
+ public string ExternalId { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs
new file mode 100644
index 00000000..27281a2d
--- /dev/null
+++ b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs
@@ -0,0 +1,49 @@
+// <copyright file="DestinationConflictStrategy.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Strategy for handling downloaded files with conflicting names.
+/// </summary>
+public enum DestinationConflictStrategy
+{
+ /// <summary>
+ /// Rename the new file by appending something.
+ /// </summary>
+ Rename = 0,
+
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ Overwrite = 1,
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/DestinationExistsStrategy.cs b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs
new file mode 100644
index 00000000..18837563
--- /dev/null
+++ b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs
@@ -0,0 +1,49 @@
+// <copyright file="DestinationExistsStrategy.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Strategy for handling downloaded files when the destination file already exists.
+/// </summary>
+public enum DestinationExistsStrategy
+{
+ /// <summary>
+ /// Rename the new file by appending something to the file name.
+ /// </summary>
+ Rename = 0,
+
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ Overwrite = 1,
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryPartialStrategy.cs
index 9ac8d8e2..20868913 100644
--- a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
+++ b/src/slskd/Transfers/Types/RetryPartialStrategy.cs
@@ -1,4 +1,4 @@
-// <copyright file="RetryIncompleteStrategy.cs" company="JP Dillingham">
+// <copyright file="RetryPartialStrategy.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -33,9 +33,9 @@
namespace slskd.Transfers;
/// <summary>
-/// Strategy for retrying incomplete files.
+/// Strategy for retrying partial files.
/// </summary>
-public enum RetryIncompleteStrategy
+public enum RetryPartialStrategy
{
/// <summary>
/// Overwrite the existing file.
@@ -43,7 +43,7 @@ public enum RetryIncompleteStrategy
Overwrite = 0,
/// <summary>
- /// Resume the transfer using the size of the incomplete file as the initial offset.
+ /// Resume the transfer using the size of the partial file as the initial offset.
/// </summary>
Resume = 1,
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs
index 93a23380..d33a5efc 100644
--- a/src/slskd/Transfers/Types/Transfer.cs
+++ b/src/slskd/Transfers/Types/Transfer.cs
@@ -30,72 +30,146 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
-namespace slskd.Transfers
+namespace slskd.Transfers;
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Text.Json.Serialization;
+using Soulseek;
+
+/// <summary>
+/// A file Transfer between network peers.
+/// </summary>
+public class Transfer
{
- using System;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text.Json.Serialization;
- using Soulseek;
-
- public class Transfer
- {
- public Guid? BatchId { get; init; } = null;
-
- [Key]
- public Guid Id { get; init; }
- public string Username { get; init; }
- public TransferDirection Direction { get; init; }
-
- /// <summary>
- /// Gets the remote filename.
- /// </summary>
- public string Filename { get; init; }
- public long Size { get; set; }
- public long StartOffset { get; init; }
-
- public TransferStates State { get; set; } = TransferStates.None;
-
- /// <summary>
- /// Gets the string representation of the transfer <see cref="State"/>.
- /// </summary>
- /// <remarks>
- /// This is a hack to get the string into the database. *DO NOT* use this property in code
- /// and especially **DO NOT** set the value. The getter and setter can't be protected because
- /// EF Core needs them to be public.
- /// </remarks>
- public string StateDescription { get; set; }
- public DateTime RequestedAt { get; set; }
- public DateTime? EnqueuedAt { get; set; }
- public DateTime? StartedAt { get; set; }
-
- /// <summary>
- /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress.
- /// </summary>
- /// <remarks>
- /// Guaranteed to be set for transfers in a terminal state.
- /// </remarks>
- public DateTime? EndedAt { get; set; }
- public long BytesTransferred { get; set; }
- public double AverageSpeed { get; set; }
-
- public int? PlaceInQueue { get; set; }
- public string Exception { get; set; }
-
- public int Attempts { get; set; } = 0;
-
- public DateTime? NextAttemptAt { get; set; } = null;
-
- [JsonIgnore]
- public bool Removed { get; set; }
-
- [NotMapped]
- public long BytesRemaining => Size - BytesTransferred;
- [NotMapped]
- public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
- [NotMapped]
- public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
- [NotMapped]
- public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
- }
+ /// <summary>
+ /// Gets the associated <see cref="Batch.Id"/>, if one was specified when the Transfer was created.
+ /// </summary>
+ public Guid? BatchId { get; init; } = null;
+
+ /// <summary>
+ /// Gets the unique identifier for the Transfer.
+ /// </summary>
+ [Key]
+ public Guid Id { get; init; }
+
+ /// <summary>
+ /// Gets the remote username associated with the Transfer.
+ /// </summary>
+ public string Username { get; init; }
+
+ /// <summary>
+ /// Gets the Transfer direction (Upload, Download).
+ /// </summary>
+ public TransferDirection Direction { get; init; }
+
+ /// <summary>
+ /// Gets the remote filename of the file.
+ /// </summary>
+ /// <remarks>
+ /// Exactly as it appeared in the originating Search, Browse, or file directory contents response.
+ /// </remarks>
+ public string Filename { get; init; }
+
+ /// <summary>
+ /// Gets or sets the remote size of the file.
+ /// </summary>
+ public long Size { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state of the Transfer.
+ /// </summary>
+ public TransferStates State { get; set; } = TransferStates.None;
+
+ /// <summary>
+ /// Gets or sets the string representation of the transfer <see cref="State"/>.
+ /// </summary>
+ /// <remarks>
+ /// This is a hack to get the string into the database. *DO NOT* use this property in code
+ /// and especially **DO NOT** set the value. The getter and setter can't be protected because
+ /// EF Core needs them to be public.
+ /// </remarks>
+ [Obsolete("Use State isntead; this is a hack for EF")]
+ [JsonIgnore]
+ public string StateDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was requested from the remote peer.
+ /// </summary>
+ public DateTime RequestedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued.
+ /// </summary>
+ /// <remarks>
+ /// For downloads, this is the time at which the remote peer responded to our enqueue request. For uploads this
+ /// is the time at which the transfer was made available for scheduling by the upload queue, after we have
+ /// responded to the remote peer's request to enqueue.
+ /// </remarks>
+ public DateTime? EnqueuedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer connection was established and data transfer began, or null if the
+ /// Transfer has not yet been started.
+ /// </summary>
+ public DateTime? StartedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress.
+ /// </summary>
+ /// <remarks>
+ /// Guaranteed to be set for transfers in a terminal state.
+ /// </remarks>
+ public DateTime? EndedAt { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of bytes transferred.
+ /// </summary>
+ public long BytesTransferred { get; set; }
+
+ /// <summary>
+ /// Gets or sets the average speed of the Transfer over the duration.
+ /// </summary>
+ public double AverageSpeed { get; set; }
+
+ /// <summary>
+ /// Gets or sets the current place in line in the remote peer's queue, if place has been requested.
+ /// </summary>
+ /// <remarks>
+ /// May be wildly innacurate to the point of uselessness.
+ /// </remarks>
+ public int? PlaceInQueue { get; set; }
+
+ /// <summary>
+ /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did.
+ /// </summary>
+ public string Exception { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of attempts. Incremented each time the Transfer is retried.
+ /// </summary>
+ /// <remarks>
+ /// Applicable to downloads only.
+ /// </remarks>
+ public int Attempts { get; set; } = 0;
+
+ /// <summary>
+ /// Gets or sets the time at which the next retry attempt will be made, if applicable.
+ /// </summary>
+ public DateTime? NextAttemptAt { get; set; } = null;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the Transfer has been removed from the UI.
+ /// </summary>
+ public bool Removed { get; set; }
+
+ [NotMapped]
+ public long BytesRemaining => Size - BytesTransferred;
+ [NotMapped]
+ public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value;
+ [NotMapped]
+ public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100;
+ [NotMapped]
+ public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed);
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
index 603c669a..333ae525 100644
--- a/src/slskd/Transfers/Types/TransferStateCategories.cs
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -111,6 +111,7 @@ public static class TransferStateCategories
/// </list>
/// </summary>
public static readonly HashSet<TransferStates> Queued = [
+ TransferStates.Requested, // optimistically assume that we will be allowed to enqueue
TransferStates.Queued, // 2, in case of some sort of a malfunction or regression
TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050
TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index ebc6c4c6..894f739b 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -101,16 +101,6 @@ namespace slskd.Transfers.Uploads
Transfer Find(Expression<Func<Transfer, bool>> expression);
/// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
-
- /// <summary>
/// Gets upload statistics for the specified <paramref name="username"/>.
/// </summary>
/// <param name="username">The username of the user.</param>
@@ -678,7 +668,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,
};
@@ -777,51 +766,12 @@ namespace slskd.Transfers.Uploads
return context.Transfers
.AsNoTracking()
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(expression).FirstOrDefault();
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
- throw;
- }
- }
-
- /// <summary>
- /// Returns a summary of the uploads matching the specified <paramref name="expression"/>. This can be expensive;
- /// consider caching.
- /// </summary>
- /// <param name="expression">The expression used to select uploads for summarization.</param>
- /// <returns>
- /// The generated summary, including the number of files and total size in bytes.
- /// </returns>
- public (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression)
- {
- expression ??= t => true;
-
- try
- {
- using var context = ContextFactory.CreateDbContext();
-
- var query = context.Transfers
- .AsNoTracking()
- .Where(t => t.Direction == TransferDirection.Upload)
.Where(expression)
- .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group.
- .Select(t => new
- {
- Files = t.Count(),
- Bytes = t.Sum(x => x.Size),
- });
-
- Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString());
-
- var stats = query.FirstOrDefault();
-
- return (stats?.Files ?? 0, stats?.Bytes ?? 0);
+ .SingleOrDefault();
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to list uploads: {Message}", ex.Message);
+ Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
throw;
}
}