From 277f57a2721ed067320c8ef41289cd105c370f48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:21:31 -0500 Subject: use TransferService to enqueue --- .../API/Controllers/TransfersController.cs | 65 ++-------------------- 1 file changed, 4 insertions(+), 61 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index d3dd5518..985452bb 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -53,14 +53,17 @@ namespace slskd.Transfers.API IOptionsSnapshot options, ISoulseekClient soulseekClient, ITransferTracker tracker, + ITransferService transferService, IFTPService ftpClient) { Client = soulseekClient; Tracker = tracker; Options = options.Value; FTP = ftpClient; + Transfers = transferService; } + private ITransferService Transfers { get; } private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } @@ -121,71 +124,11 @@ namespace slskd.Transfers.API { try { - Log.Information("Downloading {Count} files from user {Username}", requests.Count(), username); - - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); - - foreach (var request in requests) - { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", request.Filename, username); - - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var cts = new CancellationTokenSource(); - - var downloadTask = Task.Run(async () => - { - await Client.DownloadAsync(username, request.Filename, () => GetLocalFileStream(request.Filename, Options.Directories.Incomplete), request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", request.Filename, username, e.PreviousState, e.Transfer.State); - - Tracker.AddOrUpdate(e.Transfer, cts); - - if (e.Transfer.State.HasFlag(TransferStates.Queued) || e.Transfer.State == TransferStates.Initializing) - { - waitUntilEnqueue.TrySetResult(true); - } - }, progressUpdated: (e) => Tracker.AddOrUpdate(e.Transfer, cts)), cts.Token); - - MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - - if (Options.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); - } - }); - - // 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); - - if (task == downloadTask) - { - if (downloadTask.Exception is AggregateException) - { - var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) - { - Log.Error("Download of {Filename} from {Username} was rejected: {Reason}", request.Filename, username, rejected.First().Message); - return StatusCode(403, rejected.First().Message); - } - } - - Log.Error("Failed to download {Filename} from {Username}: {Message}", request.Filename, username, downloadTask.Exception.Message); - return StatusCode(500, downloadTask.Exception.Message); - } - - Log.Debug("Successfully enqueued {Filename} from user {Username}", request.Filename, username); - } - - // if nothing threw, just return ok. the download will continue waiting in the background. - Log.Information("Successfully enqueued {Count} files from user {Username}", requests.Count(), username); + await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); return StatusCode(201); } catch (Exception ex) { - Log.Error(ex, "Failed to download file(s) from user {Username}: {Message}", username, ex.Message); return StatusCode(500, ex.Message); } } -- cgit v1.2.3 From ca9eaf057e70a8514f18719a0de10965a23aec51 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 Jul 2022 09:43:27 -0500 Subject: use Downloads service for some endpoints --- .../API/Controllers/TransfersController.cs | 69 +++++++++------------- 1 file changed, 29 insertions(+), 40 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 985452bb..74d92d5f 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -83,9 +83,22 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + public async Task CancelDownloadAsync([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) { - return CancelTransfer(TransferDirection.Download, username, id, remove); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + try + { + await Transfers.Downloads.CancelAsync(guid, remove); + return NoContent(); + } + catch (NotFoundException) + { + return NotFound(); + } } /// @@ -180,15 +193,24 @@ namespace slskd.Transfers.API [ProducesResponseType(404)] public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) { - var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } - if (record == default) + try + { + var place = await Transfers.Downloads.GetPlaceInQueueAsync(guid); + return Ok(place); + } + catch (NotFoundException) { return NotFound(); } - - record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); - return Ok(record.Transfer); + catch (Exception ex) + { + return StatusCode(500, ex.Message); + } } /// @@ -241,39 +263,6 @@ namespace slskd.Transfers.API .WithId(id).Transfer); } - private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!System.IO.Directory.Exists(path)) - { - System.IO.Directory.CreateDirectory(path); - } - - return new FileStream(localFilename, FileMode.Create); - } - - private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!System.IO.Directory.Exists(destinationPath)) - { - System.IO.Directory.CreateDirectory(destinationPath); - } - - System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true); - - if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - { - System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - } - private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) { if (Tracker.TryGet(direction, username, id, out var transfer)) -- cgit v1.2.3 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/slskd/Transfers/API/Controllers/TransfersController.cs') 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 From 650b5051e92c121cc17343abfc2e0ac8cbd3ff21 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 13:48:29 -0500 Subject: use AsNoTracking() --- src/slskd/Search/SearchService.cs | 11 +- .../API/Controllers/TransfersController.cs | 119 +++++++++++++++------ src/slskd/Transfers/Downloads/DownloadService.cs | 3 + src/slskd/Transfers/Uploads/UploadService.cs | 3 + 4 files changed, 102 insertions(+), 34 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 54d8bac9..2f71c733 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -109,7 +109,9 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); - var selector = context.Searches.Where(expression); + var selector = context.Searches + .AsNoTracking() + .Where(expression); if (!includeResponses) { @@ -128,7 +130,12 @@ namespace slskd.Search { expression ??= s => true; using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + + return context.Searches + .AsNoTracking() + .Where(expression) + .WithoutResponses() + .ToListAsync(); } /// diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index a45112f8..3885f416 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -50,12 +50,10 @@ namespace slskd.Transfers.API public TransfersController( IOptionsSnapshot options, ISoulseekClient soulseekClient, - ITransferTracker tracker, ITransferService transferService, IFTPService ftpClient) { Client = soulseekClient; - Tracker = tracker; Options = options.Value; FTP = ftpClient; Transfers = transferService; @@ -64,7 +62,6 @@ namespace slskd.Transfers.API private ITransferService Transfers { get; } private Options Options { get; } private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -118,9 +115,28 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + public async Task CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) { - return CancelTransfer(TransferDirection.Upload, username, id, remove); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + try + { + Transfers.Uploads.TryCancel(guid); + + if (remove) + { + await Transfers.Uploads.RemoveAsync(guid); + } + + return NoContent(); + } + catch (NotFoundException) + { + return NotFound(); + } } /// @@ -208,6 +224,27 @@ namespace slskd.Transfers.API return Ok(response); } + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(404)] + public async Task GetDownload([FromRoute, Required] string username, [FromRoute, Required] string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + var download = await Transfers.Downloads.FindAsync(t => t.Id == guid); + + if (download == default) + { + return NotFound(); + } + + return Ok(download); + } + /// /// Gets the downlaod for the specified username matching the specified filename, and requests /// the current place in the remote queue of the specified download. @@ -217,7 +254,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. /// The specified download was not found. - [HttpGet("downloads/{username}/{id}")] + [HttpGet("downloads/{username}/{id}/position")] [Authorize] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] @@ -251,11 +288,22 @@ namespace slskd.Transfers.API [HttpGet("uploads")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads() + public async Task GetUploads([FromQuery] bool includeRemoved = false) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .ToMap()); + var uploads = await Transfers.Uploads.ListAsync(includeRemoved: includeRemoved); + + var response = uploads.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); } /// @@ -267,12 +315,27 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username) + public async Task GetUploads([FromRoute, Required] string username) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .ToMap()); + var uploads = await Transfers.Uploads.ListAsync(d => d.Username == username); + + if (!uploads.Any()) + { + return NotFound(); + } + + var response = new UserResponse() + { + Username = username, + Directories = uploads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() + { + Name = d.Key, + FileCount = d.Count(), + Files = d.ToList(), + }), + }; + + return Ok(response); } /// @@ -285,29 +348,21 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .WithId(id).Transfer); - } - - private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) + public async IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { - if (Tracker.TryGet(direction, username, id, out var transfer)) + if (!Guid.TryParse(id, out var guid)) { - transfer.CancellationTokenSource.Cancel(); + return BadRequest(); + } - if (remove) - { - Tracker.TryRemove(direction, username, id); - } + var upload = await Transfers.Uploads.FindAsync(t => t.Id == guid); - return NoContent(); + if (upload == default) + { + return NotFound(); } - return NotFound(); + return Ok(upload); } } } \ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a938e767..27d7dfb5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -249,6 +249,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(expression).FirstOrDefaultAsync(); } @@ -304,6 +305,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed || includeRemoved) .Where(expression) @@ -328,6 +330,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); var transfer = await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Id == id) .FirstOrDefaultAsync(); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 451afb09..4f545827 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -207,6 +207,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(expression).FirstOrDefaultAsync(); } @@ -231,6 +232,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed || includeRemoved) .Where(expression) @@ -255,6 +257,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); var transfer = await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(t => t.Id == id) .FirstOrDefaultAsync(); -- cgit v1.2.3 From d830ec75b4f8e33f583a2f1bbb25c822eb7f4a5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 14:07:45 -0500 Subject: remove deprecated services --- .../API/Controllers/TransfersController.cs | 24 +++------------------- 1 file changed, 3 insertions(+), 21 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3885f416..d12a3f89 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -15,8 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using Microsoft.Extensions.Options; - namespace slskd.Transfers.API { using System; @@ -26,9 +24,6 @@ namespace slskd.Transfers.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using Serilog; - using slskd.Integrations.FTP; - using Soulseek; /// /// Transfers. @@ -43,27 +38,14 @@ namespace slskd.Transfers.API /// /// Initializes a new instance of the class. /// - /// - /// - /// - /// + /// public TransfersController( - IOptionsSnapshot options, - ISoulseekClient soulseekClient, - ITransferService transferService, - IFTPService ftpClient) + ITransferService transferService) { - Client = soulseekClient; - Options = options.Value; - FTP = ftpClient; Transfers = transferService; } private ITransferService Transfers { get; } - private Options Options { get; } - private ISoulseekClient Client { get; } - private IFTPService FTP { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Cancels the specified download. @@ -348,7 +330,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public async IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) + public async Task GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { if (!Guid.TryParse(id, out var guid)) { -- cgit v1.2.3