aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2022-07-24 13:45:04 -0500
committerJP Dillingham <jpdillingham@gmail.com>2022-07-24 13:45:04 -0500
commitaa7175a22e51314aa9ba0e818bf21884bec4fe49 (patch)
treed9b77357cb468736365cb944ca2ef66c052ffca5
parent1601d121ff4374e3e95d79d7fac3bf44b03d3783 (diff)
downloadslskd-aa7175a22e51314aa9ba0e818bf21884bec4fe49.tar.gz
docs and polish
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs62
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs376
-rw-r--r--src/slskd/Transfers/Downloads/IDownloadService.cs82
3 files changed, 328 insertions, 192 deletions
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 74d92d5f..a45112f8 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -22,9 +22,7 @@ namespace slskd.Transfers.API
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
- using System.IO;
using System.Linq;
- using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -92,7 +90,13 @@ namespace slskd.Transfers.API
try
{
- await Transfers.Downloads.CancelAsync(guid, remove);
+ Transfers.Downloads.TryCancel(guid);
+
+ if (remove)
+ {
+ await Transfers.Downloads.RemoveAsync(guid);
+ }
+
return NoContent();
}
catch (NotFoundException)
@@ -133,7 +137,7 @@ namespace slskd.Transfers.API
[ProducesResponseType(201)]
[ProducesResponseType(typeof(string), 403)]
[ProducesResponseType(typeof(string), 500)]
- public async Task<IActionResult> Enqueue([FromRoute, Required]string username, [FromBody]IEnumerable<QueueDownloadRequest> requests)
+ public async Task<IActionResult> EnqueueAsync([FromRoute, Required]string username, [FromBody]IEnumerable<QueueDownloadRequest> requests)
{
try
{
@@ -154,11 +158,22 @@ namespace slskd.Transfers.API
[HttpGet("downloads")]
[Authorize]
[ProducesResponseType(200)]
- public IActionResult GetDownloads()
+ public async Task<IActionResult> GetDownloadsAsync([FromQuery]bool includeRemoved = false)
{
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Download)
- .ToMap());
+ var downloads = await Transfers.Downloads.ListAsync(includeRemoved: includeRemoved);
+
+ var response = downloads.GroupBy(t => t.Username).Select(grouping => new UserResponse()
+ {
+ Username = grouping.Key,
+ Directories = grouping.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse()
+ {
+ Name = d.Key,
+ FileCount = d.Count(),
+ Files = d.ToList(),
+ }),
+ });
+
+ return Ok(response);
}
/// <summary>
@@ -170,12 +185,27 @@ namespace slskd.Transfers.API
[HttpGet("downloads/{username}")]
[Authorize]
[ProducesResponseType(200)]
- public IActionResult GetDownloads([FromRoute, Required]string username)
+ public async Task<IActionResult> GetDownloadsAsync([FromRoute, Required] string username)
{
- return Ok(Tracker.Transfers
- .WithDirection(TransferDirection.Download)
- .FromUser(username)
- .ToMap());
+ var downloads = await Transfers.Downloads.ListAsync(d => d.Username == username);
+
+ if (!downloads.Any())
+ {
+ return NotFound();
+ }
+
+ var response = new UserResponse()
+ {
+ Username = username,
+ Directories = downloads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse()
+ {
+ Name = d.Key,
+ FileCount = d.Count(),
+ Files = d.ToList(),
+ }),
+ };
+
+ return Ok(response);
}
/// <summary>
@@ -191,7 +221,7 @@ namespace slskd.Transfers.API
[Authorize]
[ProducesResponseType(typeof(API.Transfer), 200)]
[ProducesResponseType(404)]
- public async Task<IActionResult> GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id)
+ public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, Required] string username, [FromRoute, Required] string id)
{
if (!Guid.TryParse(id, out var guid))
{
@@ -237,7 +267,7 @@ namespace slskd.Transfers.API
[HttpGet("uploads/{username}")]
[Authorize]
[ProducesResponseType(200)]
- public IActionResult GetUploads([FromRoute, Required]string username)
+ public IActionResult GetUploads([FromRoute, Required] string username)
{
return Ok(Tracker.Transfers
.WithDirection(TransferDirection.Upload)
@@ -255,7 +285,7 @@ namespace slskd.Transfers.API
[HttpGet("uploads/{username}/{id}")]
[Authorize]
[ProducesResponseType(200)]
- public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id)
+ public IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id)
{
return Ok(Tracker.Transfers
.WithDirection(TransferDirection.Upload)
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index f53c6004..87bf3023 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -35,30 +35,6 @@ namespace slskd.Transfers.Downloads
/// <summary>
/// Manages downloads.
/// </summary>
- public interface IDownloadService
- {
- /// <summary>
- /// Enqueues the requested list of <paramref name="files"/>.
- /// </summary>
- /// <remarks>
- /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be thrown after all files are dispositioned if any throws.
- /// </remarks>
- /// <param name="id"></param>
- /// <param name="username"></param>
- /// <param name="files"></param>
- /// <returns></returns>
- /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
- Task<int> GetPlaceInQueueAsync(Guid id);
- Task<bool> CancelAsync(Guid id, bool remove = false);
- Task RemoveAsync(Guid id);
- Task<Transfer> FindAsync(Expression<Func<Transfer, bool>> expression);
- Task<List<Transfer>> ListAsync(Expression<Func<Transfer, bool>> expression = null);
- }
-
- /// <summary>
- /// Manages downloads.
- /// </summary>
public class DownloadService : IDownloadService
{
public DownloadService(
@@ -75,204 +51,213 @@ namespace slskd.Transfers.Downloads
FTP = ftpClient;
}
- private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
- private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>();
private ISoulseekClient Client { get; }
- private ITransferTracker Tracker { get; }
+ private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
private IFTPService FTP { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>();
- private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>();
-
- public async Task<bool> CancelAsync(Guid id, bool remove = false)
- {
- if (CancellationTokens.TryRemove(id, out var cts))
- {
- cts.Cancel();
-
- if (remove)
- {
- await RemoveAsync(id);
- }
-
- return true;
- }
-
- return false;
- }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private ITransferTracker Tracker { get; }
/// <summary>
/// Enqueues the requested list of <paramref name="files"/>.
/// </summary>
/// <remarks>
- /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be thrown after all files are dispositioned if any throws.
+ /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
+ /// thrown after all files are dispositioned if any throws.
/// </remarks>
- /// <param name="username"></param>
- /// <param name="files"></param>
- /// <returns></returns>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="files">The list of files to enqueue.</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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files)
+ public Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files)
{
- try
+ if (string.IsNullOrEmpty(username))
{
- Log.Information("Downloading {Count} files from user {Username}", files.Count(), username);
+ throw new ArgumentException("Username is required", nameof(username));
+ }
- Log.Debug("Priming connection for user {Username}", username);
- await Client.ConnectToUserAsync(username, invalidateCache: false);
- Log.Debug("Connection for user '{Username}' primed", username);
+ if (!files.Any())
+ {
+ throw new ArgumentException("At least one file is require", nameof(files));
+ }
- var thrownExceptions = new List<Exception>();
+ return EnqueueAsyncInternal(username, files);
- foreach (var file in files)
+ async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files)
+ {
+ try
{
- Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username);
+ Log.Information("Downloading {Count} files from user {Username}", files.Count(), username);
- var id = Guid.NewGuid();
+ Log.Debug("Priming connection for user {Username}", username);
+ await Client.ConnectToUserAsync(username, invalidateCache: false);
+ Log.Debug("Connection for user '{Username}' primed", username);
- var transfer = new Transfer()
- {
- Id = id,
- Username = username,
- Direction = TransferDirection.Download,
- Filename = file.Filename,
- Size = file.Size,
- StartOffset = 0,
- RequestedAt = DateTime.UtcNow,
- };
-
- // persist the transfer to the database so we have a record that it was attempted
- using var context = await ContextFactory.CreateDbContextAsync();
- context.Add(transfer);
- await context.SaveChangesAsync();
-
- var cts = new CancellationTokenSource();
- CancellationTokens.TryAdd(id, cts);
-
- var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
-
- async Task UpdateAndSaveChangesAsync(Transfer transfer)
+ var thrownExceptions = new List<Exception>();
+
+ foreach (var file in files)
{
+ Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username);
+
+ var id = Guid.NewGuid();
+
+ var transfer = new Transfer()
+ {
+ Id = id,
+ Username = username,
+ Direction = TransferDirection.Download,
+ Filename = file.Filename,
+ Size = file.Size,
+ StartOffset = 0,
+ RequestedAt = DateTime.UtcNow,
+ };
+
+ // persist the transfer to the database so we have a record that it was attempted
using var context = await ContextFactory.CreateDbContextAsync();
- context.Update(transfer);
+ context.Add(transfer);
await context.SaveChangesAsync();
- }
- // this task does the actual work of downloading the file. if the transfer is successfully queued remotely,
- // the waitUntilEnqueue completion source is set, which yields execution to below so we can return and let
- // the caller know.
- var downloadTask = Task.Run(async () =>
- {
- using var rateLimiter = new RateLimiter(250);
+ var cts = new CancellationTokenSource();
+ CancellationTokens.TryAdd(id, cts);
- try
+ var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ async Task UpdateAndSaveChangesAsync(Transfer transfer)
{
- var completedTransfer = await Client.DownloadAsync(
- username: username,
- remoteFilename: file.Filename,
- outputStreamFactory: () => GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete),
- size: file.Size,
- startOffset: 0,
- token: null,
- cancellationToken: cts.Token,
- options: new TransferOptions(
- disposeOutputStreamOnCompletion: true,
- stateChanged: (args) =>
- {
- Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State);
-
- Tracker.AddOrUpdate(args.Transfer, cts);
-
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
- // todo: broadcast
- _ = UpdateAndSaveChangesAsync(transfer);
-
- if (args.Transfer.State.HasFlag(TransferStates.Queued) || args.Transfer.State == TransferStates.Initializing)
- {
- waitUntilEnqueue.TrySetResult(true);
- }
- },
- progressUpdated: (args) => rateLimiter.Invoke(() =>
- {
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
- // todo: broadcast
- _ = UpdateAndSaveChangesAsync(transfer);
-
- Tracker.AddOrUpdate(args.Transfer, cts);
- })));
-
- transfer = transfer.WithSoulseekTransfer(completedTransfer);
- // todo: broadcast
- await UpdateAndSaveChangesAsync(transfer);
-
- // this would be the ideal place to hook in a generic post-download task processor
- // for now, we'll just carry out hard coded behavior
- MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads);
-
- if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled)
- {
- _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads));
- }
+ using var context = await ContextFactory.CreateDbContextAsync();
+ context.Update(transfer);
+ await context.SaveChangesAsync();
}
- finally
+
+ // this task does the actual work of downloading the file. if the transfer is successfully queued
+ // remotely, the waitUntilEnqueue completion source is set, which yields execution to below so we can
+ // return and let the caller know.
+ var downloadTask = Task.Run(async () =>
{
- CancellationTokens.TryRemove(id, out _);
- }
- });
+ using var rateLimiter = new RateLimiter(250);
- // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the
- // downloadTask throws due to an error prior to successfully queueing.
- var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask);
+ try
+ {
+ var completedTransfer = await Client.DownloadAsync(
+ username: username,
+ remoteFilename: file.Filename,
+ outputStreamFactory: () => GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete),
+ size: file.Size,
+ startOffset: 0,
+ token: null,
+ cancellationToken: cts.Token,
+ options: new TransferOptions(
+ disposeOutputStreamOnCompletion: true,
+ stateChanged: (args) =>
+ {
+ Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State);
- // if the download task completed first it is a very good indication that it threw an exception or was otherwise
- // not successful. try to figure out why and update everything to reflect the failure, but continue processing the batch
- if (task == downloadTask)
- {
- Exception ex = downloadTask.Exception;
+ Tracker.AddOrUpdate(args.Transfer, cts);
+
+ transfer = transfer.WithSoulseekTransfer(args.Transfer);
+ // todo: broadcast
+ _ = UpdateAndSaveChangesAsync(transfer);
+
+ if (args.Transfer.State.HasFlag(TransferStates.Queued) || args.Transfer.State == TransferStates.Initializing)
+ {
+ waitUntilEnqueue.TrySetResult(true);
+ }
+ },
+ progressUpdated: (args) => rateLimiter.Invoke(() =>
+ {
+ transfer = transfer.WithSoulseekTransfer(args.Transfer);
+ // todo: broadcast
+ _ = UpdateAndSaveChangesAsync(transfer);
+
+ Tracker.AddOrUpdate(args.Transfer, cts);
+ })));
+
+ transfer = transfer.WithSoulseekTransfer(completedTransfer);
+ // todo: broadcast
+ await UpdateAndSaveChangesAsync(transfer);
+
+ // this would be the ideal place to hook in a generic post-download task processor for now, we'll
+ // just carry out hard coded behavior
+ MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads);
+
+ if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled)
+ {
+ _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads));
+ }
+ }
+ finally
+ {
+ CancellationTokens.TryRemove(id, out _);
+ }
+ });
+
+ // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or
+ // the downloadTask throws due to an error prior to successfully queueing.
+ var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask);
- // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate?
- if (ex is AggregateException aggEx)
+ // if the download task completed first it is a very good indication that it threw an exception or was
+ // otherwise not successful. try to figure out why and update everything to reflect the failure, but
+ // continue processing the batch
+ if (task == downloadTask)
{
- var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>();
- if (rejected.Any())
+ Exception ex = downloadTask.Exception;
+
+ // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate?
+ if (ex is AggregateException aggEx)
{
- ex = rejected.First();
+ var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>();
+ if (rejected.Any())
+ {
+ ex = rejected.First();
+ }
}
+
+ Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
+ thrownExceptions.Add(ex);
+ transfer.Exception = ex.Message;
+ transfer.State = TransferStates.Completed | TransferStates.Errored;
+ transfer.EndedAt = DateTime.UtcNow;
+ }
+ else
+ {
+ transfer.EnqueuedAt = DateTime.UtcNow;
+ Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username);
}
- Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
- thrownExceptions.Add(ex);
- transfer.Exception = ex.Message;
- transfer.State = TransferStates.Completed | TransferStates.Errored;
- transfer.EndedAt = DateTime.UtcNow;
+ await context.SaveChangesAsync();
}
- else
+
+ if (thrownExceptions.Any())
{
- transfer.EnqueuedAt = DateTime.UtcNow;
- Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username);
+ throw new AggregateException(thrownExceptions);
}
- await context.SaveChangesAsync();
+ Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username);
}
-
- if (thrownExceptions.Any())
+ catch (Exception ex)
{
- throw new AggregateException(thrownExceptions);
+ Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message);
+ throw;
}
-
- Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username);
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message);
- throw;
}
}
+ /// <summary>
+ /// Finds a single download matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match downloads.</param>
+ /// <returns>The found transfer, or default if not found.</returns>
public async Task<Transfer> FindAsync(Expression<Func<Transfer, bool>> expression)
{
try
{
var context = await ContextFactory.CreateDbContextAsync();
- return await context.Transfers.Where(expression).FirstOrDefaultAsync();
+ return await context.Transfers
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(expression).FirstOrDefaultAsync();
}
catch (Exception ex)
{
@@ -281,6 +266,11 @@ namespace slskd.Transfers.Downloads
}
}
+ /// <summary>
+ /// Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>The retrieved place in queue.</returns>
public async Task<int> GetPlaceInQueueAsync(Guid id)
{
try
@@ -307,12 +297,24 @@ namespace slskd.Transfers.Downloads
}
}
- public async Task<List<Transfer>> ListAsync(Expression<Func<Transfer, bool>> expression = null)
+ /// <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>
+ /// <param name="includeRemoved">Optionally include downloads that have been removed previously.</param>
+ /// <returns>The list of downloads matching the specified expression, or all downloads if no expression is specified.</returns>
+ public async Task<List<Transfer>> ListAsync(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false)
{
+ expression ??= t => true;
+
try
{
var context = await ContextFactory.CreateDbContextAsync();
- return await context.Transfers.Where(expression).ToListAsync();
+ return await context.Transfers
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(t => !t.Removed || includeRemoved)
+ .Where(expression)
+ .ToListAsync();
}
catch (Exception ex)
{
@@ -321,6 +323,12 @@ namespace slskd.Transfers.Downloads
}
}
+ /// <summary>
+ /// Removes the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="id">The unique identifier of the download.</param>
+ /// <returns></returns>
public async Task RemoveAsync(Guid id)
{
try
@@ -344,6 +352,22 @@ namespace slskd.Transfers.Downloads
}
}
+ /// <summary>
+ /// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>A value indicating whether the download was successfully cancelled.</returns>
+ public bool TryCancel(Guid id)
+ {
+ if (CancellationTokens.TryRemove(id, out var cts))
+ {
+ cts.Cancel();
+ return true;
+ }
+
+ return false;
+ }
+
private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory)
{
var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory);
@@ -377,4 +401,4 @@ namespace slskd.Transfers.Downloads
}
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs
new file mode 100644
index 00000000..07475d31
--- /dev/null
+++ b/src/slskd/Transfers/Downloads/IDownloadService.cs
@@ -0,0 +1,82 @@
+// <copyright file="IDownloadService.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Transfers.Downloads
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq.Expressions;
+ using System.Threading.Tasks;
+
+ /// <summary>
+ /// Manages downloads.
+ /// </summary>
+ public interface IDownloadService
+ {
+ /// <summary>
+ /// Enqueues the requested list of <paramref name="files"/>.
+ /// </summary>
+ /// <remarks>
+ /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
+ /// thrown after all files are dispositioned if any throws.
+ /// </remarks>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="files">The list of files to enqueue.</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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
+
+ /// <summary>
+ /// Finds a single download matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match downloads.</param>
+ /// <returns>The found transfer, or default if not found.</returns>
+ Task<Transfer> FindAsync(Expression<Func<Transfer, bool>> expression);
+
+ /// <summary>
+ /// Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>The retrieved place in queue.</returns>
+ Task<int> GetPlaceInQueueAsync(Guid id);
+
+ /// <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>
+ /// <param name="includeRemoved">Optionally include downloads that have been removed previously.</param>
+ /// <returns>The list of downloads matching the specified expression, or all downloads if no expression is specified.</returns>
+ Task<List<Transfer>> ListAsync(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
+
+ /// <summary>
+ /// Removes the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="id">The unique identifier of the download.</param>
+ /// <returns></returns>
+ Task RemoveAsync(Guid id);
+
+ /// <summary>
+ /// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>A value indicating whether the download was successfully cancelled.</returns>
+ bool TryCancel(Guid id);
+ }
+} \ No newline at end of file