diff options
| -rw-r--r-- | config/slskd.example.yml | 9 | ||||
| -rw-r--r-- | docs/config.md | 2 | ||||
| -rw-r--r-- | docs/system_requirements.md | 37 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 24 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/RelayException.cs (renamed from src/slskd/Common/Exceptions/NetworkException.cs) | 22 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 63 | ||||
| -rw-r--r-- | src/slskd/Core/State.cs | 12 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Relay/API/Controllers/RelayController.cs (renamed from src/slskd/Network/API/Controllers/NetworkController.cs) | 32 | ||||
| -rw-r--r-- | src/slskd/Relay/API/Hubs/RelayHub.cs (renamed from src/slskd/Network/API/Hubs/NetworkHub.cs) | 54 | ||||
| -rw-r--r-- | src/slskd/Relay/DummyRelayClient.cs (renamed from src/slskd/Network/DummyNetworkClient.cs) | 8 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs (renamed from src/slskd/Network/NetworkClient.cs) | 110 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClientState.cs (renamed from src/slskd/Network/NetworkClientState.cs) | 6 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayService.cs (renamed from src/slskd/Network/NetworkService.cs) | 62 | ||||
| -rw-r--r-- | src/slskd/Relay/Types/Agent.cs (renamed from src/slskd/Network/Types/Agent.cs) | 2 | ||||
| -rw-r--r-- | src/slskd/Relay/Types/OperationMode.cs (renamed from src/slskd/Network/Types/OperationMode.cs) | 4 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Users/API/Controllers/UsersController.cs | 23 | ||||
| -rw-r--r-- | src/web/src/components/Search/Response.js | 18 | ||||
| -rw-r--r-- | src/web/src/components/Shared/FileList.js | 57 | ||||
| -rw-r--r-- | src/web/src/lib/users.js | 4 |
22 files changed, 353 insertions, 236 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 39b52aad..a1a5d825 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -1,5 +1,4 @@ # debug: false -# experimental: false # remote_configuration: false # instance_name: default # flags: @@ -10,17 +9,19 @@ # force_share_scan: false # no_version_check: false # log_sql: false -# network: +# experimental: false +# volatile: false +# relay: # mode: controller # controller (default), agent, or debug (for local development) # # controller config is required when running in 'agent' mode -# # this specifies the network controller that will be controlling this agent +# # this specifies the relay controller that will be controlling this agent # controller: # address: # ignore_certificate_errors: false # api_key: <a 16-255 character string corresponding to one of the controller's API keys> # secret: <a 16-255 character shared secret matching the controller's config for this agent> # # agent config is optional when running in 'controller' mode -# # this specifies all of the agents on the network +# # this specifies all of the agents capable of connecting # agents: # my_agent: # secret: <a 16-255 character string unique to this agent> diff --git a/docs/config.md b/docs/config.md index 1b42c186..bde38889 100644 --- a/docs/config.md +++ b/docs/config.md @@ -799,7 +799,7 @@ Several additional feature flags are provided to change the application's runtim | `--force-share-scan` | `SLSKD_FORCE_SHARE_SCAN` | Force a scan of shared directories on startup | | `--no-version-check` | `SLSKD_NO_VERSION_CHECK` | Don't perform a version check on startup | | `--log-sql` | `SLSKD_LOG_SQL` | Log SQL queries generated by Entity Framework | -| `--dual-network-mode`| `SLSKD_DUAL_NETWORK_MODE` | Run in both Agent and Controller network modes | +| `--volatile` | `SLSKD_VOLATILE` | Use volatile data storage (all data will be lost at shutdown) | #### **YAML** ```yaml diff --git a/docs/system_requirements.md b/docs/system_requirements.md new file mode 100644 index 00000000..87241fab --- /dev/null +++ b/docs/system_requirements.md @@ -0,0 +1,37 @@ +# System Requirements + +Designed to run on a minimum of a Raspberry Pi 2 (or equivalent), or any system with: + +* x86, x86_64, amd64, or ARMv7+ processor +* at least 512mb RAM +* at least 150mb disk space + +Users concerned about optimal performance should consider something faster. + +# Known Issues + +## Any device with an ARMv6 or earlier processor + +Not supported by the .NET runtime. This may change in future versions. + +## Raspberry Pi Zero (any variant) + +At the moment all Pi Zeros are ARMv6. + +## Devices using a copy-on-write filesystem such as BTRFS or ZFS + +slskd uses SQLite to store transactional data associated with things like transfers and searches, and these reads and writes experience too much I/O latency for the application to work properly with these filesystems. + +Optimizations to the filesystems can be made to improve performance, but will come at a cost to most other use cases and are not recommended. + +slskd can still run on devices using these filesystems if application data can be stored on a separate disk or partition using a different filesystem, or potentially on a RAM disk (which would be volatile unless configured otherwise). + +Users can also enable 'volatile mode' (`SLSKD_VOLATILE` or `flags.volatile: true`), which will use in-memory SQLite tables. Searches and transfers will be lost when the application is restarted while in this mode. + +## Application data stored on network filesystems (NFS, SMB, Windows file sharing) + +For the same reasons as copy-on-write systems. + +## AWS EC2 t3a.nano with Ubuntu Linux + +The instance will run out of memory and crash every 12 hours or so. This instance size works when using Amazon Linux OS, but memory usage is very high and wouldn't be able to handle a lot of activity.
\ No newline at end of file diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 5d614d28..531355a5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -42,7 +42,7 @@ namespace slskd using slskd.Core.API; using slskd.Integrations.Pushbullet; using slskd.Messaging; - using slskd.Network; + using slskd.Relay; using slskd.Search; using slskd.Shares; using slskd.Transfers; @@ -89,7 +89,7 @@ namespace slskd IUserService userService, IShareService shareService, IPushbulletService pushbulletService, - INetworkService networkService, + IRelayService relayService, IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) { @@ -135,8 +135,8 @@ namespace slskd Users = userService; ApplicationHub = applicationHub; - Network = networkService; - Network.StateMonitor.OnChange(networkState => State.SetValue(state => state with { Network = networkState.Current })); + Relay = relayService; + Relay.StateMonitor.OnChange(relayState => State.SetValue(state => state with { Relay = relayState.Current })); LogHub = logHub; Program.LogEmitted += (_, log) => LogHub.EmitLogAsync(log); @@ -199,7 +199,7 @@ namespace slskd private IHubContext<LogsHub> LogHub { get; set; } private IUserService Users { get; set; } private IShareService Shares { get; set; } - private INetworkService Network { get; set; } + private IRelayService Relay { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; } private IEnumerable<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = Enumerable.Empty<Guid>(); @@ -398,17 +398,17 @@ namespace slskd { Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } - else if (OptionsAtStartup.Network.Mode.ToEnum<OperationMode>() == OperationMode.Agent) + else if (OptionsAtStartup.Relay.Mode.ToEnum<OperationMode>() == OperationMode.Agent) { - Log.Information("Running in Agent mode; not connecting to the Soulseek server."); - _ = Network.Client.StartAsync(cancellationToken); + Log.Information("Running in Agent relay mode; not connecting to the Soulseek server."); + await Relay.Client.StartAsync(cancellationToken); } else { - if (OptionsAtStartup.Network.Mode.ToEnum<OperationMode>() == OperationMode.Debug) + if (OptionsAtStartup.Relay.Mode.ToEnum<OperationMode>() == OperationMode.Debug) { - Log.Warning("Running in Debug network mode; connecting to controller"); - _ = Network.Client.StartAsync(cancellationToken); + Log.Warning("Running in Debug relay mode; connecting to controller"); + _ = Relay.Client.StartAsync(cancellationToken); } await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); @@ -1108,7 +1108,7 @@ namespace slskd if (rebuildBrowseCache) { _ = CacheBrowseResponse(); - _ = Network.Client.SynchronizeAsync(); + _ = Relay.Client.SynchronizeAsync(); } } diff --git a/src/slskd/Common/Exceptions/NetworkException.cs b/src/slskd/Common/Exceptions/RelayException.cs index 1fb903bb..11a6bd9e 100644 --- a/src/slskd/Common/Exceptions/NetworkException.cs +++ b/src/slskd/Common/Exceptions/RelayException.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkException.cs" company="slskd Team"> +// <copyright file="RelayException.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -22,31 +22,31 @@ namespace slskd using System.Runtime.Serialization; /// <summary> - /// Represents an error related to the slskd network feature. + /// Represents an error related to the slskd relay feature. /// </summary> [ExcludeFromCodeCoverage] [Serializable] - public class NetworkException : SlskdException + public class RelayException : SlskdException { /// <summary> - /// Initializes a new instance of the <see cref="NetworkException"/> class. + /// Initializes a new instance of the <see cref="RelayException"/> class. /// </summary> - public NetworkException() + public RelayException() : base() { } /// <summary> - /// Initializes a new instance of the <see cref="NetworkException"/> class with a specified error message. + /// Initializes a new instance of the <see cref="RelayException"/> class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> - public NetworkException(string message) + public RelayException(string message) : base(message) { } /// <summary> - /// Initializes a new instance of the <see cref="NetworkException"/> class with a specified error message and a + /// Initializes a new instance of the <see cref="RelayException"/> class with a specified error message and a /// reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The message that describes the error.</param> @@ -54,17 +54,17 @@ namespace slskd /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no /// inner exception is specified. /// </param> - public NetworkException(string message, Exception innerException) + public RelayException(string message, Exception innerException) : base(message, innerException) { } /// <summary> - /// Initializes a new instance of the <see cref="NetworkException"/> class with serialized data. + /// Initializes a new instance of the <see cref="RelayException"/> class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> - protected NetworkException(SerializationInfo info, StreamingContext context) + protected RelayException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e273229f..3a61e376 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -32,7 +32,7 @@ namespace slskd using slskd.Authentication; using slskd.Configuration; using slskd.Cryptography; - using slskd.Network; + using slskd.Relay; using slskd.Shares; using slskd.Validation; using Soulseek.Diagnostics; @@ -151,15 +151,6 @@ namespace slskd public bool Debug { get; init; } = Debugger.IsAttached; /// <summary> - /// Gets a value indicating whether the application should run in experimental mode. - /// </summary> - [Argument(default, "experimental")] - [EnvironmentVariable("EXPERIMENTAL")] - [Description("run in experimental mode")] - [RequiresRestart] - public bool Experimental { get; init; } = false; - - /// <summary> /// Gets a value indicating whether remote configuration of options is allowed. /// </summary> [Argument(default, "remote-configuration")] @@ -205,10 +196,10 @@ namespace slskd public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile; /// <summary> - /// Gets network options. + /// Gets relay options. /// </summary> [Validate] - public NetworkOptions Network { get; init; } = new NetworkOptions(); + public RelayOptions Relay { get; init; } = new RelayOptions(); /// <summary> /// Gets directory options. @@ -297,9 +288,9 @@ namespace slskd { var results = new List<ValidationResult>(); - if (InstanceName == "local" && Network.Mode.ToEnum<OperationMode>() == OperationMode.Agent) + if (InstanceName == "local" && Relay.Mode.ToEnum<OperationMode>() == OperationMode.Agent) { - results.Add(new ValidationResult("Instance name must be something other than 'local' when operating in Network Agent mode")); + results.Add(new ValidationResult("Instance name must be something other than 'local' when operating in Relay Agent mode")); } return results; @@ -372,32 +363,50 @@ namespace slskd [Description("log SQL queries generated by Entity Framework")] [RequiresRestart] public bool LogSQL { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should run in experimental mode. + /// </summary> + [Argument(default, "experimental")] + [EnvironmentVariable("EXPERIMENTAL")] + [Description("run in experimental mode")] + [RequiresRestart] + public bool Experimental { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should run in volatile mode. + /// </summary> + [Argument(default, "volatile")] + [EnvironmentVariable("VOLATILE")] + [Description("use volatile data storage (all data will be lost at shutdown)")] + [RequiresRestart] + public bool Volatile { get; init; } = false; } /// <summary> - /// Network options. + /// Relay options. /// </summary> - public class NetworkOptions : IValidatableObject + public class RelayOptions : IValidatableObject { /// <summary> /// Gets the application operation mode. /// </summary> - [Argument('m', "network-operation-mode")] - [EnvironmentVariable("NETWORK_OPERATION_MODE")] - [Description("network operation mode; controller, agent")] + [Argument('m', "relay-operation-mode")] + [EnvironmentVariable("RELAY_OPERATION_MODE")] + [Description("relay operation mode; controller, agent")] [RequiresRestart] [Enum(typeof(OperationMode))] - public string Mode { get; init; } = slskd.Network.OperationMode.Controller.ToString().ToLowerInvariant(); + public string Mode { get; init; } = slskd.Relay.OperationMode.Controller.ToString().ToLowerInvariant(); /// <summary> /// Gets the controller configuration. /// </summary> - public NetworkControllerConfigurationOptions Controller { get; init; } = new NetworkControllerConfigurationOptions(); + public RelayControllerConfigurationOptions Controller { get; init; } = new RelayControllerConfigurationOptions(); /// <summary> /// Gets the agent configuration. /// </summary> - public Dictionary<string, NetworkAgentConfigurationOptions> Agents { get; init; } = new(); + public Dictionary<string, RelayAgentConfigurationOptions> Agents { get; init; } = new(); public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { @@ -405,7 +414,7 @@ namespace slskd var results = new List<ValidationResult>(); var modeResults = new List<ValidationResult>(); - if (mode == slskd.Network.OperationMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true)) + if (mode == slskd.Relay.OperationMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true)) { results.Add(new CompositeValidationResult("Controller", modeResults)); } @@ -430,9 +439,9 @@ namespace slskd } /// <summary> - /// Network controller configuration options. + /// Relay controller configuration options. /// </summary> - public class NetworkControllerConfigurationOptions + public class RelayControllerConfigurationOptions { /// <summary> /// Gets the controller address. @@ -476,9 +485,9 @@ namespace slskd } /// <summary> - /// Network agent configuration options. + /// Relay agent configuration options. /// </summary> - public class NetworkAgentConfigurationOptions + public class RelayAgentConfigurationOptions { /// <summary> /// Gets the agent secret. diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index df670893..76253501 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -22,7 +22,7 @@ namespace slskd using System.Linq; using System.Net; using System.Text.Json.Serialization; - using slskd.Network; + using slskd.Relay; using slskd.Users; using Soulseek; @@ -35,7 +35,7 @@ namespace slskd public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } public ServerState Server { get; init; } = new ServerState(); - public NetworkState Network { get; init; } = new NetworkState(); + public RelayState Relay { get; init; } = new RelayState(); public UserState User { get; init; } = new UserState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); @@ -65,17 +65,17 @@ namespace slskd public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); } - public record NetworkState + public record RelayState { public OperationMode Mode { get; init; } - public NetworkControllerState Controller { get; init; } = new NetworkControllerState(); + public RelayControllerState Controller { get; init; } = new RelayControllerState(); public IReadOnlyCollection<Agent> Agents { get; init; } = Enumerable.Empty<Agent>().ToList().AsReadOnly(); } - public record NetworkControllerState + public record RelayControllerState { public string Address { get; init; } - public NetworkClientState State { get; init; } = NetworkClientState.Disconnected; + public RelayClientState State { get; init; } = RelayClientState.Disconnected; } public record UserState diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 3a4e923f..58b1252f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -58,7 +58,7 @@ namespace slskd using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Messaging; - using slskd.Network; + using slskd.Relay; using slskd.Search; using slskd.Search.API; using slskd.Shares; @@ -517,8 +517,16 @@ namespace slskd services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>(); - services.AddDbContext<SearchDbContext>($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); - services.AddDbContext<TransfersDbContext>($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); + if (OptionsAtStartup.Flags.Volatile) + { + services.AddDbContext<SearchDbContext>($"Data Source=file:search?mode=memory;Cache=shared;Pooling=True;"); + services.AddDbContext<TransfersDbContext>($"Data Source=file:transfers?mode=memory;Cache=shared;Pooling=True;"); + } + else + { + services.AddDbContext<SearchDbContext>($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); + services.AddDbContext<TransfersDbContext>($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); + } services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); @@ -535,7 +543,7 @@ namespace slskd services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); - services.AddSingleton<INetworkService, NetworkService>(); + services.AddSingleton<IRelayService, RelayService>(); services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddSingleton<IFTPService, FTPService>(); @@ -811,7 +819,7 @@ namespace slskd endpoints.MapHub<ApplicationHub>("/hub/application"); endpoints.MapHub<LogsHub>("/hub/logs"); endpoints.MapHub<SearchHub>("/hub/search"); - endpoints.MapHub<NetworkHub>("/hub/agents"); + endpoints.MapHub<RelayHub>("/hub/relay"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index b0e15663..3440c8ea 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkController.cs" company="slskd Team"> +// <copyright file="RelayController.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { using System; using System.Collections.Generic; @@ -31,21 +31,21 @@ namespace slskd.Network using slskd.Shares; /// <summary> - /// Network. + /// Relay. /// </summary> [Route("api/v{version:apiVersion}/[controller]")] [ApiVersion("0")] [ApiController] - public class NetworkController : ControllerBase + public class RelayController : ControllerBase { - public NetworkController( - INetworkService networkService) + public RelayController( + IRelayService relayService) { - Network = networkService; + Relay = relayService; } - private ILogger Log { get; } = Serilog.Log.ForContext<NetworkController>(); - private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<RelayController>(); + private IRelayService Relay { get; } [HttpPut("")] [Authorize(Policy = AuthPolicy.Any)] @@ -118,7 +118,7 @@ namespace slskd.Network return BadRequest(); } - if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) { return Unauthorized(); } @@ -129,7 +129,7 @@ namespace slskd.Network // provide the encrypted value as the credential with the request. the validation below verifies a bunch of // things, including that the encrypted value matches the expected value. the goal here is to ensure that the // caller is the same caller that received the request, and that the caller knows the shared secret. - if (!Network.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) + if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", agentName); return Unauthorized(); @@ -137,9 +137,9 @@ namespace slskd.Network Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName); - // pass the stream back to the network service, which will in turn pass it to the upload service, and use it to + // 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 Network.HandleFileStreamResponse(agentName, id: guid, stream); + await Relay.HandleFileStreamResponse(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); @@ -189,12 +189,12 @@ namespace slskd.Network return BadRequest(); } - if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) { return Unauthorized(); } - if (!Network.TryValidateShareUploadCredential(token: guid, agentName, credential)) + if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent}"); return Unauthorized(); @@ -214,7 +214,7 @@ namespace slskd.Network Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); - await Network.HandleShareUpload(agentName, id: guid, shares, temp); + await Relay.HandleShareUpload(agentName, id: guid, shares, temp); return Ok(); } diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 9a54dde5..ab14e064 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkHub.cs" company="slskd Team"> +// <copyright file="RelayHub.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { using System; using System.Threading.Tasks; @@ -25,9 +25,9 @@ namespace slskd.Network using Serilog; /// <summary> - /// Methods for the <see cref="NetworkHub"/>. + /// Methods for the <see cref="RelayHub"/>. /// </summary> - public interface INetworkHub + public interface IRelayHub { /// <summary> /// Sends an authentication challenge token to the newly connected agent. @@ -54,23 +54,23 @@ namespace slskd.Network } /// <summary> - /// The network SignalR hub. + /// The relay SignalR hub. /// </summary> [Authorize] - public class NetworkHub : Hub<INetworkHub> + public class RelayHub : Hub<IRelayHub> { /// <summary> - /// Initializes a new instance of the <see cref="NetworkHub"/> class. + /// Initializes a new instance of the <see cref="RelayHub"/> class. /// </summary> - /// <param name="networkService"></param> - public NetworkHub( - INetworkService networkService) + /// <param name="relayService"></param> + public RelayHub( + IRelayService relayService) { - Network = networkService; + Relay = relayService; } - private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); - private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<RelayService>(); + private IRelayService Relay { get; } /// <summary> /// Executed when a new connection is established. @@ -78,7 +78,7 @@ namespace slskd.Network /// <returns></returns> public override async Task OnConnectedAsync() { - var token = Network.GenerateAuthenticationChallengeToken(Context.ConnectionId); + var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); Log.Information("Agent connection {Id} established. Sending authentication challenge {Token}...", Context.ConnectionId, token); await Clients.Caller.Challenge(token); @@ -91,10 +91,10 @@ namespace slskd.Network /// <returns></returns> public override Task OnDisconnectedAsync(Exception exception) { - if (Network.TryDeregisterAgent(Context.ConnectionId, out var record)) + if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { Log.Warning("Agent {Agent} (connection {Id}) disconnected", record.Agent.Name, Context.ConnectionId); - Network.TryDeregisterAgent(record.Agent.Name, out _); + Relay.TryDeregisterAgent(record.Agent.Name, out _); } return Task.CompletedTask; @@ -108,10 +108,10 @@ namespace slskd.Network /// <exception cref="UnauthorizedAccessException">Thrown when the challenge response is invalid.</exception> public void Login(string agent, string challengeResponse) { - if (!Network.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) + if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); - Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! + Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } @@ -119,7 +119,7 @@ namespace slskd.Network var record = new Agent { Name = agent, IPAddress = remoteIp }; Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); - Network.RegisterAgent(Context.ConnectionId, record); + Relay.RegisterAgent(Context.ConnectionId, record); } /// <summary> @@ -129,27 +129,27 @@ namespace slskd.Network /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> public Guid BeginShareUpload() { - if (!Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) + if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in Log.Information("Agent connection {Id} requested a share upload token, but is not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } - var token = Network.GenerateShareUploadToken(record.Agent.Name); + var token = Relay.GenerateShareUploadToken(record.Agent.Name); Log.Information("Agent {Agent} (connection {Id}) requested share upload token {Token}", record.Agent.Name, record.ConnectionId, token); return token; } /// <summary> - /// Notifies the controller that the agent was unable to upload the file requested by a call to <see cref="INetworkHub.RequestFileUpload"/>. + /// Notifies 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> /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> public void NotifyFileUploadFailed(Guid id, Exception exception) { - if (!Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) + if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { Log.Warning("Agent connection {Id} attempted to report a failed upload, but is not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); @@ -157,11 +157,11 @@ namespace slskd.Network Log.Warning("Agent {Agent} (connection {ConnectionId}) reported upload failure for {Id}: {Message}", id, exception.Message); - Network.NotifyFileStreamException(id, exception); + Relay.NotifyFileStreamException(id, exception); } /// <summary> - /// Returns the response to a call to <see cref="INetworkHub.RequestFileInfo"/>. + /// Returns 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> @@ -169,7 +169,7 @@ namespace slskd.Network /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> public void ReturnFileInfo(Guid id, bool exists, long length) { - if (!Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) + if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { Log.Warning("Agent connection {Id} attempted to return file information, but is not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); @@ -177,7 +177,7 @@ namespace slskd.Network Log.Information("Agent {Agent} (connection {ConnectionId}) returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, id, exists, length); - Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); + Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } } }
\ No newline at end of file diff --git a/src/slskd/Network/DummyNetworkClient.cs b/src/slskd/Relay/DummyRelayClient.cs index f592f492..dca4f808 100644 --- a/src/slskd/Network/DummyNetworkClient.cs +++ b/src/slskd/Relay/DummyRelayClient.cs @@ -1,4 +1,4 @@ -// <copyright file="DummyNetworkClient.cs" company="slskd Team"> +// <copyright file="DummyRelayClient.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,14 +15,14 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { using System.Threading; using System.Threading.Tasks; - public class DummyNetworkClient : INetworkClient + public class DummyRelayClient : IRelayClient { - public IStateMonitor<NetworkClientState> StateMonitor => new ManagedState<NetworkClientState>(); + public IStateMonitor<RelayClientState> StateMonitor => new ManagedState<RelayClientState>(); public void Dispose() { } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Relay/RelayClient.cs index 207494ff..854399dd 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkClient.cs" company="slskd Team"> +// <copyright file="RelayClient.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -17,7 +17,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Network +namespace slskd.Relay { using System; using System.IO; @@ -30,14 +30,14 @@ namespace slskd.Network using slskd.Shares; /// <summary> - /// Network client (agent). + /// Relay client (agent). /// </summary> - public interface INetworkClient : IDisposable + public interface IRelayClient : IDisposable { /// <summary> /// Gets the client state. /// </summary> - IStateMonitor<NetworkClientState> StateMonitor { get; } + IStateMonitor<RelayClientState> StateMonitor { get; } /// <summary> /// Starts the client and connects to the controller. @@ -61,17 +61,17 @@ namespace slskd.Network } /// <summary> - /// Network client (agent). + /// Relay client (agent). /// </summary> - public class NetworkClient : INetworkClient + public class RelayClient : IRelayClient { /// <summary> - /// Initializes a new instance of the <see cref="NetworkClient"/> class. + /// Initializes a new instance of the <see cref="RelayClient"/> class. /// </summary> /// <param name="shareService"></param> /// <param name="optionsMonitor"></param> /// <param name="httpClientFactory"></param> - public NetworkClient( + public RelayClient( IShareService shareService, IOptionsMonitor<Options> optionsMonitor, IHttpClientFactory httpClientFactory) @@ -91,9 +91,9 @@ namespace slskd.Network /// <summary> /// Gets the client state. /// </summary> - public IStateMonitor<NetworkClientState> StateMonitor { get; } + public IStateMonitor<RelayClientState> StateMonitor { get; } - private ManagedState<NetworkClientState> State { get; } = new(); + private ManagedState<RelayClientState> State { get; } = new(); private IShareService Shares { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } @@ -102,7 +102,7 @@ namespace slskd.Network private HubConnection HubConnection { get; set; } private bool StartRequested { get; set; } private CancellationTokenSource StartCancellationTokenSource { get; set; } - private ILogger Log { get; } = Serilog.Log.ForContext<NetworkClient>(); + private ILogger Log { get; } = Serilog.Log.ForContext<RelayClient>(); private bool LoggedIn { get; set; } private TaskCompletionSource LoggedInTaskCompletionSource { get; set; } private bool Disposed { get; set; } @@ -114,18 +114,18 @@ namespace slskd.Network /// <returns></returns> public async Task StartAsync(CancellationToken cancellationToken = default) { - var mode = OptionsMonitor.CurrentValue.Network.Mode.ToEnum<OperationMode>(); + var mode = OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<OperationMode>(); if (mode != OperationMode.Agent && mode != OperationMode.Debug) { - throw new InvalidOperationException($"Network client can only be started when operation mode is {OperationMode.Agent}"); + throw new InvalidOperationException($"Relay client can only be started when operation mode is {OperationMode.Agent}"); } StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); LoggedInTaskCompletionSource = new TaskCompletionSource(); StartRequested = true; - Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); + Log.Information("Attempting to connect to the relay controller {Address}", OptionsMonitor.CurrentValue.Relay.Controller.Address); State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); @@ -135,15 +135,15 @@ namespace slskd.Network isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => { - Log.Debug(ex, "Network hub connection failure"); - Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message); + Log.Debug(ex, "Relay hub connection failure"); + Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); }, maxAttempts: int.MaxValue, maxDelayInMilliseconds: 30000, StartCancellationTokenSource.Token); State.SetValue(_ => TranslateState(HubConnection.State)); - Log.Information("Network controller connection established. Awaiting authentication..."); + Log.Information("Relay controller connection established. Awaiting authentication..."); await LoggedInTaskCompletionSource.Task; @@ -158,7 +158,7 @@ namespace slskd.Network catch (Exception ex) { Log.Error(ex, ex.Message); - Log.Error("Disconnecting from the network controller"); + Log.Error("Disconnecting from the relay controller"); await StopAsync(); throw; } @@ -181,7 +181,7 @@ namespace slskd.Network LoggedIn = false; - Log.Information("Network controller connection disconnected"); + Log.Information("Relay controller connection disconnected"); } } @@ -194,12 +194,12 @@ namespace slskd.Network return UploadSharesAsync(); } - private NetworkClientState TranslateState(HubConnectionState hub) => hub switch + private RelayClientState TranslateState(HubConnectionState hub) => hub switch { - HubConnectionState.Disconnected => NetworkClientState.Disconnected, - HubConnectionState.Connected => NetworkClientState.Connected, - HubConnectionState.Connecting => NetworkClientState.Connecting, - HubConnectionState.Reconnecting => NetworkClientState.Reconnecting, + HubConnectionState.Disconnected => RelayClientState.Disconnected, + HubConnectionState.Connected => RelayClientState.Connected, + HubConnectionState.Connecting => RelayClientState.Connecting, + HubConnectionState.Reconnecting => RelayClientState.Reconnecting, _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"), }; @@ -221,12 +221,12 @@ namespace slskd.Network Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync<Guid>(nameof(NetworkHub.BeginShareUpload)); + var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.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/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}"); using var content = new MultipartFormDataContent { { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, @@ -235,7 +235,7 @@ namespace slskd.Network { new StreamContent(stream), "database", "shares" }, }; - request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Network.Controller.ApiKey); + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Content = content; Log.Information("Beginning upload of shares"); @@ -243,7 +243,7 @@ namespace slskd.Network if (!response.IsSuccessStatusCode) { - throw new NetworkException($"Failed to upload shares to network controller: {response.StatusCode}"); + throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}"); } Log.Information("Upload shares succeeded"); @@ -258,7 +258,7 @@ namespace slskd.Network { var options = OptionsMonitor.CurrentValue; - var key = Pbkdf2.GetKey(options.Network.Controller.Secret, options.InstanceName, 48); + var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48); var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); return Aes.Encrypt(tokenBytes, key).ToBase62(); @@ -270,7 +270,7 @@ namespace slskd.Network { _ = Task.Run(async () => { - Log.Information("Network controller requested file {Filename} with ID {Id}", filename, token); + Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token); try { @@ -285,7 +285,7 @@ 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/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/files/{token}"); using var content = new MultipartFormDataContent { { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, @@ -293,7 +293,7 @@ namespace slskd.Network { new StreamContent(stream), "file", filename }, }; - request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Network.Controller.ApiKey); + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Content = content; Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); @@ -313,7 +313,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.NotifyFileUploadFailed), token); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); } }); @@ -322,7 +322,7 @@ 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); + Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); try { @@ -330,12 +330,12 @@ namespace slskd.Network var localFileInfo = new FileInfo(localFilename); - await HubConnection.InvokeAsync(nameof(NetworkHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + await HubConnection.InvokeAsync(nameof(RelayHub.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); + await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); } } @@ -343,7 +343,7 @@ namespace slskd.Network { try { - Log.Debug("Network controller sent an authentication challenge"); + Log.Debug("Relay controller sent an authentication challenge"); var options = OptionsMonitor.CurrentValue; @@ -351,14 +351,14 @@ namespace slskd.Network var response = ComputeCredential(challengeToken); Log.Debug("Logging in..."); - await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); + await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response); Log.Debug("Login succeeded."); LoggedInTaskCompletionSource?.TrySetResult(); } catch (UnauthorizedAccessException) { await HubConnection.StopAsync(); - Log.Error("Network controller authentication failed. Check configuration."); + Log.Error("Relay controller authentication failed. Check configuration."); } catch (Exception ex) { @@ -368,7 +368,7 @@ namespace slskd.Network private Task HubConnection_Closed(Exception arg) { - Log.Warning("Network controller connection closed: {Message}", arg.Message); + Log.Warning("Relay controller connection closed: {Message}", arg.Message); LoggedIn = false; State.SetValue(_ => TranslateState(HubConnection.State)); return Task.CompletedTask; @@ -376,7 +376,7 @@ namespace slskd.Network private Task HubConnection_Reconnecting(Exception arg) { - Log.Warning("Network controller connection reconnecting: {Message}", arg.Message); + Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message); LoggedIn = false; State.SetValue(_ => TranslateState(HubConnection.State)); return Task.CompletedTask; @@ -384,7 +384,7 @@ namespace slskd.Network private async Task HubConnection_Reconnected(string arg) { - Log.Warning("Network controller connection reconnected"); + Log.Warning("Relay controller connection reconnected"); // todo: does this need to log in again? does it retain the same connection id? LoggedIn = true; State.SetValue(_ => TranslateState(HubConnection.State)); @@ -393,7 +393,7 @@ namespace slskd.Network private HttpClient CreateHttpClient() { - var options = OptionsMonitor.CurrentValue.Network.Controller; + var options = OptionsMonitor.CurrentValue.Relay.Controller; HttpClient client; if (options.IgnoreCertificateErrors) @@ -416,7 +416,7 @@ namespace slskd.Network private void Configure(Options options) { - var mode = options.Network.Mode.ToEnum<OperationMode>(); + var mode = options.Relay.Mode.ToEnum<OperationMode>(); if (mode != OperationMode.Agent && mode != OperationMode.Debug) { @@ -427,14 +427,14 @@ namespace slskd.Network try { - var optionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson()); if (optionsHash == LastOptionsHash) { return; } - Log.Debug("Network options changed. Reconfiguring..."); + Log.Debug("Relay options changed. Reconfiguring..."); // if the client is attempting a connection, cancel it // it's going to be dropped when we create a new instance, but we need @@ -442,12 +442,12 @@ namespace slskd.Network StartCancellationTokenSource?.Cancel(); HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Network.Controller.Address}/hub/agents", builder => + .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder => { - builder.AccessTokenProvider = () => Task.FromResult(options.Network.Controller.ApiKey); + builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey); builder.HttpMessageHandlerFactory = (message) => { - if (message is HttpClientHandler clientHandler && options.Network.Controller.IgnoreCertificateErrors) + if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors) { clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true; } @@ -462,19 +462,19 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On<string, Guid>(nameof(INetworkHub.RequestFileUpload), HandleFileUploadRequest); - HubConnection.On<string, Guid>(nameof(INetworkHub.RequestFileInfo), HandleFileInfoRequest); - HubConnection.On<string>(nameof(INetworkHub.Challenge), HandleAuthenticationChallenge); + HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); + HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); + HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); LastOptionsHash = optionsHash; - Log.Debug("Network options reconfigured"); + Log.Debug("Relay options reconfigured"); // if start was requested (if StartAsync() was called externally), restart // after re-configuration if (StartRequested) { - Log.Information("Reconnecting the network controller connection..."); + Log.Information("Reconnecting the relay controller connection..."); _ = StartAsync(); } } diff --git a/src/slskd/Network/NetworkClientState.cs b/src/slskd/Relay/RelayClientState.cs index ba1c1369..def25411 100644 --- a/src/slskd/Network/NetworkClientState.cs +++ b/src/slskd/Relay/RelayClientState.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkClientState.cs" company="slskd Team"> +// <copyright file="RelayClientState.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,9 +15,9 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { - public enum NetworkClientState + public enum RelayClientState { Disconnected, Connected, diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Relay/RelayService.cs index a0bbe85f..2e986c84 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -1,4 +1,4 @@ -// <copyright file="NetworkService.cs" company="slskd Team"> +// <copyright file="RelayService.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -17,7 +17,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Network +namespace slskd.Relay { using System; using System.Collections.Concurrent; @@ -35,14 +35,14 @@ namespace slskd.Network using slskd.Shares; /// <summary> - /// Handles network (controller/agent) interactions. + /// Handles relay (controller/agent) interactions. /// </summary> - public interface INetworkService + public interface IRelayService { /// <summary> - /// Gets the network client (agent). + /// Gets the relay client (agent). /// </summary> - INetworkClient Client { get; } + IRelayClient Client { get; } /// <summary> /// Gets the collection of registered Agents. @@ -52,7 +52,7 @@ namespace slskd.Network /// <summary> /// Gets the state monitor for the service. /// </summary> - IStateMonitor<NetworkState> StateMonitor { get; } + IStateMonitor<RelayState> StateMonitor { get; } /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. @@ -245,26 +245,28 @@ namespace slskd.Network } /// <summary> - /// Handles network (controller/agent) interactions. + /// Handles relay (controller/agent) interactions. /// </summary> - public class NetworkService : INetworkService + public class RelayService : IRelayService { - public NetworkService( + public RelayService( IWaiter waiter, IShareService shareService, IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor<Options> optionsMonitor, - IHubContext<NetworkHub, INetworkHub> networkHub, + IHubContext<RelayHub, IRelayHub> relayHub, IHttpClientFactory httpClientFactory, - INetworkClient networkClient = null) + IRelayClient relayClient = null) { Shares = shareService; ShareRepositoryFactory = shareRepositoryFactory; Waiter = waiter; - NetworkHub = networkHub; + RelayHub = relayHub; + + HttpClientFactory = httpClientFactory; // wire up a dummy client so callers don't need to handle nulls - Client = networkClient ?? new DummyNetworkClient(); + Client = relayClient ?? new DummyRelayClient(); StateMonitor = State; @@ -274,9 +276,9 @@ namespace slskd.Network } /// <summary> - /// Gets the network client (agent). + /// Gets the relay client (agent). /// </summary> - public INetworkClient Client { get; private set; } + public IRelayClient Client { get; private set; } /// <summary> /// Gets the collection of registered Agents. @@ -286,19 +288,19 @@ namespace slskd.Network /// <summary> /// Gets the state monitor for the service. /// </summary> - public IStateMonitor<NetworkState> StateMonitor { get; } + public IStateMonitor<RelayState> StateMonitor { get; } private IHttpClientFactory HttpClientFactory { get; } - private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); + private ILogger Log { get; } = Serilog.Log.ForContext<RelayService>(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); - private IHubContext<NetworkHub, INetworkHub> NetworkHub { get; set; } + 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 IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareService Shares { get; } private IWaiter Waiter { get; } - private IManagedState<NetworkState> State { get; } = new ManagedState<NetworkState>(); + 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; } @@ -392,7 +394,7 @@ namespace slskd.Network try { - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); + await RelayHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, id); return await wait; @@ -466,7 +468,7 @@ namespace slskd.Network Log.Information("Created wait {Key}", key); - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileUpload(filename, id); + await RelayHub.Clients.Client(record.ConnectionId).RequestFileUpload(filename, id); Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, id); var task = await Task.WhenAny(wait, Task.Delay(timeout, cancellationToken)); @@ -662,7 +664,7 @@ namespace slskd.Network return false; } - if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions)) + if (!OptionsMonitor.CurrentValue.Relay.Agents.TryGetValue(agentName, out var agentOptions)) { Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agentName); return false; @@ -706,15 +708,15 @@ namespace slskd.Network try { - var optionsHash = Compute.Sha1Hash(options.Network.ToJson()); - var controllerOptionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + var optionsHash = Compute.Sha1Hash(options.Relay.ToJson()); + var controllerOptionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson()); if (optionsHash == LastOptionsHash || controllerOptionsHash == LastControllerOptionsHash) { return; } - var mode = options.Network.Mode.ToEnum<OperationMode>(); + var mode = options.Relay.Mode.ToEnum<OperationMode>(); if (mode == OperationMode.Controller) { @@ -727,16 +729,16 @@ namespace slskd.Network else { // the controller changed. disconnect and throw away the client and create a new one - Client = new NetworkClient(Shares, OptionsMonitor, HttpClientFactory); + Client = new RelayClient(Shares, OptionsMonitor, HttpClientFactory); Client.StateMonitor.OnChange(clientState => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); State.SetValue(state => state with { Mode = mode, - Controller = new NetworkControllerState() + Controller = new RelayControllerState() { - Address = options.Network.Controller.Address, + Address = options.Relay.Controller.Address, State = Client.StateMonitor.CurrentValue, }, }); @@ -761,7 +763,7 @@ namespace slskd.Network { try { - if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions)) + if (!OptionsMonitor.CurrentValue.Relay.Agents.TryGetValue(agentName, out var agentOptions)) { Log.Debug("Validation failed: Agent {Agent} not configured", agentName); return false; diff --git a/src/slskd/Network/Types/Agent.cs b/src/slskd/Relay/Types/Agent.cs index 8c392210..3ed1767e 100644 --- a/src/slskd/Network/Types/Agent.cs +++ b/src/slskd/Relay/Types/Agent.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { public record Agent { diff --git a/src/slskd/Network/Types/OperationMode.cs b/src/slskd/Relay/Types/OperationMode.cs index 7503c6c9..c572f0da 100644 --- a/src/slskd/Network/Types/OperationMode.cs +++ b/src/slskd/Relay/Types/OperationMode.cs @@ -15,10 +15,10 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Network +namespace slskd.Relay { /// <summary> - /// The network operation mode. + /// The relay operation mode. /// </summary> public enum OperationMode { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 1d1b6dfc..4c3a7298 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -446,7 +446,7 @@ namespace slskd.Transfers.Downloads /// <param name="transfer">The transfer to update.</param> public void Update(Transfer transfer) { - var experimental = OptionsMonitor.CurrentValue.Experimental; + var experimental = OptionsMonitor.CurrentValue.Flags.Experimental; var id = Guid.NewGuid(); System.Diagnostics.Stopwatch sw = default; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 77d91525..7a5a6e27 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -30,7 +30,7 @@ namespace slskd.Transfers.Uploads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; - using slskd.Network; + using slskd.Relay; using slskd.Shares; using slskd.Users; @@ -44,13 +44,13 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor<Options> optionsMonitor, IShareService shareService, - INetworkService networkService, + IRelayService relayService, IDbContextFactory<TransfersDbContext> contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; - Network = networkService; + Relay = relayService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -75,7 +75,7 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } - private INetworkService Network { get; } + private IRelayService Relay { get; } /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. @@ -137,7 +137,7 @@ namespace slskd.Transfers.Uploads } else { - var (exists, length) = await Network.GetFileInfoAsync(agentName: host, filename); + var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename); if (!exists || length <= 0) { @@ -269,11 +269,11 @@ namespace slskd.Transfers.Uploads username, filename, size: localFileLength, - inputStreamFactory: () => Network.GetFileStreamAsync(agentName: host, filename, id), + inputStreamFactory: () => Relay.GetFileStreamAsync(agentName: host, filename, id), options: topts, cancellationToken: cts.Token); - Network.TryCloseFileStream(host, id); + Relay.TryCloseFileStream(host, id); transfer = transfer.WithSoulseekTransfer(completedTransfer); } @@ -294,7 +294,7 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); - Network.TryCloseFileStream(host, id, ex); + Relay.TryCloseFileStream(host, id, ex); throw; } @@ -309,7 +309,7 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); - Network.TryCloseFileStream(host, id, ex); + Relay.TryCloseFileStream(host, id, ex); throw; } finally @@ -429,7 +429,7 @@ namespace slskd.Transfers.Uploads /// <param name="transfer">The transfer to update.</param> public void Update(Transfer transfer) { - var experimental = OptionsMonitor.CurrentValue.Experimental; + var experimental = OptionsMonitor.CurrentValue.Flags.Experimental; var id = Guid.NewGuid(); System.Diagnostics.Stopwatch sw = default; diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 0f06a677..c018ecfd 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -124,6 +124,29 @@ namespace slskd.Users.API } /// <summary> + /// Retrieves the files from the specified <paramref name="directory"/> from the specified <paramref name="username"/>. + /// </summary> + /// <param name="directory">The desired directory.</param> + /// <param name="username">The username of the user.</param> + /// <returns></returns> + [HttpGet("{username}/directory/{directory}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Directory), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Directory([FromRoute, Required] string username, [FromRoute, Required] string directory) + { + try + { + var result = await Client.GetDirectoryContentsAsync(username, directory); + return Ok(result); + } + catch (UserOfflineException ex) + { + return NotFound(ex.Message); + } + } + + /// <summary> /// Retrieves information about the specified <paramref name="username"/>. /// </summary> /// <param name="username">The username of the user.</param> diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js index 6493393f..fc3cb400 100644 --- a/src/web/src/components/Search/Response.js +++ b/src/web/src/components/Search/Response.js @@ -11,6 +11,7 @@ import { Icon, Label, } from 'semantic-ui-react'; +import { getDirectoryContents } from '../../lib/users'; const buildTree = (response) => { let { files = [], lockedFiles = [] } = response; @@ -59,6 +60,18 @@ class Response extends Component { }); }; + getFullDirectory = async (username, directory) => { + const { name, files } = await getDirectoryContents({ username, directory }); + files.forEach((file, index) => { + const newFilename = `${directory}\\${file.filename}`; + files[index] = { ...files[index], filename: newFilename }; + }); + + const newTree = this.state.tree; + newTree[name] = files; + this.setState({ tree: { ...newTree } }); + }; + toggleFolded = () => { this.setState({ isFolded: !this.state.isFolded }); }; @@ -107,6 +120,11 @@ class Response extends Component { files={tree[dir]} disabled={downloadRequest === 'inProgress'} onSelectionChange={this.onFileSelectionChange} + footer={<button + onClick={() => this.getFullDirectory(response.username, dir)} + style={{ cursor: 'pointer', width: '100%', backgroundColor: 'transparent', border: 'none' }}> + <Icon name='folder'/>Get Full Directory Contents + </button>} /> )} </Card.Content> diff --git a/src/web/src/components/Shared/FileList.js b/src/web/src/components/Shared/FileList.js index 9d19b886..3e171baf 100644 --- a/src/web/src/components/Shared/FileList.js +++ b/src/web/src/components/Shared/FileList.js @@ -1,36 +1,44 @@ -import React, {useState} from 'react'; +import React, { useState } from 'react'; import { formatSeconds, formatBytes, getFileName, formatAttributes } from '../../lib/util'; -import { - Header, - Table, - Icon, - List, +import { + Header, + Table, + Icon, + List, Checkbox, } from 'semantic-ui-react'; -const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, onClose }) => { +const FileList = ({ + directoryName, + files, + locked, + onSelectionChange, + disabled, + onClose, + footer, +}) => { const [folded, setFolded] = useState(false); return ( - <div style={{opacity: locked ? 0.5 : 1}}> - <Header - size='small' + <div style={{ opacity: locked ? 0.5 : 1 }}> + <Header + size='small' className='filelist-header' > <div> - <Icon - size='large' - link={!locked} + <Icon + size='large' + link={!locked} name={locked ? 'lock' : folded ? 'folder' : 'folder open'} onClick={() => !locked && setFolded(!folded)}/> {directoryName} - - {!!onClose && <Icon - className='close-button' - name='close' + + {!!onClose && <Icon + className='close-button' + name='close' color='red' link onClick={() => onClose()} @@ -43,7 +51,7 @@ const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, o <Table.Header> <Table.Row> <Table.HeaderCell className='filelist-selector'> - <Checkbox + <Checkbox fitted onChange={(event, data) => files.map(f => onSelectionChange(f, data.checked))} checked={files.filter(f => !f.selected).length === 0} @@ -57,11 +65,11 @@ const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, o </Table.Row> </Table.Header> <Table.Body> - {files.sort((a, b) => a.filename > b.filename ? 1 : -1).map((f, i) => + {files.sort((a, b) => a.filename > b.filename ? 1 : -1).map((f, i) => <Table.Row key={i}> <Table.Cell className='filelist-selector'> - <Checkbox - fitted + <Checkbox + fitted onChange={(event, data) => onSelectionChange(f, data.checked)} checked={f.selected} disabled={disabled} @@ -76,6 +84,13 @@ const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, o </Table.Row> )} </Table.Body> + {footer && <Table.Footer fullWidth> + <Table.Row> + <Table.HeaderCell colSpan='5'> + {footer} + </Table.HeaderCell> + </Table.Row> + </Table.Footer>} </Table> </List.Item> </List>} diff --git a/src/web/src/lib/users.js b/src/web/src/lib/users.js index f79cea20..9107a0ca 100644 --- a/src/web/src/lib/users.js +++ b/src/web/src/lib/users.js @@ -18,4 +18,8 @@ export const browse = async ({ username }) => { export const getBrowseStatus = ({ username }) => { return api.get(`/users/${encodeURIComponent(username)}/browse/status`); +}; + +export const getDirectoryContents = async ({ username, directory }) => { + return (await api.get(`/users/${encodeURIComponent(username)}/directory/${encodeURIComponent(directory)}`)).data; };
\ No newline at end of file |
