diff options
Diffstat (limited to 'src')
21 files changed, 1604 insertions, 711 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index cd45fbeb..44723aba 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -30,6 +30,7 @@ namespace slskd using System.Reflection; using System.Runtime; using System.Text.RegularExpressions; + using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -71,13 +72,14 @@ namespace slskd /// </summary> public static readonly string LeecherGroup = "leechers"; + private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor<Options> optionsMonitor, IManagedState<State> state, ISoulseekClient soulseekClient, IConnectionWatchdog connectionWatchdog, - ITransferTracker transferTracker, ITransferService transferService, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -89,6 +91,21 @@ namespace slskd IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) { + Console.CancelKeyPress += (_, args) => + { + ShuttingDown = true; + Log.Warning("Received SIGINT"); + }; + + foreach (var signal in new[] { PosixSignal.SIGINT, PosixSignal.SIGQUIT, PosixSignal.SIGTERM }) + { + PosixSignalRegistration.Create(signal, context => + { + ShuttingDown = true; + Log.Fatal("Received {Signal}", signal); + }); + } + OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; @@ -104,7 +121,6 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); - TransferTracker = transferTracker; Transfers = transferService; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; @@ -146,6 +162,13 @@ namespace slskd ConnectionWatchdog = connectionWatchdog; } + /// <summary> + /// Gets a value indicating whether the application is in the process of shutting down. + /// </summary> + public static bool IsShuttingDown => Environment.HasShutdownStarted || ShuttingDown; + + private static bool ShuttingDown { get; set; } = false; + private ISoulseekClient Client { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } @@ -161,7 +184,6 @@ namespace slskd private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } private IManagedState<State> State { get; } - private ITransferTracker TransferTracker { get; set; } private ITransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } @@ -169,6 +191,7 @@ namespace slskd private IShareService Shares { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; } + private IEnumerable<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = Enumerable.Empty<Guid>(); public void CollectGarbage() { @@ -236,7 +259,41 @@ namespace slskd async Task IHostedService.StartAsync(CancellationToken cancellationToken) { - Log.Information("Configuring client"); + // if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these + // records to be updated if the application has started to shut down so that we can do this cleanup and properly + // disposition them as having failed due to an application shutdown, instead of some random exception thrown while + // things are being disposed. + var activeUploads = (await Transfers.Uploads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)) + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .ToList(); + + await Task.WhenAll(activeUploads.Select(async upload => + { + Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username); + upload.State = TransferStates.Completed | TransferStates.Errored; + upload.Exception = ApplicationShutdownTransferExceptionMessage; + await Transfers.Uploads.UpdateAsync(upload); + })); + + var activeDownloads = (await Transfers.Downloads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)) + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .ToList(); + + await Task.WhenAll(activeDownloads.Select(async download => + { + Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username); + download.State = TransferStates.Completed | TransferStates.Errored; + download.Exception = ApplicationShutdownTransferExceptionMessage; + await Transfers.Downloads.UpdateAsync(download); + })); + + // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in. + // we need to check the database before we re-request to make sure the user didn't remove them from the UI while + // the application was running, but before it was logged in. so just save the ids. + ActiveDownloadIdsAtPreviousShutdown = activeDownloads.Select(d => d.Id); + Log.Debug("Downloads to resume upon connection: {Ids}", ActiveDownloadIdsAtPreviousShutdown.ToJson()); + + Log.Debug("Configuring client"); ProxyOptions proxyOptions = default; @@ -290,15 +347,15 @@ namespace slskd userInfoResolver: UserInfoResolver, browseResponseResolver: BrowseResponseResolver, directoryContentsResolver: DirectoryContentsResponseResolver, - enqueueDownload: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + enqueueDownload: (username, endpoint, filename) => Transfers.Uploads.EnqueueAsync(username, filename), searchResponseCache: new SearchResponseCache(), searchResponseResolver: SearchResponseResolver, placeInQueueResolver: PlaceInQueueResolver); await Client.ReconfigureOptionsAsync(patch); - Log.Information("Client configured"); - Log.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); + Log.Debug("Client configured"); + Log.Information("Listening for incoming connections on port {Port}", OptionsAtStartup.Soulseek.ListenPort); if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { @@ -335,6 +392,8 @@ namespace slskd Task IHostedService.StopAsync(CancellationToken cancellationToken) { + ShuttingDown = true; + Log.Warning("Application is shutting down"); Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); Client.Dispose(); Log.Information("Client stopped"); @@ -368,7 +427,7 @@ namespace slskd BrowseTracker.AddOrUpdate(args.Username, args); } - private void Client_Connected(object sender, EventArgs e) + private async void Client_Connected(object sender, EventArgs e) { ConnectionWatchdog.Stop(); Log.Information("Connected to the Soulseek server"); @@ -451,16 +510,54 @@ namespace slskd } } - private void Client_LoggedIn(object sender, EventArgs e) + private async void Client_LoggedIn(object sender, EventArgs e) { Log.Information("Logged in to the Soulseek server as {Username}", Client.Username); - // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero - // initially, but we'll update them when the cache is filled. - _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); + try + { + // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero + // initially, but we'll update them when the cache is filled. + await Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); + + // fetch our average upload speed from the server, so we can provide it along with search results + await RefreshUserStatistics(force: true); + + // we previously saved a list of all of the download ids that were active at the previous shutdown; fetch the latest + // record for those transfers from the db and ensure they haven't been removed from the UI while the application was offline + // the user doesn't want those transfers anymore and we don't want to add them back. + var resumeableDownloads = await Transfers.Downloads.ListAsync(t => !t.Removed && ActiveDownloadIdsAtPreviousShutdown.Contains(t.Id)); + + if (resumeableDownloads.Any()) + { + Log.Information("Attempting to re-enqueue previously active downloads..."); - // fetch our average upload speed from the server, so we can provide it along with search results - _ = RefreshUserStatistics(force: true); + var groups = resumeableDownloads.GroupBy(d => d.Username); + + // re-request downloads. we use a try/catch here because there's a very good chance that the other user is offline. + foreach (var group in groups) + { + var username = group.Key; + var files = group.Select(f => (f.Filename, f.Size)); + + try + { + await Transfers.Downloads.EnqueueAsync(username, files); + } + catch (Exception ex) + { + Log.Warning("Failed to re-enqueue {Count} file(s) from {Username}: {Message}", files.Count(), username, ex.Message); + } + } + } + + // clear the ids we saved at startup; we don't want to re-request these again if the connection is cycled + ActiveDownloadIdsAtPreviousShutdown = Enumerable.Empty<Guid>(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute post-login actions"); + } } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -599,99 +696,6 @@ namespace slskd } } - /// <summary> - /// Invoked upon a remote request to download a file. - /// </summary> - /// <param name="username">The username of the requesting user.</param> - /// <param name="endpoint">The IP endpoint of the requesting user.</param> - /// <param name="filename">The filename of the requested file.</param> - /// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param> - /// <returns>A Task representing the asynchronous operation.</returns> - /// <exception cref="DownloadEnqueueException"> - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// </exception> - /// <exception cref="Exception"> - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// </exception> - private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - // remote clients might sometimes re-request downloads to check the status. don't try to add the download again - // if it is already tracked. - if (tracker.Contains(TransferDirection.Upload, username, filename)) - { - return; - } - - try - { - _ = endpoint; - string localFilename; - FileInfo fileInfo = default; - - Log.Information("[{Context}] {Username} requested {Filename}]", "UPLOAD REQUESTED", username, filename); - - try - { - localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); - - fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - throw new NotFoundException(); - } - } - catch (NotFoundException) - { - Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename); - throw new DownloadEnqueueException($"File not shared."); - } - - // create a new cancellation token source so that we can cancel the upload from the UI. - var cts = new CancellationTokenSource(); - var topts = new TransferOptions( - stateChanged: (e) => - { - tracker.AddOrUpdate(e.Transfer, cts); - - if (e.Transfer.State.HasFlag(TransferStates.Queued)) - { - Transfers.Uploads.Queue.Enqueue(e.Transfer); - } - }, - progressUpdated: (e) => tracker.AddOrUpdate(e.Transfer, cts), - governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx, req, ct), - reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx, att, grant, act), - slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx), - slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx)); - - // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and - // uploads would be handled separately. - _ = Task.Run(async () => - { - // users with uploads must be watched so that we can keep informed of their - // online status, privileges, and statistics. this is so that we can accurately - // determine their effective group. - if (!Users.IsWatched(username)) - { - await Users.WatchAsync(username); - } - - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => - { - Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); - }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to enqueue upload: {Message}", ex.Message); - throw; - } - } - private async Task OptionsMonitor_OnChange(Options newOptions) { // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently. diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f11132b4..5ed6bf80 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Logging; + namespace slskd { using System; @@ -60,6 +62,8 @@ namespace slskd using slskd.Search.API; using slskd.Shares; using slskd.Transfers; + using slskd.Transfers.Downloads; + using slskd.Transfers.Uploads; using slskd.Users; using slskd.Validation; using Soulseek; @@ -449,8 +453,8 @@ namespace slskd services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>(); services.AddDbContext<SearchDbContext>("search.db"); + services.AddDbContext<TransfersDbContext>("transfers.db"); - services.AddSingleton<ITransferTracker, TransferTracker>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); @@ -460,7 +464,10 @@ namespace slskd services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IUserService, UserService>(); services.AddSingleton<IRoomService, RoomService>(); + services.AddSingleton<ITransferService, TransferService>(); + services.AddSingleton<IDownloadService, DownloadService>(); + services.AddSingleton<IUploadService, UploadService>(); services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddSingleton<IFTPService, FTPService>(); @@ -785,13 +792,19 @@ namespace slskd private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string filename) where T : DbContext { - Log.Debug($"Initializing database context {typeof(T).Name}"); + Log.Debug("Initializing database context {Name}", typeof(T).Name); try { - services.AddDbContextFactory<SearchDbContext>(options => + services.AddDbContextFactory<T>(options => { options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + + // tweak this to enable Entity Framework SQL logging + if (OptionsAtStartup.Debug && false) + { + options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())); + } }); using var ctx = services diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs index 9a45280b..4fe15fae 100644 --- a/src/slskd/Search/ISearchService.cs +++ b/src/slskd/Search/ISearchService.cs @@ -21,9 +21,7 @@ namespace slskd.Search using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; - using SearchOptions = Soulseek.SearchOptions; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; + using Soulseek; /// <summary> /// Handles the lifecycle and persistence of searches. @@ -31,16 +29,6 @@ namespace slskd.Search public interface ISearchService { /// <summary> - /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. - /// </summary> - /// <param name="id">A unique identifier for the search.</param> - /// <param name="query">The search query.</param> - /// <param name="scope">The search scope.</param> - /// <param name="options">Search options.</param> - /// <returns>The completed search.</returns> - Task<Search> StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - - /// <summary> /// Deletes the specified ssearch. /// </summary> /// <param name="search">The search to delete.</param> @@ -53,17 +41,27 @@ namespace slskd.Search /// <param name="expression">The expression to use to match searches.</param> /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> /// <returns>The found search, or default if not found.</returns> - /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception> + /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false); /// <summary> - /// Returns a list of all completed and in-progress searches, with responses omitted. + /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional <paramref name="expression"/>. /// </summary> /// <param name="expression">An optional expression used to match searches.</param> - /// <returns>The list of searches matching the specified expression.</returns> + /// <returns>The list of searches matching the specified expression, or all searches if no expression is specified.</returns> Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null); /// <summary> + /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. + /// </summary> + /// <param name="id">A unique identifier for the search.</param> + /// <param name="query">The search query.</param> + /// <param name="scope">The search scope.</param> + /// <param name="options">Search options.</param> + /// <returns>The completed search.</returns> + Task<Search> StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + + /// <summary> /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. /// </summary> /// <param name="id">The unique identifier for the search.</param> diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 12c75fb1..2f71c733 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -70,6 +70,75 @@ namespace slskd.Search private IHubContext<SearchHub> SearchHub { get; set; } /// <summary> + /// Deletes the specified ssearch. + /// </summary> + /// <param name="search">The search to delete.</param> + /// <returns>The operation context.</returns> + public Task DeleteAsync(Search search) + { + if (search == default) + { + throw new ArgumentNullException(nameof(search)); + } + + return DoDeleteAsync(search); + + async Task DoDeleteAsync(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); + } + } + + /// <summary> + /// Finds a single search matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match searches.</param> + /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> + /// <returns>The found search, or default if not found.</returns> + /// <exception cref="ArgumentException">Thrown when an expression is not supplied.</exception> + public Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + var selector = context.Searches + .AsNoTracking() + .Where(expression); + + if (!includeResponses) + { + selector = selector.WithoutResponses(); + } + + return selector.FirstOrDefaultAsync(); + } + + /// <summary> + /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to match searches.</param> + /// <returns>The list of searches matching the specified expression, or all searches if no expression is specified.</returns> + public Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null) + { + expression ??= s => true; + using var context = ContextFactory.CreateDbContext(); + + return context.Searches + .AsNoTracking() + .Where(expression) + .WithoutResponses() + .ToListAsync(); + } + + /// <summary> /// Performs a search for the specified <paramref name="query"/> and <paramref name="scope"/>. /// </summary> /// <param name="id">A unique identifier for the search.</param> @@ -117,10 +186,9 @@ namespace slskd.Search }, responseReceived: (args) => rateLimiter.Invoke(() => { - // note: this is rate limited, but has the potential to update - // the database every 250ms (or whatever the interval is set to) - // for the duration of the search. any issues with disk i/o or performance - // while searches are running should investigate this as a cause + // note: this is rate limited, but has the potential to update the database every 250ms (or whatever the + // interval is set to) for the duration of the search. any issues with disk i/o or performance while searches + // are running should investigate this as a cause search.ResponseCount = args.Search.ResponseCount; search.FileCount = args.Search.FileCount; search.LockedFileCount = args.Search.LockedFileCount; @@ -174,68 +242,6 @@ namespace slskd.Search } /// <summary> - /// Deletes the specified ssearch. - /// </summary> - /// <param name="search">The search to delete.</param> - /// <returns>The operation context.</returns> - public Task DeleteAsync(Search search) - { - if (search == default) - { - throw new ArgumentNullException(nameof(search)); - } - - return DoDeleteAsync(search); - - async Task DoDeleteAsync(Search search) - { - using var context = ContextFactory.CreateDbContext(); - context.Searches.Remove(search); - await context.SaveChangesAsync(); - - await SearchHub.BroadcastDeleteAsync(search); - } - } - - /// <summary> - /// Finds a single search matching the specified <paramref name="expression"/>. - /// </summary> - /// <param name="expression">The expression to use to match searches.</param> - /// <param name="includeResponses">A value indicating whether to include search responses in the result.</param> - /// <returns>The found search, or default if not found.</returns> - /// <exception cref="ArgumentException">Thrown an expression is not supplied.</exception> - public Task<Search> FindAsync(Expression<Func<Search, bool>> expression, bool includeResponses = false) - { - if (expression == default) - { - throw new ArgumentException("An expression must be supplied.", nameof(expression)); - } - - using var context = ContextFactory.CreateDbContext(); - - var selector = context.Searches.Where(expression); - - if (!includeResponses) - { - selector = selector.WithoutResponses(); - } - - return selector.FirstOrDefaultAsync(); - } - - /// <summary> - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// </summary> - /// <param name="expression">An optional expression used to match searches.</param> - /// <returns>The list of searches matching the specified expression.</returns> - public Task<List<Search>> ListAsync(Expression<Func<Search, bool>> expression = null) - { - expression ??= s => true; - using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); - } - - /// <summary> /// Cancels the search matching the specified <paramref name="id"/>, if it is in progress. /// </summary> /// <param name="id">The unique identifier for the search.</param> diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index d3dd5518..d12a3f89 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -15,22 +15,15 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -using Microsoft.Extensions.Options; - 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; - using Serilog; - using slskd.Integrations.FTP; - using Soulseek; /// <summary> /// Transfers. @@ -45,27 +38,14 @@ namespace slskd.Transfers.API /// <summary> /// Initializes a new instance of the <see cref="TransfersController"/> class. /// </summary> - /// <param name="options"></param> - /// <param name="soulseekClient"></param> - /// <param name="tracker"></param> - /// <param name="ftpClient"></param> + /// <param name="transferService"></param> public TransfersController( - IOptionsSnapshot<Options> options, - ISoulseekClient soulseekClient, - ITransferTracker tracker, - IFTPService ftpClient) + ITransferService transferService) { - Client = soulseekClient; - Tracker = tracker; - Options = options.Value; - FTP = ftpClient; + Transfers = transferService; } - private Options Options { get; } - private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } - private IFTPService FTP { get; } - private ILogger Log { get; } = Serilog.Log.ForContext<TransfersController>(); + private ITransferService Transfers { get; } /// <summary> /// Cancels the specified download. @@ -80,9 +60,28 @@ 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<IActionResult> 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 + { + Transfers.Downloads.TryCancel(guid); + + if (remove) + { + await Transfers.Downloads.RemoveAsync(guid); + } + + return NoContent(); + } + catch (NotFoundException) + { + return NotFound(); + } } /// <summary> @@ -98,9 +97,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<IActionResult> 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(); + } } /// <summary> @@ -117,75 +135,15 @@ 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 { - 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<bool>(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<Exception>(); - 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); } } @@ -198,11 +156,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> @@ -214,12 +183,48 @@ 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) + { + 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); + } + + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> GetDownload([FromRoute, Required] string username, [FromRoute, Required] string id) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .FromUser(username) - .ToMap()); + 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); } /// <summary> @@ -231,21 +236,30 @@ namespace slskd.Transfers.API /// <returns></returns> /// <response code="200">The request completed successfully.</response> /// <response code="404">The specified download was not found.</response> - [HttpGet("downloads/{username}/{id}")] + [HttpGet("downloads/{username}/{id}/position")] [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) { - 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); + } } /// <summary> @@ -256,11 +270,22 @@ namespace slskd.Transfers.API [HttpGet("uploads")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads() + public async Task<IActionResult> 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); } /// <summary> @@ -272,12 +297,27 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username) + public async Task<IActionResult> 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); } /// <summary> @@ -290,62 +330,21 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) + public async Task<IActionResult> GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .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)) + if (!Guid.TryParse(id, out var guid)) { - System.IO.Directory.CreateDirectory(path); + return BadRequest(); } - 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); + var upload = await Transfers.Uploads.FindAsync(t => t.Id == guid); - if (!System.IO.Directory.Exists(destinationPath)) + if (upload == default) { - 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)) - { - transfer.CancellationTokenSource.Cancel(); - - if (remove) - { - Tracker.TryRemove(direction, username, id); - } - - return NoContent(); + return NotFound(); } - return NotFound(); + return Ok(upload); } } }
\ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs new file mode 100644 index 00000000..1f8b1df9 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs @@ -0,0 +1,28 @@ +// <copyright file="DirectoryResponse.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.API +{ + using System.Collections.Generic; + + public record DirectoryResponse + { + public string Name { get; init; } + public int FileCount { get; init; } + public IEnumerable<Transfers.Transfer> Files { get; init; } + } +} diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs index 5e8807c2..62e6316c 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs @@ -27,11 +27,6 @@ namespace slskd.Transfers.API /// <summary> /// Gets or sets the size of the file. /// </summary> - public long? Size { get; set; } - - /// <summary> - /// Gets or sets the optional transfer token. - /// </summary> - public int? Token { get; set; } + public long Size { get; set; } } } diff --git a/src/slskd/Transfers/API/DTO/UserResponse.cs b/src/slskd/Transfers/API/DTO/UserResponse.cs new file mode 100644 index 00000000..92605161 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/UserResponse.cs @@ -0,0 +1,27 @@ +// <copyright file="UserResponse.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.API +{ + using System.Collections.Generic; + + public record UserResponse + { + public string Username { get; init; } + public IEnumerable<DirectoryResponse> Directories { get; init; } + } +} diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs new file mode 100644 index 00000000..b499baa4 --- /dev/null +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -0,0 +1,449 @@ +// <copyright file="DownloadService.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> + +using Microsoft.Extensions.Options; +using Soulseek; + +namespace slskd.Transfers.Downloads +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Linq.Expressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Serilog; + using slskd.Integrations.FTP; + + /// <summary> + /// Manages downloads. + /// </summary> + public class DownloadService : IDownloadService + { + public DownloadService( + IOptionsMonitor<Options> optionsMonitor, + ISoulseekClient soulseekClient, + IDbContextFactory<TransfersDbContext> contextFactory, + IFTPService ftpClient) + { + Client = soulseekClient; + OptionsMonitor = optionsMonitor; + ContextFactory = contextFactory; + FTP = ftpClient; + } + + private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); + private ISoulseekClient Client { get; } + private IDbContextFactory<TransfersDbContext> ContextFactory { get; } + private IFTPService FTP { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } + + /// <summary> + /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. + /// </summary> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, IEnumerable(string Filename, long Size)})"/> instead.</remarks> + /// <param name="transfer"></param> + /// <returns></returns> + public async Task AddOrSupersedeAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + + var existing = await context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename == transfer.Filename) + .Where(t => !t.Removed) + .FirstOrDefaultAsync(); + + if (existing != default) + { + Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username); + existing.Removed = true; + } + + context.Add(transfer); + await context.SaveChangesAsync(); + } + + /// <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 remote 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 Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentException("Username is required", nameof(username)); + } + + if (!files.Any()) + { + throw new ArgumentException("At least one file is require", nameof(files)); + } + + return EnqueueAsyncInternal(username, files); + + async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + { + try + { + Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + + Log.Debug("Priming connection for user {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false); + Log.Debug("Connection for user '{Username}' primed", username); + + 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 + await AddOrSupersedeAsync(transfer); + + var cts = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cts); + + var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + + // 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); + + 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 (Application.IsShuttingDown) + { + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAsync(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 + _ = UpdateAsync(transfer); + }))); + + transfer = transfer.WithSoulseekTransfer(completedTransfer); + // todo: broadcast + await UpdateAsync(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)); + } + } + catch (Exception ex) when (ex is not TaskCanceledException) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); + throw; + } + 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); + + // 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; + + // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? + if (ex is AggregateException aggEx) + { + 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); + } + + // todo: broadcast + await UpdateAsync(transfer); + } + + if (thrownExceptions.Any()) + { + throw new AggregateException(thrownExceptions); + } + + Log.Information("Successfully enqueued {Count} file(s) 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 + { + using var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(expression).FirstOrDefaultAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find download: {Message}", ex.Message); + throw; + } + } + + /// <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 + { + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers.FindAsync(id); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + + transfer.PlaceInQueue = place; + await context.SaveChangesAsync(); + + return place; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); + throw; + } + } + + /// <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 + { + using var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToListAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); + throw; + } + } + + /// <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 + { + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Id == id) + .FirstOrDefaultAsync(); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); + } + + transfer.Removed = true; + + await context.SaveChangesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + throw; + } + } + + /// <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; + } + + /// <summary> + /// Updates the specified <paramref name="transfer"/>. + /// </summary> + /// <param name="transfer">The transfer to update.</param> + /// <returns>The operation context.</returns> + public async Task UpdateAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); + } + + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + { + var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); + var path = Path.GetDirectoryName(localFilename); + + if (!Directory.Exists(path)) + { + 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 (!Directory.Exists(destinationPath)) + { + Directory.CreateDirectory(destinationPath); + } + + File.Move(sourceFilename, destinationFilename, overwrite: true); + + if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + } + } +}
\ 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..1c1d8202 --- /dev/null +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -0,0 +1,97 @@ +// <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> + /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. + /// </summary> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, IEnumerable(string Filename, long Size)})"/> instead.</remarks> + /// <param name="transfer"></param> + /// <returns></returns> + Task AddOrSupersedeAsync(Transfer transfer); + + /// <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 remote 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); + + /// <summary> + /// Updates the specified <paramref name="transfer"/>. + /// </summary> + /// <param name="transfer">The transfer to update.</param> + /// <returns>The operation context.</returns> + Task UpdateAsync(Transfer transfer); + } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs new file mode 100644 index 00000000..7ec1b55c --- /dev/null +++ b/src/slskd/Transfers/Extensions.cs @@ -0,0 +1,43 @@ +// <copyright file="Extensions.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 +{ + public static class Extensions + { + public static Transfer WithSoulseekTransfer(this Transfer transfer, Soulseek.Transfer t) + { + return new Transfer() + { + Id = transfer.Id, + Username = transfer.Username, + Direction = transfer.Direction, + Filename = transfer.Filename, + Size = transfer.Size, + StartOffset = t.StartOffset, + State = t.State, + RequestedAt = transfer.RequestedAt, + EnqueuedAt = transfer.EnqueuedAt, + StartedAt = t.StartTime, + EndedAt = t.EndTime, + BytesTransferred = t.BytesTransferred, + AverageSpeed = t.AverageSpeed, + Exception = t.Exception?.Message, + }; + } + } +} diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs deleted file mode 100644 index fabcf856..00000000 --- a/src/slskd/Transfers/ITransferTracker.cs +++ /dev/null @@ -1,66 +0,0 @@ -// <copyright file="ITransferTracker.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 -{ - using System.Collections.Concurrent; - using System.Threading; - using Soulseek; - - /// <summary> - /// Tracks transfers. - /// </summary> - public interface ITransferTracker - { - /// <summary> - /// Tracked transfers. - /// </summary> - ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; } - - /// <summary> - /// Adds or updates a tracked transfer. - /// </summary> - /// <param name="transfer"></param> - /// <param name="cancellationTokenSource"></param> - void AddOrUpdate(Transfer transfer, CancellationTokenSource cancellationTokenSource); - - /// <summary> - /// Removes a tracked transfer. - /// </summary> - /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks> - void TryRemove(TransferDirection direction, string username, string id = null); - - /// <summary> - /// Gets the specified transfer. - /// </summary> - /// <param name="direction"></param> - /// <param name="username"></param> - /// <param name="id"></param> - /// <param name="transfer"></param> - /// <returns></returns> - bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); - - /// <summary> - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// </summary> - /// <param name="direction"></param> - /// <param name="username"></param> - /// <param name="filename"></param> - /// <returns></returns> - bool Contains(TransferDirection direction, string username, string filename); - } -}
\ No newline at end of file diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 714d85be..20b9b8e3 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -15,12 +15,10 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -using Microsoft.Extensions.Options; - namespace slskd.Transfers { + using slskd.Transfers.Downloads; using slskd.Transfers.Uploads; - using slskd.Users; /// <summary> /// Manages transfers. @@ -31,6 +29,11 @@ namespace slskd.Transfers /// Gets the upload service. /// </summary> IUploadService Uploads { get; } + + /// <summary> + /// Gets the download service. + /// </summary> + IDownloadService Downloads { get; } } /// <summary> @@ -41,22 +44,12 @@ namespace slskd.Transfers /// <summary> /// Initializes a new instance of the <see cref="TransferService"/> class. /// </summary> - /// <param name="userService">The UserService instance to use.</param> - /// <param name="optionsMonitor">The OptionsMonitor instance to use.</param> - /// <param name="uploadService">The optional UploadService instance to use.</param> public TransferService( - IUserService userService, - IOptionsMonitor<Options> optionsMonitor, - IUploadService uploadService = null) + IUploadService uploadService = null, + IDownloadService downloadService = null) { - Users = userService; - OptionsMonitor = optionsMonitor; - - Uploads = uploadService ?? new UploadService() - { - Governor = new UploadGovernor(userService: Users, optionsMonitor: OptionsMonitor), - Queue = new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor), - }; + Uploads = uploadService; + Downloads = downloadService; } /// <summary> @@ -64,7 +57,9 @@ namespace slskd.Transfers /// </summary> public IUploadService Uploads { get; init; } - private IOptionsMonitor<Options> OptionsMonitor { get; init; } - private IUserService Users { get; init; } + /// <summary> + /// Gets the download service. + /// </summary> + public IDownloadService Downloads { get; init; } } }
\ No newline at end of file diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs deleted file mode 100644 index 522da0fe..00000000 --- a/src/slskd/Transfers/TransferTracker.cs +++ /dev/null @@ -1,212 +0,0 @@ -// <copyright file="TransferTracker.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 -{ - using System.Collections.Concurrent; - using System.Linq; - using System.Threading; - using Soulseek; - - /// <summary> - /// Transfer extensions. - /// </summary> - public static class TransferTrackerExtensions - { - /// <summary> - /// Filters a Transfer collection by user. - /// </summary> - /// <param name="directedTransfers"></param> - /// <param name="username"></param> - /// <returns></returns> - public static ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser( - this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers, - string username) - { - directedTransfers.TryGetValue(username, out var transfers); - return transfers ?? new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>(); - } - - /// <summary> - /// Maps a Transfer collection to a serializable object. - /// </summary> - /// <param name="directedTransfers"></param> - /// <returns></returns> - public static object ToMap( - this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers) - { - return directedTransfers.Select(u => new - { - Username = u.Key, - Directories = u.Value.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), - }); - } - - /// <summary> - /// Maps a Transfer collection to a serializable object. - /// </summary> - /// <param name="userTransfers"></param> - /// <returns></returns> - public static object ToMap( - this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers) - { - return userTransfers.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); - } - - /// <summary> - /// Filters a Transfer collection by direction. - /// </summary> - /// <param name="allTransfers"></param> - /// <param name="direction"></param> - /// <returns></returns> - public static ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection( - this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers, - TransferDirection direction) - { - allTransfers.TryGetValue(direction, out var transfers); - return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>(); - } - - /// <summary> - /// Retrieves a Transfer from a Transfer collection by id. - /// </summary> - /// <param name="userTransfers"></param> - /// <param name="id"></param> - /// <returns></returns> - public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( - this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers, - string id) - { - userTransfers.TryGetValue(id, out var transfer); - return transfer; - } - } - - /// <summary> - /// Tracks transfers. - /// </summary> - public class TransferTracker : ITransferTracker - { - /// <summary> - /// Initializes a new instance of the <see cref="TransferTracker"/> class. - /// </summary> - public TransferTracker() - { - Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>()); - Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>()); - } - - /// <summary> - /// Gets tracked transfers. - /// </summary> - public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } = - new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer, CancellationTokenSource)>>>(); - - /// <summary> - /// Adds or updates a tracked transfer. - /// </summary> - /// <param name="transfer"></param> - /// <param name="cancellationTokenSource"></param> - public void AddOrUpdate(Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - Transfers.TryGetValue(transfer.Direction, out var direction); - - direction.AddOrUpdate(transfer.Username, GetNewDictionaryForUser(transfer, cancellationTokenSource), (user, dict) => - { - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - dict.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, cancellationTokenSource)); - return dict; - }); - } - - /// <summary> - /// Gets the specified transfer. - /// </summary> - /// <param name="direction"></param> - /// <param name="username"></param> - /// <param name="id"></param> - /// <param name="transfer"></param> - /// <returns></returns> - public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) - { - transfer = default; - - if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) - { - return true; - } - - return false; - } - - /// <summary> - /// Removes a tracked transfer. - /// </summary> - /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks> - public void TryRemove(TransferDirection direction, string username, string id = null) - { - Transfers.TryGetValue(direction, out var directionDict); - - if (string.IsNullOrEmpty(id)) - { - directionDict.TryRemove(username, out _); - } - else - { - directionDict.TryGetValue(username, out var userDict); - userDict.TryRemove(id, out _); - - if (userDict.IsEmpty) - { - directionDict.TryRemove(username, out _); - } - } - } - - /// <summary> - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// </summary> - /// <param name="direction"></param> - /// <param name="username"></param> - /// <param name="filename"></param> - /// <returns></returns> - public bool Contains(TransferDirection direction, string username, string filename) - { - if (Transfers.TryGetValue(direction, out var directionDict)) - { - if (directionDict.TryGetValue(username, out var userDict)) - { - return userDict.Values.Any(record => record.Transfer.Filename == filename); - } - } - - return false; - } - - private ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - var r = new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>(); - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - r.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, record.CancellationTokenSource)); - return r; - } - } -}
\ No newline at end of file diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs new file mode 100644 index 00000000..3b226016 --- /dev/null +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -0,0 +1,57 @@ +// <copyright file="TransfersDbContext.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 +{ + using System; + using Microsoft.EntityFrameworkCore; + using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + + public class TransfersDbContext : DbContext + { + public TransfersDbContext(DbContextOptions<TransfersDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<Transfer> Transfers { get; set;} + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity<Transfer>() + .Property(e => e.StartedAt) + .HasConversion(v => v, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : null); + + modelBuilder + .Entity<Transfer>() + .Property(e => e.EndedAt) + .HasConversion(v => v, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : null); + + modelBuilder + .Entity<Transfer>() + .Property(d => d.Direction) + .HasConversion(new EnumToStringConverter<Soulseek.TransferDirection>()); + + modelBuilder + .Entity<Transfer>() + .Property(d => d.State) + .HasConversion(new EnumToStringConverter<Soulseek.TransferStates>()); + } + } +} diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs new file mode 100644 index 00000000..c55826d4 --- /dev/null +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -0,0 +1,59 @@ +// <copyright file="Transfer.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 +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json.Serialization; + using Soulseek; + + public class Transfer + { + [Key] + public Guid Id { get; init; } + public string Username { get; init; } + public TransferDirection Direction { get; init; } + public string Filename { get; init; } + public long Size { get; set; } + public long StartOffset { get; init; } + + public TransferStates State { get; set; } + public DateTime RequestedAt { get; set; } + public DateTime? EnqueuedAt { get; set; } + public DateTime? StartedAt { get; set; } + public DateTime? EndedAt { get; set; } + public long BytesTransferred { get; set; } + public double AverageSpeed { get; set; } + + public int? PlaceInQueue { get; set; } + public string Exception { get; set; } + + [JsonIgnore] + public bool Removed { get; set; } + + [NotMapped] + public long BytesRemaining => Size - BytesTransferred; + [NotMapped] + public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + [NotMapped] + public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); + } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs new file mode 100644 index 00000000..b902f20c --- /dev/null +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -0,0 +1,100 @@ +// <copyright file="IUploadService.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.Uploads +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + + /// <summary> + /// Manages uploads. + /// </summary> + public interface IUploadService + { + /// <summary> + /// Gets the upload governor. + /// </summary> + IUploadGovernor Governor { get; } + + /// <summary> + /// Gets the upload queue. + /// </summary> + IUploadQueue Queue { get; } + + /// <summary> + /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. + /// </summary> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <param name="transfer"></param> + /// <returns></returns> + Task AddOrSupersedeAsync(Transfer transfer); + + /// <summary> + /// Enqueues the requested file. + /// </summary> + /// <param name="username">The username of the requesting user.</param> + /// <param name="filename">The local filename of the requested file.</param> + /// <returns>The operation context.</returns> + Task EnqueueAsync(string username, string filename); + + /// <summary> + /// Returns a value indicating whether an upload matching the specified <paramref name="expression"/> exists. + /// </summary> + /// <param name="expression">The expression used to match uploads.</param> + /// <returns>A value indicating whether an upload matching the specified expression exists.</returns> + Task<bool> ExistsAsync(Expression<Func<Transfer, bool>> expression); + + /// <summary> + /// Finds a single upload matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match uploads.</param> + /// <returns>The found transfer, or default if not found.</returns> + Task<Transfer> FindAsync(Expression<Func<Transfer, bool>> expression); + + /// <summary> + /// Returns a list of all uploads matching the optional <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to match uploads.</param> + /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param> + /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns> + Task<List<Transfer>> ListAsync(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false); + + /// <summary> + /// Removes the upload 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 upload.</param> + /// <returns></returns> + Task RemoveAsync(Guid id); + + /// <summary> + /// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress. + /// </summary> + /// <param name="id">The unique identifier for the upload.</param> + /// <returns>A value indicating whether the upload was successfully cancelled.</returns> + bool TryCancel(Guid id); + + /// <summary> + /// Updates the specified <paramref name="transfer"/>. + /// </summary> + /// <param name="transfer">The transfer to update.</param> + /// <returns>The operation context.</returns> + Task UpdateAsync(Transfer transfer); + } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index a806815f..0f481e69 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -24,7 +24,6 @@ namespace slskd.Transfers using System.Threading; using System.Threading.Tasks; using slskd.Users; - using Soulseek; /// <summary> /// Governs upload transfer speed. @@ -32,26 +31,26 @@ namespace slskd.Transfers public interface IUploadGovernor { /// <summary> - /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the specified <paramref name="transfer"/>. + /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the requesting <paramref name="username"/>. /// </summary> /// <remarks> /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the /// requested amount. /// </remarks> - /// <param name="transfer">The transfer for which the grant is requested.</param> + /// <param name="username">The username of the requesting user.</param> /// <param name="requestedBytes">The number of requested bytes.</param> /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context, including the number of bytes granted.</returns> - Task<int> GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + Task<int> GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken); /// <summary> /// Returns wasted bytes for redistribution. /// </summary> - /// <param name="transfer">The transfer which generated the waste.</param> + /// <param name="username">The username of the user that generated the waste.</param> /// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param> /// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param> /// <param name="actualBytes">The actual number of bytes transferred.</param> - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes); } /// <summary> @@ -83,19 +82,19 @@ namespace slskd.Transfers private IUserService Users { get; } /// <summary> - /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the specified <paramref name="transfer"/>. + /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the requesting <paramref name="username"/>. /// </summary> /// <remarks> /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the /// requested amount. /// </remarks> - /// <param name="transfer">The transfer for which the grant is requested.</param> + /// <param name="username">The username of the requesting user.</param> /// <param name="requestedBytes">The number of requested bytes.</param> /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context, including the number of bytes granted.</returns> - public Task<int> GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + public Task<int> GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken) { - var group = Users.GetGroup(transfer.Username); + var group = Users.GetGroup(username); var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); return bucket.GetAsync(requestedBytes, cancellationToken); @@ -104,11 +103,11 @@ namespace slskd.Transfers /// <summary> /// Returns wasted bytes for redistribution. /// </summary> - /// <param name="transfer">The transfer which generated the waste.</param> + /// <param name="username">The username of the user that generated the waste.</param> /// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param> /// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param> /// <param name="actualBytes">The actual number of bytes transferred.</param> - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes) { var waste = Math.Max(0, grantedBytes - actualBytes); @@ -117,7 +116,7 @@ namespace slskd.Transfers return; } - var group = Users.GetGroup(transfer.Username); + var group = Users.GetGroup(username); var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); // we don't have enough information to tell whether grantedBytes was reduced by the global limiter within diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index f694a887..9ac6b385 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -28,7 +28,6 @@ namespace slskd.Transfers using System.Threading.Tasks; using Serilog; using slskd.Users; - using Soulseek; /// <summary> /// Orchestrates uploads. @@ -38,21 +37,24 @@ namespace slskd.Transfers /// <summary> /// Awaits the start of an upload. /// </summary> - /// <param name="transfer">The upload for which to wait.</param> + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The filename for which to await the start.</param> /// <returns>The operation context.</returns> - Task AwaitStartAsync(Transfer transfer); + Task AwaitStartAsync(string username, string filename); /// <summary> /// Signals the completion of an upload. /// </summary> - /// <param name="transfer">The completed upload.</param> - void Complete(Transfer transfer); + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The completed filename.</param> + void Complete(string username, string filename); /// <summary> /// Enqueues an upload. /// </summary> - /// <param name="transfer">The upload to enqueue.</param> - void Enqueue(Transfer transfer); + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The filename to enqueue.</param> + void Enqueue(string username, string filename); /// <summary> /// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>. @@ -109,24 +111,25 @@ namespace slskd.Transfers /// <summary> /// Awaits the start of an upload. /// </summary> - /// <param name="transfer">The upload for which to wait.</param> + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The filename for which to await the start.</param> /// <returns>The operation context.</returns> - public Task AwaitStartAsync(Transfer transfer) + public Task AwaitStartAsync(string username, string filename) { SyncRoot.Wait(); try { - if (!Uploads.TryGetValue(transfer.Username, out var list)) + if (!Uploads.TryGetValue(username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + throw new SlskdException($"No enqueued uploads for user {username}"); } - var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == filename); if (upload == default) { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + throw new SlskdException($"File {filename} is not enqueued for user {username}"); } upload.Ready = DateTime.UtcNow; @@ -144,23 +147,24 @@ namespace slskd.Transfers /// <summary> /// Signals the completion of an upload. /// </summary> - /// <param name="transfer">The completed upload.</param> - public void Complete(Transfer transfer) + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The completed filename.</param> + public void Complete(string username, string filename) { SyncRoot.Wait(); try { - if (!Uploads.TryGetValue(transfer.Username, out var list)) + if (!Uploads.TryGetValue(username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + throw new SlskdException($"No enqueued uploads for user {username}"); } - var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == filename); if (upload == default) { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + throw new SlskdException($"File {filename} is not enqueued for user {username}"); } list.Remove(upload); @@ -176,9 +180,9 @@ namespace slskd.Transfers Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); } - if (!list.Any() && Uploads.TryRemove(transfer.Username, out _)) + if (!list.Any() && Uploads.TryRemove(username, out _)) { - Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", transfer.Username); + Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", username); } } finally @@ -191,17 +195,18 @@ namespace slskd.Transfers /// <summary> /// Enqueues an upload. /// </summary> - /// <param name="transfer">The upload to enqueue.</param> - public void Enqueue(Transfer transfer) + /// <param name="username">The username of the remote user.</param> + /// <param name="filename">The filename to enqueue.</param> + public void Enqueue(string username, string filename) { SyncRoot.Wait(); try { - var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; + var upload = new Upload() { Username = username, Filename = filename }; Uploads.AddOrUpdate( - key: transfer.Username, + key: username, addValue: new List<Upload>(new[] { upload }), updateValueFactory: (key, list) => { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index f88e80a8..4dc6e30d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -15,37 +15,334 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; +using Soulseek; + namespace slskd.Transfers.Uploads { + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Linq.Expressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Serilog; + using slskd.Shares; + using slskd.Users; + /// <summary> /// Manages uploads. /// </summary> - public interface IUploadService + public class UploadService : IUploadService { + public UploadService( + IUserService userService, + ISoulseekClient soulseekClient, + IOptionsMonitor<Options> optionsMonitor, + IShareService shareService, + IDbContextFactory<TransfersDbContext> contextFactory) + { + Users = userService; + Client = soulseekClient; + Shares = shareService; + ContextFactory = contextFactory; + + Governor = new UploadGovernor(userService, optionsMonitor); + Queue = new UploadQueue(userService, optionsMonitor); + } + /// <summary> /// Gets the upload governor. /// </summary> - IUploadGovernor Governor { get; } + public IUploadGovernor Governor { get; init; } /// <summary> /// Gets the upload queue. /// </summary> - IUploadQueue Queue { get; } - } + public IUploadQueue Queue { get; init; } + + private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); + private ISoulseekClient Client { get; set; } + private IDbContextFactory<TransfersDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<UploadService>(); + private IShareService Shares { get; set; } + private IUserService Users { get; set; } - /// <summary> - /// Manages uploads. - /// </summary> - public class UploadService : IUploadService - { /// <summary> - /// Gets the upload governor. + /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> - public IUploadGovernor Governor { get; init; } + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <param name="transfer"></param> + /// <returns></returns> + public async Task AddOrSupersedeAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + + var existing = await context.Transfers + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename == transfer.Filename) + .Where(t => !t.Removed) + .FirstOrDefaultAsync(); + + if (existing != default) + { + Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username); + existing.Removed = true; + } + + context.Add(transfer); + await context.SaveChangesAsync(); + } /// <summary> - /// Gets the upload queue. + /// Enqueues the requested file. /// </summary> - public IUploadQueue Queue { get; init; } + /// <param name="username">The username of the requesting user.</param> + /// <param name="filename">The local filename of the requested file.</param> + /// <returns>The operation context.</returns> + public async Task EnqueueAsync(string username, string filename) + { + // remote clients might sometimes re-request downloads to check the status. don't try to add the download again if it + // is already tracked. + if (await ExistsAsync(t => t.Username == username && t.Filename == filename)) + { + return; + } + + string localFilename; + FileInfo fileInfo = default; + + Log.Information("[{Context}] {Username} requested {Filename}]", "UPLOAD REQUESTED", username, filename); + + try + { + localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + + fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + throw new NotFoundException(); + } + } + catch (NotFoundException) + { + Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename); + throw new DownloadEnqueueException($"File not shared."); + } + + var id = Guid.NewGuid(); + + var transfer = new Transfer() + { + Id = id, + Username = username, + Direction = TransferDirection.Upload, + Filename = localFilename, + Size = fileInfo.Length, + StartOffset = 0, // potentially updated later during handshaking + RequestedAt = DateTime.UtcNow, + EnqueuedAt = DateTime.UtcNow, + }; + + // persist the transfer to the database so we have a record that it was attempted + await AddOrSupersedeAsync(transfer); + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cts); + + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. + _ = Task.Run(async () => + { + using var rateLimiter = new RateLimiter(250); + + try + { + var topts = new TransferOptions( + stateChanged: (args) => + { + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); + + if (Application.IsShuttingDown) + { + Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", filename, username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAsync(transfer); + + if (args.Transfer.State.HasFlag(TransferStates.Queued)) + { + Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAsync(transfer); + }), + governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), + reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), + slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), + slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + + // users with uploads must be watched so that we can keep informed of their online status, privileges, and + // statistics. this is so that we can accurately determine their effective group. + if (!Users.IsWatched(username)) + { + await Users.WatchAsync(username); + } + + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + var completedTransfer = await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); + + transfer = transfer.WithSoulseekTransfer(completedTransfer); + //todo: broadcast + await UpdateAsync(transfer); + } + catch (Exception ex) when (ex is not TaskCanceledException) + { + Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", filename, username, ex.Message); + throw; + } + finally + { + CancellationTokens.TryRemove(id, out _); + } + }); + } + + /// <summary> + /// Returns a value indicating whether an upload matching the specified <paramref name="expression"/> exists. + /// </summary> + /// <param name="expression">The expression used to match uploads.</param> + /// <returns>A value indicating whether an upload matching the specified expression exists.</returns> + public async Task<bool> ExistsAsync(Expression<Func<Transfer, bool>> expression) + { + return (await FindAsync(expression)) != default; + } + + /// <summary> + /// Finds a single upload matching the specified <paramref name="expression"/>. + /// </summary> + /// <param name="expression">The expression to use to match uploads.</param> + /// <returns>The found transfer, or default if not found.</returns> + public async Task<Transfer> FindAsync(Expression<Func<Transfer, bool>> expression) + { + try + { + using var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Upload) + .Where(expression).FirstOrDefaultAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find upload: {Message}", ex.Message); + throw; + } + } + + /// <summary> + /// Returns a list of all uploads matching the optional <paramref name="expression"/>. + /// </summary> + /// <param name="expression">An optional expression used to match uploads.</param> + /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param> + /// <returns>The list of uploads matching the specified expression, or all uploads 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 + { + using var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToListAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + throw; + } + } + + /// <summary> + /// Removes the upload 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 upload.</param> + /// <returns></returns> + public async Task RemoveAsync(Guid id) + { + try + { + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => t.Id == id) + .FirstOrDefaultAsync(); + + if (transfer == default) + { + throw new NotFoundException($"No upload matching id ${id}"); + } + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete"); + } + + transfer.Removed = true; + + await context.SaveChangesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, ex.Message); + throw; + } + } + + /// <summary> + /// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress. + /// </summary> + /// <param name="id">The unique identifier for the upload.</param> + /// <returns>A value indicating whether the upload was successfully cancelled.</returns> + public bool TryCancel(Guid id) + { + if (CancellationTokens.TryRemove(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + /// <summary> + /// Updates the specified <paramref name="transfer"/>. + /// </summary> + /// <param name="transfer">The transfer to update.</param> + /// <returns>The operation context.</returns> + public async Task UpdateAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); + } } -} +}
\ No newline at end of file diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js index e9d021e0..d78a0ee8 100644 --- a/src/web/src/lib/transfers.js +++ b/src/web/src/lib/transfers.js @@ -31,7 +31,7 @@ export const cancel = ({ direction, username, id, remove = false }) => { // 'Completed, Rejected' export const getPlaceInQueue = ({ username, id }) => { - return api.get(`/transfers/downloads/${username}/${id}`); + return api.get(`/transfers/downloads/${username}/${id}/position`); }; export const isStateRetryable = (state) => |
