diff options
| -rwxr-xr-x | bin/build | 2 | ||||
| -rwxr-xr-x | bin/publish | 4 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Relay/API/Controllers/RelayController.cs | 34 | ||||
| -rw-r--r-- | src/slskd/Relay/API/Hubs/RelayHub.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Relay/IRelayClient.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Relay/NullRelayClient.cs (renamed from src/slskd/Relay/DummyRelayClient.cs) | 34 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayService.cs | 172 | ||||
| -rw-r--r-- | src/slskd/Relay/Types/Agent.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Relay/Types/RelayClientState.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Relay/Types/RelayMode.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 2 | ||||
| -rw-r--r-- | src/web/src/components/App.js | 77 | ||||
| -rw-r--r-- | src/web/src/components/Search/Searches.js | 2 | ||||
| -rw-r--r-- | src/web/src/components/Transfers/TransferList.js | 4 |
16 files changed, 295 insertions, 188 deletions
@@ -13,7 +13,7 @@ while test $# -gt 0; do echo '--web-only skip dotnet build' echo '--dotnet-only skip web build' echo '--skip-tests skip execution of npm and dotnet tests' - echo '--version version for the binary. defaults to current git tag-SHA' + echo '--version version for the binary. defaults to current git tag+SHA' exit 0 ;; --web-only) diff --git a/bin/publish b/bin/publish index 3461c470..512fb9f6 100755 --- a/bin/publish +++ b/bin/publish @@ -11,7 +11,7 @@ while test $# -gt 0; do echo '--no-prebuild skip build and test' echo '--runtime a valid RID (https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)' echo '--platform one of: linux/amd64, linux/arm64, linux/arm/v7. overrides runtime.' - echo '--version version for the binary. defaults to current git tag-SHA' + echo '--version version for the binary. defaults to current git tag+SHA' echo '--output the output directory. defaults to ../../dist/<runtime>' exit 0 ;; @@ -69,7 +69,7 @@ fi if [ -z "$version" ]; then tag=$(git describe --tags --abbrev=0) sha=$(git rev-parse --short HEAD) - version=$tag-$sha + version=$tag+$sha fi if [ -z "$runtime" ]; then diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f1f6bc03..65a42522 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -135,7 +135,7 @@ namespace slskd /// <summary> /// Gets the semantic application version. /// </summary> - public static string SemanticVersion { get; } = InformationalVersion.Split('-').First(); + public static string SemanticVersion { get; } = InformationalVersion.Split('+').First(); /// <summary> /// Gets the full application version, including both assembly and informational versions. @@ -246,7 +246,7 @@ namespace slskd try { - Arguments.Populate(clearExistingValues: false); + Arguments.Populate(clearExistingValues: false); } catch (Exception ex) { @@ -841,6 +841,11 @@ namespace slskd app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); + + // starting with .NET 7 the framework *really* wants you to use top level endpoint mapping + // for whatever reason this breaks everything, and i just can't bring myself to care unless + // UseEndpoints is going to be deprecated or if there's some material benefit +#pragma warning disable ASP0014 // Suggest using top level route registrations app.UseEndpoints(endpoints => { endpoints.MapHub<ApplicationHub>("/hub/application"); @@ -885,6 +890,7 @@ namespace slskd }); } }); +#pragma warning restore ASP0014 // Suggest using top level route registrations // if this is an /api route and no API controller was matched, give up and return a 404. app.Use(async (context, next) => diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index f6c6d778..586cbbb2 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -41,6 +41,12 @@ namespace slskd.Relay [ApiController] public class RelayController : ControllerBase { + /// <summary> + /// Initializes a new instance of the <see cref="RelayController"/> class. + /// </summary> + /// <param name="relayService"></param> + /// <param name="optionsMonitor"></param> + /// <param name="optionsAtStartup"></param> public RelayController( IRelayService relayService, IOptionsMonitor<Options> optionsMonitor, @@ -57,7 +63,11 @@ namespace slskd.Relay private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>(); private IOptionsMonitor<Options> OptionsMonitor { get; } - [HttpPut("")] + /// <summary> + /// Connects to the configured controller. + /// </summary> + /// <returns></returns> + [HttpPut("agent")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task<IActionResult> Connect() { @@ -70,7 +80,11 @@ namespace slskd.Relay return Ok(); } - [HttpDelete("")] + /// <summary> + /// Disconnects from the connected controller. + /// </summary> + /// <returns></returns> + [HttpDelete("agent")] [Authorize(Policy = AuthPolicy.JwtOnly)] public async Task<IActionResult> Disconnect() { @@ -84,11 +98,11 @@ namespace slskd.Relay } /// <summary> - /// Downloads a file. + /// Downloads a file from the connected controller. /// </summary> /// <param name="token">The unique identifier for the request.</param> /// <returns></returns> - [HttpGet("downloads/{token}")] + [HttpGet("controller/downloads/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly)] public IActionResult DownloadFile([FromRoute]string token) { @@ -135,11 +149,11 @@ namespace slskd.Relay } /// <summary> - /// Uploads a file. + /// Uploads a file to the connected controller. /// </summary> /// <param name="token">The unique identifier for the request.</param> /// <returns></returns> - [HttpPost("files/{token}")] + [HttpPost("controller/files/{token}")] [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] @@ -221,7 +235,7 @@ namespace slskd.Relay // pass the stream back to the relay service, which will in turn pass it to the upload service, and use it to // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. - await Relay.HandleFileStreamResponse(agentName, id: guid, stream); + await Relay.HandleFileStreamResponseAsync(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); @@ -233,11 +247,11 @@ namespace slskd.Relay } /// <summary> - /// Uploads share information. + /// Uploads share information to the connected controller. /// </summary> /// <param name="token">The unique identifier for the request.</param> /// <returns></returns> - [HttpPost("shares/{token}")] + [HttpPost("controller/shares/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly)] public async Task<IActionResult> UploadShares(string token) { @@ -307,7 +321,7 @@ namespace slskd.Relay Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); - await Relay.HandleShareUpload(agentName, id: guid, shares, temp); + await Relay.HandleShareUploadAsync(agentName, id: guid, shares, temp); return Ok(); } diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 43f49976..e246711e 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -169,7 +169,7 @@ namespace slskd.Relay } /// <summary> - /// Initiates the share upload workflow by generating and retrieving a request token. + /// Executed by the agent to initiate the share upload workflow by generating and retrieving a request token. /// </summary> /// <returns>The generated token.</returns> /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> @@ -188,7 +188,7 @@ namespace slskd.Relay } /// <summary> - /// Notifies the controller that the agent was unable to upload the file requested by a call to <see cref="IRelayHub.RequestFileUpload"/>. + /// Executed by the agent to notify the controller that the agent was unable to upload the file requested by a call to <see cref="IRelayHub.RequestFileUpload"/>. /// </summary> /// <param name="id">The unique identifier of the request.</param> /// <param name="exception">The Exception that caused the failure.</param> @@ -207,7 +207,7 @@ namespace slskd.Relay } /// <summary> - /// Returns the response to a call to <see cref="IRelayHub.RequestFileInfo"/>. + /// Executed by the agent to return the response to a call to <see cref="IRelayHub.RequestFileInfo"/>. /// </summary> /// <param name="id">The unique identifier for the request.</param> /// <param name="exists">A value indicating whether the requested file exists on the agent's filesystem.</param> diff --git a/src/slskd/Relay/IRelayClient.cs b/src/slskd/Relay/IRelayClient.cs new file mode 100644 index 00000000..376f3eaf --- /dev/null +++ b/src/slskd/Relay/IRelayClient.cs @@ -0,0 +1,55 @@ +// <copyright file="IRelayClient.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.Relay +{ + using System; + using System.Threading; + using System.Threading.Tasks; + + /// <summary> + /// Relay client (agent). + /// </summary> + public interface IRelayClient : IDisposable + { + /// <summary> + /// Gets the client state. + /// </summary> + IStateMonitor<RelayClientState> StateMonitor { get; } + + /// <summary> + /// Starts the client and connects to the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> + Task StartAsync(CancellationToken cancellationToken = default); + + /// <summary> + /// Stops the client and disconnects from the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> + Task StopAsync(CancellationToken cancellationToken = default); + + /// <summary> + /// Synchronizes state with the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> + Task SynchronizeAsync(CancellationToken cancellationToken = default); + } +} diff --git a/src/slskd/Relay/DummyRelayClient.cs b/src/slskd/Relay/NullRelayClient.cs index c5bd477c..d86e994f 100644 --- a/src/slskd/Relay/DummyRelayClient.cs +++ b/src/slskd/Relay/NullRelayClient.cs @@ -1,4 +1,4 @@ -// <copyright file="DummyRelayClient.cs" company="slskd Team"> +// <copyright file="NullRelayClient.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -20,24 +20,52 @@ namespace slskd.Relay using System.Threading; using System.Threading.Tasks; - public class DummyRelayClient : IRelayClient + /// <summary> + /// A non-operarable Relay client. + /// </summary> + public class NullRelayClient : IRelayClient { - public IStateMonitor<RelayClientState> StateMonitor => new ManagedState<RelayClientState>(); + /// <summary> + /// Gets the client state. + /// </summary> + public IStateMonitor<RelayClientState> StateMonitor { get; set; } = new ManagedState<RelayClientState>(); private bool Disposed { get; set; } + /// <summary> + /// Disposes this instance. + /// </summary> public void Dispose() { Dispose(disposing: true); System.GC.SuppressFinalize(this); } + /// <summary> + /// Starts the client and connects to the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + /// <summary> + /// Stops the client and disconnects from the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + /// <summary> + /// Synchronizes state with the controller. + /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> public Task SynchronizeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + /// <summary> + /// Disposes this instance. + /// </summary> + /// <param name="disposing">Disposing.</param> protected virtual void Dispose(bool disposing) { if (!Disposed) diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index dae89f78..eef84c27 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -33,37 +33,6 @@ namespace slskd.Relay /// <summary> /// Relay client (agent). /// </summary> - public interface IRelayClient : IDisposable - { - /// <summary> - /// Gets the client state. - /// </summary> - IStateMonitor<RelayClientState> StateMonitor { get; } - - /// <summary> - /// Starts the client and connects to the controller. - /// </summary> - /// <param name="cancellationToken"></param> - /// <returns></returns> - Task StartAsync(CancellationToken cancellationToken = default); - - /// <summary> - /// Stops the client and disconnects from the controller. - /// </summary> - /// <param name="cancellationToken"></param> - /// <returns></returns> - Task StopAsync(CancellationToken cancellationToken = default); - - /// <summary> - /// Synchronizes state with the controller. - /// </summary> - /// <returns>The operation context.</returns> - Task SynchronizeAsync(CancellationToken cancellationToken = default); - } - - /// <summary> - /// Relay client (agent). - /// </summary> public class RelayClient : IRelayClient { /// <summary> @@ -121,8 +90,8 @@ namespace slskd.Relay /// <summary> /// Starts the client and connects to the controller. /// </summary> - /// <param name="cancellationToken"></param> - /// <returns></returns> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> public async Task StartAsync(CancellationToken cancellationToken = default) { if (!StateSyncRoot.Wait(0, cancellationToken)) @@ -200,8 +169,8 @@ namespace slskd.Relay /// <summary> /// Stops the client and disconnects from the controller. /// </summary> - /// <param name="cancellationToken"></param> - /// <returns></returns> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>The operation context.</returns> public async Task StopAsync(CancellationToken cancellationToken = default) { StartRequested = false; @@ -220,6 +189,7 @@ namespace slskd.Relay /// <summary> /// Synchronizes state with the controller. /// </summary> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The operation context.</returns> public Task SynchronizeAsync(CancellationToken cancellationToken = default) { @@ -229,7 +199,7 @@ namespace slskd.Relay /// <summary> /// Disposes this instance. /// </summary> - /// <param name="disposing"></param> + /// <param name="disposing">Disposing.</param> protected virtual void Dispose(bool disposing) { if (!Disposed) @@ -419,7 +389,7 @@ namespace slskd.Relay stream.Seek(startOffset, SeekOrigin.Begin); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/files/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/controller/files/{token}"); request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); @@ -482,7 +452,7 @@ namespace slskd.Relay await Retry.Do(task: async () => { - using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/downloads/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/controller/downloads/{token}"); request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); @@ -531,7 +501,6 @@ namespace slskd.Relay try { // wait for the authentication flow to complete - // time out after 5 seconds in case we get stuck waiting on a dead Task await LoggedInTaskCompletionSource.Task; Log.Information("Uploading shares..."); @@ -540,7 +509,7 @@ namespace slskd.Relay } catch (Exception ex) { - Log.Error(ex, ex.Message); + Log.Error(ex, "Failed to log in and/or upload shares: {Message}", ex.Message); Log.Error("Disconnecting from the relay controller"); // stop, then fire and forget StartAsync() to re-enter the connection retry loop @@ -621,7 +590,7 @@ namespace slskd.Relay var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/controller/shares/{token}"); request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 2cf09f8d..c7056a0c 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -55,13 +55,6 @@ namespace slskd.Relay IStateMonitor<RelayState> StateMonitor { get; } /// <summary> - /// Notifies connected agents that a file download has completed. - /// </summary> - /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> - /// <returns>The operation context.</returns> - Task BroadcastFileDownloadCompletedNotificationAsync(string filename); - - /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. /// </summary> /// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks> @@ -76,12 +69,13 @@ namespace slskd.Relay /// <para>This is the first step in a multi-step workflow. The entire sequence is:</para> /// <list type="number"> /// <item> - /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn - /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached, and is only valid while it is in the cache. + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn calls + /// <see cref="GenerateShareUploadToken"/>. The token is generated and cached, and is only valid while it is + /// in the cache. /// </item> /// <item> - /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its - /// shared database and a serialized list of locally configured shares, and the controller invokes <see cref="HandleShareUpload"/>. + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its shared + /// database and a serialized list of locally configured shares, and the controller invokes <see cref="HandleShareUploadAsync"/>. /// </item> /// </list> /// </remarks> @@ -128,7 +122,7 @@ namespace slskd.Relay /// <item> /// <para> /// The remote agent makes an HTTP POST request containing a multipart upload including the file, and the - /// API controller invokes and awaits <see cref="HandleFileStreamResponse"/>. The stream is passed from + /// API controller invokes and awaits <see cref="HandleFileStreamResponseAsync"/>. The stream is passed from /// this method back to the awaited <see cref="GetFileStreamAsync"/>, and the Upload service passes the /// stream to Soulseek.NET, streaming the data from the still-open HTTP request through to the remote /// Soulseek user. @@ -143,7 +137,7 @@ namespace slskd.Relay /// <item> /// When the Upload is complete (successfully or otherwise), the Upload service invokes /// <see cref="TryCloseFileStream"/>, passing an optional <see cref="Exception"/> if the transfer was not - /// successful. This call signals the waiting <see cref="HandleFileStreamResponse"/> to complete, passing + /// successful. This call signals the waiting <see cref="HandleFileStreamResponseAsync"/> to complete, passing /// control back to the API controller and completing the HTTP POST request from the agent. /// </item> /// </list> @@ -173,7 +167,7 @@ namespace slskd.Relay /// <param name="id">The ID of the request.</param> /// <param name="response">The client response to the request.</param> /// <returns>The operation context.</returns> - Task HandleFileStreamResponse(string agentName, Guid id, Stream response); + Task HandleFileStreamResponseAsync(string agentName, Guid id, Stream response); /// <summary> /// Handles incoming share uploads. @@ -183,7 +177,14 @@ namespace slskd.Relay /// <param name="shares">The list of shares provided.</param> /// <param name="filename">The filename of the temporary file containing the upload.</param> /// <returns>The operation context.</returns> - Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename); + Task HandleShareUploadAsync(string agentName, Guid id, IEnumerable<Share> shares, string filename); + + /// <summary> + /// Notifies connected agents that a file download has completed. + /// </summary> + /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> + /// <returns>The operation context.</returns> + Task NotifyFileDownloadCompleteAsync(string filename); /// <summary> /// Notifies the caller of <see cref="GetFileStreamAsync"/> of a failure to obtain a file stream from the requested agent. @@ -267,6 +268,16 @@ namespace slskd.Relay /// </summary> public class RelayService : IRelayService { + /// <summary> + /// Initializes a new instance of the <see cref="RelayService"/> class. + /// </summary> + /// <param name="waiter"></param> + /// <param name="shareService"></param> + /// <param name="shareRepositoryFactory"></param> + /// <param name="optionsMonitor"></param> + /// <param name="relayHub"></param> + /// <param name="httpClientFactory"></param> + /// <param name="relayClient"></param> public RelayService( IWaiter waiter, IShareService shareService, @@ -284,7 +295,7 @@ namespace slskd.Relay HttpClientFactory = httpClientFactory; // wire up a dummy client so callers don't need to handle nulls - Client = relayClient ?? new DummyRelayClient(); + Client = relayClient ?? new NullRelayClient(); StateMonitor = State; @@ -309,68 +320,20 @@ namespace slskd.Relay public IStateMonitor<RelayState> StateMonitor { get; } private IHttpClientFactory HttpClientFactory { get; } + private string LastControllerOptionsHash { get; set; } + private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<RelayService>(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); - private IHubContext<RelayHub, IRelayHub> RelayHub { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } private ConcurrentDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary<string, (string ConnectionId, Agent Agent)> RegisteredAgentDictionary { get; } = new(); + private IHubContext<RelayHub, IRelayHub> RelayHub { get; set; } private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareService Shares { get; } - private IWaiter Waiter { get; } private IManagedState<RelayState> State { get; } = new ManagedState<RelayState>(); - private ConcurrentDictionary<WaitKey, Guid> WaitIdDictionary { get; } = new(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private string LastOptionsHash { get; set; } - private string LastControllerOptionsHash { get; set; } - - /// <summary> - /// Notifies connected agents that a file download has completed. - /// </summary> - /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> - /// <returns>The operation context.</returns> - public Task BroadcastFileDownloadCompletedNotificationAsync(string filename) - { - if (!OptionsMonitor.CurrentValue.Relay.Enabled || - !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>())) - { - return Task.CompletedTask; - } - - var agents = RegisteredAgentDictionary.Values; - - if (!agents.Any()) - { - return Task.CompletedTask; - } - - // ensure filename is relative to the local download directory - // and make sure it doesn't start with a slash - filename = filename - .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) - .TrimStart(new[] { '/', '\\' }); - - async Task Notify((string ConnectionId, Agent Agent) record) - { - try - { - var id = Guid.NewGuid(); - - MemoryCache.Set(GetDownloadTokenCacheKey(filename, id), record.Agent.Name, TimeSpan.FromMinutes(10)); - Log.Debug("Cached file download token {Token} for agent {Agent}", id, record.Agent.Name); - - await RelayHub.Clients.Client(record.ConnectionId).NotifyFileDownloadCompleted(filename, id); - } - catch - { - Log.Warning("Failed to notify agent {Agent} of download completion for {Filename}", record.Agent.Name, filename); - } - } - - Log.Information("Notifying agents of download completion for {Filename}", filename); - - return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); - } + private IWaiter Waiter { get; } + private ConcurrentDictionary<WaitKey, Guid> WaitIdDictionary { get; } = new(); /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. @@ -396,16 +359,16 @@ namespace slskd.Relay /// <para>This is the first step in a multi-step workflow. The entire sequence is:</para> /// <list type="number"> /// <item> - /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn - /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached. + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn calls + /// <see cref="GenerateShareUploadToken"/>. The token is generated and cached. /// </item> /// <item> - /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its - /// shared database and a serialized list of locally configured shares. + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its shared + /// database and a serialized list of locally configured shares. /// </item> /// <item> - /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or updates) - /// a share host for the agent. + /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or + /// updates) a share host for the agent. /// </item> /// </list> /// </remarks> @@ -488,7 +451,7 @@ namespace slskd.Relay /// <item> /// <para> /// The remote agent makes an HTTP POST request containing a multipart upload including the file, and the - /// API controller invokes and awaits <see cref="HandleFileStreamResponse"/>. The stream is passed from + /// API controller invokes and awaits <see cref="HandleFileStreamResponseAsync"/>. The stream is passed from /// this method back to the awaited <see cref="GetFileStreamAsync"/>, and the Upload service passes the /// stream to Soulseek.NET, streaming the data from the still-open HTTP request through to the remote /// Soulseek user. @@ -503,7 +466,7 @@ namespace slskd.Relay /// <item> /// When the Upload is complete (successfully or otherwise), the Upload service invokes /// <see cref="TryCloseFileStream"/>, passing an optional <see cref="Exception"/> if the transfer was not - /// successful. This call signals the waiting <see cref="HandleFileStreamResponse"/> to complete, passing + /// successful. This call signals the waiting <see cref="HandleFileStreamResponseAsync"/> to complete, passing /// control back to the API controller and completing the HTTP POST request from the agent. /// </item> /// </list> @@ -582,7 +545,7 @@ namespace slskd.Relay /// <param name="id">The ID of the request.</param> /// <param name="response">The client response to the request.</param> /// <returns>The operation context.</returns> - public async Task HandleFileStreamResponse(string agentName, Guid id, Stream response) + public async Task HandleFileStreamResponseAsync(string agentName, Guid id, Stream response) { var streamKey = new WaitKey(nameof(GetFileStreamAsync), agentName, id); @@ -596,7 +559,7 @@ namespace slskd.Relay // create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this to // keep execution in the body of the API controller that provided the stream, in order to keep the stream open for the // duration of the remote transfer. omit the id from the key, the caller doesn't know it. - var completionKey = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); + var completionKey = new WaitKey(nameof(HandleFileStreamResponseAsync), agentName, id); var completion = Waiter.WaitIndefinitely(completionKey); // complete the wait that's waiting for the stream, so we can send the stream back to the caller of GetFileStream this @@ -616,7 +579,7 @@ namespace slskd.Relay /// <param name="shares">The list of shares provided.</param> /// <param name="filename">The filename of the temporary file containing the upload.</param> /// <returns>The operation context.</returns> - public Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename) + public Task HandleShareUploadAsync(string agentName, Guid id, IEnumerable<Share> shares, string filename) { Log.Information("Loading shares from agent {Agent}", agentName); @@ -639,6 +602,53 @@ namespace slskd.Relay } /// <summary> + /// Notifies connected agents that a file download has completed. + /// </summary> + /// <param name="filename">The filename of the completed file, relative to the downloads directory.</param> + /// <returns>The operation context.</returns> + public Task NotifyFileDownloadCompleteAsync(string filename) + { + if (!OptionsMonitor.CurrentValue.Relay.Enabled || + !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>())) + { + return Task.CompletedTask; + } + + var agents = RegisteredAgentDictionary.Values; + + if (!agents.Any()) + { + return Task.CompletedTask; + } + + // ensure filename is relative to the local download directory and make sure it doesn't start with a slash + filename = filename + .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) + .TrimStart(new[] { '/', '\\' }); + + async Task Notify((string ConnectionId, Agent Agent) record) + { + try + { + var id = Guid.NewGuid(); + + MemoryCache.Set(GetDownloadTokenCacheKey(filename, id), record.Agent.Name, TimeSpan.FromMinutes(10)); + Log.Debug("Cached file download token {Token} for agent {Agent}", id, record.Agent.Name); + + await RelayHub.Clients.Client(record.ConnectionId).NotifyFileDownloadCompleted(filename, id); + } + catch + { + Log.Warning("Failed to notify agent {Agent} of download completion for {Filename}", record.Agent.Name, filename); + } + } + + Log.Information("Notifying agents of download completion for {Filename}", filename); + + return Task.WhenAll(RegisteredAgentDictionary.Values.Select(Notify)); + } + + /// <summary> /// Notifies the caller of <see cref="GetFileStreamAsync"/> of a failure to obtain a file stream from the requested agent. /// </summary> /// <param name="id">The unique ID for the stream.</param> @@ -668,7 +678,7 @@ namespace slskd.Relay /// <param name="exception">If the transfer associated with the stream failed, the exception that caused the failure.</param> public void TryCloseFileStream(string agentName, Guid id, Exception exception = default) { - var key = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); + var key = new WaitKey(nameof(HandleFileStreamResponseAsync), agentName, id); if (exception != default) { diff --git a/src/slskd/Relay/Types/Agent.cs b/src/slskd/Relay/Types/Agent.cs index 3ed1767e..6a70cbd2 100644 --- a/src/slskd/Relay/Types/Agent.cs +++ b/src/slskd/Relay/Types/Agent.cs @@ -17,9 +17,19 @@ namespace slskd.Relay { + /// <summary> + /// Tracking information for a Relay agent. + /// </summary> public record Agent { + /// <summary> + /// The name of the agent. + /// </summary> public string Name { get; init; } + + /// <summary> + /// The IP address associated with the active connection. + /// </summary> public string IPAddress { get; init; } } } diff --git a/src/slskd/Relay/Types/RelayClientState.cs b/src/slskd/Relay/Types/RelayClientState.cs index def25411..79f90e69 100644 --- a/src/slskd/Relay/Types/RelayClientState.cs +++ b/src/slskd/Relay/Types/RelayClientState.cs @@ -17,11 +17,29 @@ namespace slskd.Relay { + /// <summary> + /// The state of a Relay client. + /// </summary> public enum RelayClientState { + /// <summary> + /// Disconnected. + /// </summary> Disconnected, + + /// <summary> + /// Connected. + /// </summary> Connected, + + /// <summary> + /// Connecting. + /// </summary> Connecting, + + /// <summary> + /// Reconnecting. + /// </summary> Reconnecting, } } diff --git a/src/slskd/Relay/Types/RelayMode.cs b/src/slskd/Relay/Types/RelayMode.cs index d45a8933..3663271c 100644 --- a/src/slskd/Relay/Types/RelayMode.cs +++ b/src/slskd/Relay/Types/RelayMode.cs @@ -18,7 +18,7 @@ namespace slskd.Relay { /// <summary> - /// The relay mode. + /// The mode the Relay is operating under. /// </summary> public enum RelayMode { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c85ff551..827a0528 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -232,7 +232,7 @@ namespace slskd.Transfers.Downloads if (OptionsMonitor.CurrentValue.Relay.Enabled) { - _ = Relay.BroadcastFileDownloadCompletedNotificationAsync(finalFilename); + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 70d154af..b52a3bdd 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -315,50 +315,49 @@ class App extends Component { </Sidebar> <Sidebar.Pusher className='app-content'> <AppContext.Provider value={{ state: applicationState, options: applicationOptions }}> - <Switch> - {isAgent ? <> + {isAgent ? <Switch> + <Route path={`${urlBase}/system/:tab?`} render={ + (props) => this.withTokenCheck( + <System {...props} state={applicationState} options={applicationOptions} /> + ) + }/> + <Redirect from='*' to={`${urlBase}/system`}/> + </Switch> : + <Switch> + <Route path={`${urlBase}/searches/:id?`} render={(props) => + this.withTokenCheck(<div className='view'> + <Searches + server={applicationState.server} + {...props} + /> + </div>)} + /> + <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> + <Route path={`${urlBase}/users`} render={(props) => + this.withTokenCheck(<Users {...props}/>)} + /> + <Route path={`${urlBase}/chat`} render={(props) => + this.withTokenCheck(<Chat {...props} state={applicationState}/>)} + /> + <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/> + <Route path={`${urlBase}/uploads`} render={ + (props) => + this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>) + }/> + <Route path={`${urlBase}/downloads`} render={ + (props) => + this.withTokenCheck(<div className='view'> + <Transfers {...props} direction='download' server={applicationState.server}/> + </div>) + }/> <Route path={`${urlBase}/system/:tab?`} render={ (props) => this.withTokenCheck( <System {...props} state={applicationState} options={applicationOptions} /> ) }/> - <Redirect from='*' to={`${urlBase}/system`}/> - </> : - <> - <Route path={`${urlBase}/searches/:id?`} render={(props) => - this.withTokenCheck(<div className='view'> - <Searches - server={applicationState.server} - {...props} - /> - </div>)} - /> - <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> - <Route path={`${urlBase}/users`} render={(props) => - this.withTokenCheck(<Users {...props}/>)} - /> - <Route path={`${urlBase}/chat`} render={(props) => - this.withTokenCheck(<Chat {...props} state={applicationState}/>)} - /> - <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/> - <Route path={`${urlBase}/uploads`} render={ - (props) => - this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>) - }/> - <Route path={`${urlBase}/downloads`} render={ - (props) => - this.withTokenCheck(<div className='view'> - <Transfers {...props} direction='download' server={applicationState.server}/> - </div>) - }/> - <Route path={`${urlBase}/system/:tab?`} render={ - (props) => this.withTokenCheck( - <System {...props} state={applicationState} options={applicationOptions} /> - ) - }/> - <Redirect from='*' to={`${urlBase}/searches`}/> - </>} - </Switch> + <Redirect from='*' to={`${urlBase}/searches`}/> + </Switch> + } </AppContext.Provider> </Sidebar.Pusher> </Sidebar.Pushable> diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js index 46a9f709..42b82f8c 100644 --- a/src/web/src/components/Search/Searches.js +++ b/src/web/src/components/Search/Searches.js @@ -42,8 +42,8 @@ const Searches = ({ server }) => { const onConnectionError = (error) => { setConnecting(false); setError(error); }; const onUpdate = (update) => { - onConnected(); setSearches(update); + onConnected(); }; useEffect(() => { diff --git a/src/web/src/components/Transfers/TransferList.js b/src/web/src/components/Transfers/TransferList.js index 0c725f98..c35f512f 100644 --- a/src/web/src/components/Transfers/TransferList.js +++ b/src/web/src/components/Transfers/TransferList.js @@ -143,9 +143,7 @@ class TransferList extends Component { </Button>} </Table.Cell> <Table.Cell className='transferlist-size'> - {f.bytesTransferred > 0 - ? formatBytesTransferred({ transferred: f.bytesTransferred, size: f.size }) - : ''} + {formatBytesTransferred({ transferred: f.bytesTransferred, size: f.size })} </Table.Cell> </Table.Row> )} |
