From 8432e1395cbe4f5788dec579fbf0516f59847f34 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:07:06 -0500 Subject: stub DownloadService --- src/slskd/Transfers/Downloads/DownloadService.cs | 262 +++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 src/slskd/Transfers/Downloads/DownloadService.cs (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs new file mode 100644 index 00000000..bca7ca12 --- /dev/null +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -0,0 +1,262 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; +using Soulseek; + +namespace slskd.Transfers.Downloads +{ + using System; + 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; + + /// + /// Manages downloads. + /// + public interface IDownloadService + { + /// + /// Enqueues the requested list of . + /// + /// + /// If one file in the specified collection fails, the rest will continue. An will be thrown after all files are dispositioned if any throws. + /// + /// + /// + /// + /// + /// Thrown when at least one of the requested files throws. + Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + Task GetPlaceInQueueAsync(Guid id); + Task CancelAsync(Guid id); + Task RemoveAsync(Guid id, bool cancel = false); + Task FindAsync(Expression> expression); + Task> ListAsync(Expression> expression = null); + } + + /// + /// Manages downloads. + /// + public class DownloadService : IDownloadService + { + public DownloadService( + IOptionsSnapshot options, + ISoulseekClient soulseekClient, + ITransferTracker tracker, + IDbContextFactory contextFactory, + IFTPService ftpClient) + { + Client = soulseekClient; + Tracker = tracker; + Options = options.Value; + FTP = ftpClient; + } + + private IDbContextFactory ContextFactory { get; } + private Options Options { get; } + private ISoulseekClient Client { get; } + private ITransferTracker Tracker { get; } + private IFTPService FTP { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public Task CancelAsync(Guid id) + { + throw new NotImplementedException(); + } + + /// + /// Enqueues the requested list of . + /// + /// + /// If one file in the specified collection fails, the rest will continue. An will be thrown after all files are dispositioned if any throws. + /// + /// + /// + /// + /// Thrown when at least one of the requested files throws. + public async Task EnqueueAsync(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(); + + foreach (var file in files) + { + Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + + var transfer = new Transfer() + { + Id = Guid.NewGuid(), + Username = username, + Direction = TransferDirection.Download, + Filename = file.Filename, + Size = file.Size, + StartOffset = 0, + RequestedAt = DateTime.UtcNow, + }; + + using var context = ContextFactory.CreateDbContext(); + context.Add(transfer); + + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cts = new CancellationTokenSource(); + + var downloadTask = Task.Run(async () => + { + using var context = ContextFactory.CreateDbContext(); + using var rateLimiter = new RateLimiter(250); + + await Client.DownloadAsync(username, file.Filename, () => GetLocalFileStream(file.Filename, Options.Directories.Incomplete), file.Size, 0, token: null, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => + { + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, e.PreviousState, e.Transfer.State); + + transfer.UpdateFromSoulseekTransfer(e.Transfer); + + 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); + + // TODO: transfer is complete. make sure a final broadcast is sent + // TODO: save final state in db + + MoveFile(file.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + + if (Options.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(file.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); + + // the download task finished first, meaning the transfer was stopped before it was enqueued (and therefore threw) + 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(); + 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; + 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); + } + + await context.SaveChangesAsync(); + } + + if (thrownExceptions.Any()) + { + throw new AggregateException(thrownExceptions); + } + + Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); + throw; + } + } + + public Task FindAsync(Expression> expression) + { + throw new NotImplementedException(); + } + + public Task GetPlaceInQueueAsync(Guid id) + { + throw new NotImplementedException(); + } + + public Task> ListAsync(Expression> expression = null) + { + throw new NotImplementedException(); + } + + public Task RemoveAsync(Guid id, bool cancel = false) + { + throw new NotImplementedException(); + } + + 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)); + } + } + } +} -- cgit v1.2.3