From aa7175a22e51314aa9ba0e818bf21884bec4fe49 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Jul 2022 13:45:04 -0500 Subject: docs and polish --- .../API/Controllers/TransfersController.cs | 62 +++- src/slskd/Transfers/Downloads/DownloadService.cs | 376 +++++++++++---------- src/slskd/Transfers/Downloads/IDownloadService.cs | 82 +++++ 3 files changed, 328 insertions(+), 192 deletions(-) create mode 100644 src/slskd/Transfers/Downloads/IDownloadService.cs (limited to 'src') 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 Enqueue([FromRoute, Required]string username, [FromBody]IEnumerable requests) + public async Task EnqueueAsync([FromRoute, Required]string username, [FromBody]IEnumerable requests) { try { @@ -154,11 +158,22 @@ namespace slskd.Transfers.API [HttpGet("downloads")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetDownloads() + public async Task 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); } /// @@ -170,12 +185,27 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetDownloads([FromRoute, Required]string username) + public async Task 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); } /// @@ -191,7 +221,7 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] - public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) + public async Task 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 @@ -32,30 +32,6 @@ namespace slskd.Transfers.Downloads using Serilog; using slskd.Integrations.FTP; - /// - /// Manages downloads. - /// - public interface IDownloadService - { - /// - /// Enqueues the requested list of . - /// - /// - /// If one file in the specified collection fails, the rest will continue. An will be thrown after all files are dispositioned if any throws. - /// - /// - /// - /// - /// - /// Thrown when at least one of the requested files throws. - Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); - Task GetPlaceInQueueAsync(Guid id); - Task CancelAsync(Guid id, bool remove = false); - Task RemoveAsync(Guid id); - Task FindAsync(Expression> expression); - Task> ListAsync(Expression> expression = null); - } - /// /// Manages downloads. /// @@ -75,204 +51,213 @@ namespace slskd.Transfers.Downloads FTP = ftpClient; } - private IDbContextFactory ContextFactory { get; } - private IOptionsMonitor OptionsMonitor { get; } + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } + private IDbContextFactory ContextFactory { get; } private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); - - public async Task 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 OptionsMonitor { get; } + private ITransferTracker Tracker { get; } /// /// Enqueues the requested list of . /// /// - /// If one file in the specified collection fails, the rest will continue. An will be thrown after all files are dispositioned if any throws. + /// If one file in the specified collection fails, the rest will continue. An will be + /// thrown after all files are dispositioned if any throws. /// - /// - /// - /// + /// The username of the requesting user. + /// The list of files to enqueue. + /// The operation context. + /// Thrown when the username is null or an empty string. + /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task 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(); + 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(TaskCreationOptions.RunContinuationsAsynchronously); - - async Task UpdateAndSaveChangesAsync(Transfer transfer) + var thrownExceptions = new List(); + + 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(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(); - 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(); + 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; } } + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. public async Task FindAsync(Expression> 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 } } + /// + /// Retrieves the place in the remote queue for the download matching the specified . + /// + /// The unique identifier for the download. + /// The retrieved place in queue. public async Task GetPlaceInQueueAsync(Guid id) { try @@ -307,12 +297,24 @@ namespace slskd.Transfers.Downloads } } - public async Task> ListAsync(Expression> expression = null) + /// + /// Returns a list of all downloads matching the optional . + /// + /// An optional expression used to match downloads. + /// Optionally include downloads that have been removed previously. + /// The list of downloads matching the specified expression, or all downloads if no expression is specified. + public async Task> ListAsync(Expression> 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 } } + /// + /// Removes the download matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + /// public async Task RemoveAsync(Guid id) { try @@ -344,6 +352,22 @@ namespace slskd.Transfers.Downloads } } + /// + /// Cancels the download matching the specified , if it is in progress. + /// + /// The unique identifier for the download. + /// A value indicating whether the download was successfully cancelled. + 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 (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/. +// + +namespace slskd.Transfers.Downloads +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + + /// + /// Manages downloads. + /// + public interface IDownloadService + { + /// + /// Enqueues the requested list of . + /// + /// + /// If one file in the specified collection fails, the rest will continue. An will be + /// thrown after all files are dispositioned if any throws. + /// + /// The username of the requesting user. + /// The list of files to enqueue. + /// The operation context. + /// Thrown when the username is null or an empty string. + /// Thrown when no files are requested. + /// Thrown when at least one of the requested files throws. + Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. + Task FindAsync(Expression> expression); + + /// + /// Retrieves the place in the remote queue for the download matching the specified . + /// + /// The unique identifier for the download. + /// The retrieved place in queue. + Task GetPlaceInQueueAsync(Guid id); + + /// + /// Returns a list of all downloads matching the optional . + /// + /// An optional expression used to match downloads. + /// Optionally include downloads that have been removed previously. + /// The list of downloads matching the specified expression, or all downloads if no expression is specified. + Task> ListAsync(Expression> expression = null, bool includeRemoved = false); + + /// + /// Removes the download matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + /// + Task RemoveAsync(Guid id); + + /// + /// Cancels the download matching the specified , if it is in progress. + /// + /// The unique identifier for the download. + /// A value indicating whether the download was successfully cancelled. + bool TryCancel(Guid id); + } +} \ No newline at end of file -- cgit v1.2.3