diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-10-15 19:09:41 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-10-15 19:09:41 -0500 |
| commit | 8663b3fac9597f7b0c6ffd8081b99c761a18b326 (patch) | |
| tree | 6780fbd2e1b950f60f2bf7f57dcd963d853df50b /src | |
| parent | 7e34146d679b3b6c1692a41f1ea9ab4547889a43 (diff) | |
| download | slskd-8663b3fac9597f7b0c6ffd8081b99c761a18b326.tar.gz | |
add file info handling
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Network/API/Hubs/NetworkHub.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClient.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkService.cs | 141 |
3 files changed, 139 insertions, 43 deletions
diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 6d43e6da..f79fecf2 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -26,6 +26,7 @@ namespace slskd.Network public static class NetworkHubMethods { public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; @@ -41,6 +42,11 @@ namespace slskd.Network // todo: how to send this to the specified agent? return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); } + + public static Task RequestFileInfoAsync(this IHubContext<NetworkHub> hub, string agent, string filename, Guid id) + { + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + } } /// <summary> @@ -104,7 +110,15 @@ namespace slskd.Network { if (Network.PendingFileUploads.TryGetValue(id, out var record)) { - record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } + + public void ReturnFileInfo(Guid id, bool exists, long length) + { + if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + { + record.TrySetResult((exists, length)); } } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index d171e9b9..6e4e4dca 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -156,7 +156,7 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(Guid id, string filename) + private async Task HandleFileRequest(string filename, Guid id) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -164,7 +164,7 @@ namespace slskd.Network { var localFilename = await Shares.ResolveFileAsync(filename); - var localFileInfo = new FileInfo(filename); + var localFileInfo = new FileInfo(localFilename); if (!localFileInfo.Exists) { @@ -202,6 +202,25 @@ namespace slskd.Network } } + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Network controller requested file info for {Filename} with ID {Id}", filename, id); + + try + { + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); + await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, false, 0); + } + } + private async Task HandleAuthenticationChallenge(string challengeToken) { Log.Debug("Network controller sent an authentication challenge"); @@ -296,7 +315,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On<Guid, string>(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On<string, Guid>(NetworkHubMethods.RequestFile, HandleFileRequest); HubConnection.On<string>(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8753ae0a..d857cac5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -38,11 +38,25 @@ namespace slskd.Network ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } /// <summary> + /// Gets the collection of pending Agent file inquiries. + /// </summary> + ReadOnlyDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiries { get; } + + /// <summary> /// Gets the collection of registered Agents. /// </summary> ReadOnlyDictionary<string, string> RegisteredAgents { get; } /// <summary> + /// Retrieves information about the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file information.</param> + /// <param name="filename">The file for which to retrieve information.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>A value indicating whether the file exists, and the length in bytes.</returns> + Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000); + + /// <summary> /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. /// </summary> /// <param name="agent">The agent from which to retrieve the file.</param> @@ -132,11 +146,17 @@ namespace slskd.Network public ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); /// <summary> + /// Gets the collection of pending Agent file inquiries. + /// </summary> + public ReadOnlyDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiries => new(PendingFileInquiryDictionary); + + /// <summary> /// Gets the collection of registered Agents. /// </summary> public ReadOnlyDictionary<string, string> RegisteredAgents => new(RegisteredAgentDictionary); private ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary<string, string> RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -145,6 +165,88 @@ namespace slskd.Network private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); /// <summary> + /// Retrieves information about the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file information.</param> + /// <param name="filename">The file for which to retrieve information.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>A value indicating whether the file exists, and the length in bytes.</returns> + public async Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + + PendingFileInquiryDictionary.TryAdd(id, tcs); + + try + { + await NetworkHub.RequestFileInfoAsync(agent, filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agent, id); + + var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); + + if (task == tcs.Task) + { + return await tcs.Task; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + } + } + finally + { + PendingFileInquiryDictionary.TryRemove(id, out _); + } + } + + /// <summary> + /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file.</param> + /// <param name="filename">The file to retrieve.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns> + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + + // create a TCS for the upload stream. this is awaited below and completed in + // the API controller when the agent POSTs the file + var upload = new TaskCompletionSource<Stream>(); + + // create a TCS for the upload itself. this is awaited by the API controller + // and completed by the transfer service when the upload to the remote user is complete + // the API controller needs to wait until the remote transfer is complete in order to + // keep the stream open for the duration + var completion = new TaskCompletionSource(); + + PendingFileUploadDictionary.TryAdd(id, (upload, completion)); + + try + { + await NetworkHub.RequestFileAsync(agent, filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); + + var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + + if (task == upload.Task) + { + var stream = await upload.Task; + return (stream, completion); + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); + } + } + finally + { + PendingFileUploadDictionary.TryRemove(id, out _); + } + } + + /// <summary> /// Retrieves a new share upload token for the specified <paramref name="agent"/>. /// </summary> /// <remarks> @@ -249,45 +351,6 @@ namespace slskd.Network return expectedResponse == challengeResponse; } - /// <summary> - /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. - /// </summary> - /// <param name="agent">The agent from which to retrieve the file.</param> - /// <param name="filename">The file to retrieve.</param> - /// <param name="timeout">An optional timeout value.</param> - /// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns> - public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) - { - var id = Guid.NewGuid(); - - // create a TCS for the upload stream. this is awaited below and completed in - // the API controller when the agent POSTs the file - var upload = new TaskCompletionSource<Stream>(); - - // create a TCS for the upload itself. this is awaited by the API controller - // and completed by the transfer service when the upload to the remote user is complete - // the API controller needs to wait until the remote transfer is complete in order to - // keep the stream open for the duration - var completion = new TaskCompletionSource(); - - PendingFileUploadDictionary.TryAdd(id, (upload, completion)); - - await NetworkHub.RequestFileAsync(agent, filename, id); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); - - if (task == upload.Task) - { - var stream = await upload.Task; - return (stream, completion); - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); - } - } - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; |
