diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Agents/API/Controllers/AgentController.cs | 48 | ||||
| -rw-r--r-- | src/slskd/Agents/API/Controllers/AgentsController.cs | 83 | ||||
| -rw-r--r-- | src/slskd/Agents/API/Hubs/AgentHub.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Agents/AgentService.cs | 218 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 14 |
5 files changed, 315 insertions, 59 deletions
diff --git a/src/slskd/Agents/API/Controllers/AgentController.cs b/src/slskd/Agents/API/Controllers/AgentController.cs deleted file mode 100644 index dab925a4..00000000 --- a/src/slskd/Agents/API/Controllers/AgentController.cs +++ /dev/null @@ -1,48 +0,0 @@ -// <copyright file="AgentController.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.Agents -{ - using Microsoft.AspNetCore.Authorization; - using Microsoft.AspNetCore.Mvc; - - /// <summary> - /// Application. - /// </summary> - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] - [ApiController] - [Produces("application/json")] - [Consumes("application/json")] - public class AgentController : ControllerBase - { - public AgentController() - { - } - - /// <summary> - /// Gets the current state of the application. - /// </summary> - /// <returns></returns> - [HttpPost("files/{id}")] - [Authorize] - public IActionResult UploadFile(string id) - { - return Ok(id); - } - } -} diff --git a/src/slskd/Agents/API/Controllers/AgentsController.cs b/src/slskd/Agents/API/Controllers/AgentsController.cs new file mode 100644 index 00000000..48f70cee --- /dev/null +++ b/src/slskd/Agents/API/Controllers/AgentsController.cs @@ -0,0 +1,83 @@ +// <copyright file="AgentController.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.Agents +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Serilog; + + /// <summary> + /// Application. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + public class AgentsController : ControllerBase + { + public AgentsController(IAgentService agentService) + { + Agents = agentService; + } + + private IAgentService Agents { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<AgentService>(); + + /// <summary> + /// Gets the current state of the application. + /// </summary> + /// <returns></returns> + [HttpPost("files/{id}")] + [Authorize] + public async Task<IActionResult> UploadFile(string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest("Id is not a valid Guid"); + } + + // get the record for the waiting file + if (Agents.PendingUploads.TryGetValue(guid, out var record)) + { + // get the stream from the multipart upload + var stream = Request.Form.Files.First().OpenReadStream(); + + // set the result for the stream + // this should pass control to the transfer service along with + // the stream + record.Upload.SetResult(stream); + + Console.WriteLine("Stream handed off. Waiting for completion..."); + + // wait for the transfer service to set the completion result + await record.Completion.Task; + + stream.Dispose(); + Console.WriteLine("Upload complete"); + return Ok(); + } + else + { + Log.Warning("Agent"); + return NotFound(); + } + } + } +} diff --git a/src/slskd/Agents/API/Hubs/AgentHub.cs b/src/slskd/Agents/API/Hubs/AgentHub.cs index 533621a8..99df6bf8 100644 --- a/src/slskd/Agents/API/Hubs/AgentHub.cs +++ b/src/slskd/Agents/API/Hubs/AgentHub.cs @@ -35,10 +35,10 @@ namespace slskd.Agents /// </summary> public static class AgentHubExtensions { - public static Task RequestFileAsync(this IHubContext<AgentHub> hub, Guid id, string filename) + public static Task RequestFileAsync(this IHubContext<AgentHub> hub, string agent, string filename, Guid id) { - // todo: how to send this to a specific user? - return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, id, filename); + // todo: how to send this to the specified agent? + return hub.Clients.All.SendAsync(AgentHubMethods.RequestFile, filename, id); } } @@ -68,10 +68,5 @@ namespace slskd.Agents // todo: how to authenticate? // todo: how to identify? } - - public Task RequestFileAsync(string filename) - { - return Clients.All.SendAsync("foo"); - } } }
\ No newline at end of file diff --git a/src/slskd/Agents/AgentService.cs b/src/slskd/Agents/AgentService.cs index 8ecb7c71..5b17d996 100644 --- a/src/slskd/Agents/AgentService.cs +++ b/src/slskd/Agents/AgentService.cs @@ -1,11 +1,227 @@ -namespace slskd.Agents +// <copyright file="AgentService.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; + +namespace slskd.Agents { + using System; + using System.Collections.Concurrent; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR; + using Microsoft.AspNetCore.SignalR.Client; + using Serilog; + public interface IAgentService { + /// <summary> + /// Gets the collection of pending Agent uploads. + /// </summary> + ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads { get; } + /// <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> + Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); } public class AgentService : IAgentService { + public AgentService( + IOptionsMonitor<Options> optionsMonitor, + IHttpClientFactory httpClientFactory, + IHubContext<AgentHub> agentHub) + { + AgentHub = agentHub; + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + private IOptionsMonitor<Options> OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private IHubContext<AgentHub> AgentHub { get; set; } + private string LastOptionsHash { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private ILogger Log { get; } = Serilog.Log.ForContext<AgentService>(); + + /// <summary> + /// Gets the collection of pending Agent uploads. + /// </summary> + public ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads { get; } = new(); + + /// <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)> GetUpload(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(); + + PendingUploads.TryAdd(id, (upload, completion)); + + await AgentHub.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 async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Shares.Directories)); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var mode = options.Network.OperationMode.ToEnum<NetworkOperationMode>(); + + //if (mode == NetworkOperationMode.Agent + //{ + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + Console.WriteLine("-------------------------- building hub ------------------------"); + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect() + .Build(); + + HubConnection.On<Guid, string>(AgentHubMethods.RequestFile, HandleFileRequest); + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + _ = Task.Run(async () => + { + try + { + await Task.Delay(1000); + Console.WriteLine("------------------- connecting hub -------------------"); + await HubConnection.StartAsync(); + Log.Information("Controller connection established"); + Console.WriteLine("---------------------------- hub connected ----------------------"); + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + }); + //} + + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.Release(); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Controller connection reconnected"); + return Task.CompletedTask; + } } } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c3cfe2fb..8c7eaffa 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -30,6 +30,7 @@ namespace slskd.Transfers.Uploads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Agents; using slskd.Shares; using slskd.Users; @@ -43,11 +44,13 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor<Options> optionsMonitor, IShareService shareService, + IAgentService agentService, IDbContextFactory<TransfersDbContext> contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; + Agents = agentService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -72,6 +75,7 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } + private IAgentService Agents { get; set; } /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. @@ -214,14 +218,20 @@ namespace slskd.Transfers.Uploads slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + //using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + + var (stream, completion) = await Agents.GetFileStream(filename); + var completedTransfer = await Client.UploadAsync( username, filename, - fileInfo.FullName, + size: fileInfo.Length, + inputStreamFactory: () => stream, options: topts, cancellationToken: cts.Token); + completion.SetResult(); + // explicitly dispose the rate limiter to prevent updates from it // beyond this point, which may overwrite the final state rateLimiter.Dispose(); |
