From 4871bdf439421514a53c7b3f111838cfb63ed664 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Oct 2022 18:09:05 -0500 Subject: clean up and tweak --- src/slskd/Network/NetworkClient.cs | 47 +++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 6 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 49f483fc..dfb53f86 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -29,14 +29,37 @@ namespace slskd.Network using slskd.Cryptography; using slskd.Shares; + /// + /// Network client (agent). + /// public interface INetworkClient { + /// + /// Starts the client and connects to the controller. + /// + /// + /// Task StartAsync(CancellationToken cancellationToken = default); + + /// + /// Stops the client and disconnects from the controller. + /// + /// + /// Task StopAsync(CancellationToken cancellationToken = default); } + /// + /// Network client (agent). + /// public class NetworkClient : INetworkClient { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// public NetworkClient( IShareService shareService, IOptionsMonitor optionsMonitor, @@ -63,6 +86,11 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private TaskCompletionSource LoggedIn { get; set; } + /// + /// Starts the client and connects to the controller. + /// + /// + /// public async Task StartAsync(CancellationToken cancellationToken = default) { if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) @@ -106,6 +134,11 @@ namespace slskd.Network Log.Information("Shares uploaded. Ready to upload files."); } + /// + /// Stops the client and disconnects from the controller. + /// + /// + /// public async Task StopAsync(CancellationToken cancellationToken = default) { StartRequested = false; @@ -129,14 +162,15 @@ namespace slskd.Network Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); + var token = await HubConnection.InvokeAsync(nameof(NetworkHub.BeginShareUpload)); Log.Debug("Share upload token {Token}", token); var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, { new StreamContent(stream), "database", "shares" }, @@ -167,7 +201,7 @@ namespace slskd.Network private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); - private Task HandleFileRequest(string filename, Guid token) + private Task HandleFileUploadRequest(string filename, Guid token) { _ = Task.Run(async () => { @@ -186,9 +220,10 @@ namespace slskd.Network } using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; @@ -212,7 +247,7 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), token); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyFileUploadFailed), token); } }); @@ -334,7 +369,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(nameof(INetworkHub.RequestFile), HandleFileRequest); + HubConnection.On(nameof(INetworkHub.RequestFileUpload), HandleFileUploadRequest); HubConnection.On(nameof(INetworkHub.RequestFileInfo), HandleFileInfoRequest); HubConnection.On(nameof(INetworkHub.Challenge), HandleAuthenticationChallenge); -- cgit v1.2.3 From 4489434a5d5580b8bf74bc0a16512545e0dcb0f6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Oct 2022 18:26:45 -0500 Subject: fix bugs --- src/slskd/Network/API/Controllers/NetworkController.cs | 8 ++++++-- src/slskd/Network/NetworkClient.cs | 18 ++++++++---------- 2 files changed, 14 insertions(+), 12 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 6ecb0005..276cdcd0 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -162,7 +162,7 @@ namespace slskd.Network try { - agentName = Request.Form["agent"].ToString(); + agentName = Request.Form["name"].ToString(); credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson>(); database = Request.Form.Files[0]; @@ -185,16 +185,19 @@ namespace slskd.Network } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db"); + Stream outputStream = default; try { Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); - using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); + outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); + await outputStream.FlushAsync(); + Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); await Network.HandleShareUpload(agentName, id: guid, shares, temp); @@ -209,6 +212,7 @@ namespace slskd.Network { try { + outputStream?.TryDispose(); System.IO.File.Delete(temp); } catch (Exception ex) diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index dfb53f86..e0aec505 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -275,27 +275,25 @@ namespace slskd.Network private async Task HandleAuthenticationChallenge(string challengeToken) { - Log.Debug("Network controller sent an authentication challenge"); - try { + Log.Debug("Network controller sent an authentication challenge"); + var options = OptionsMonitor.CurrentValue; var agent = options.InstanceName; var response = ComputeCredential(challengeToken); Log.Debug("Logging in..."); - var success = await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); - - if (!success) - { - await HubConnection.StopAsync(); - Log.Error("Network controller authentication failed. Check configuration."); - } - + await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); Log.Debug("Login succeeded."); LoggedIn?.TrySetResult(); } + catch (UnauthorizedAccessException) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); -- cgit v1.2.3