diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-06-25 19:10:27 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-06-25 19:10:27 -0500 |
| commit | a8deb4361362ed01c930447dcfa92a9b756d03c0 (patch) | |
| tree | b29508c1d3ba35a7f8b664984ee628b0e466ef5c /src/slskd/Core | |
| parent | 037c6b2bbb37442fb09eb5163ecfe84f2adb3fa9 (diff) | |
| download | slskd-a8deb4361362ed01c930447dcfa92a9b756d03c0.tar.gz | |
move some things into Core
Diffstat (limited to 'src/slskd/Core')
| -rw-r--r-- | src/slskd/Core/CacheKeys.cs | 24 | ||||
| -rw-r--r-- | src/slskd/Core/CoreExtensions.cs | 75 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 1340 | ||||
| -rw-r--r-- | src/slskd/Core/QueueStrategy.cs | 35 | ||||
| -rw-r--r-- | src/slskd/Core/State.cs | 134 |
5 files changed, 1608 insertions, 0 deletions
diff --git a/src/slskd/Core/CacheKeys.cs b/src/slskd/Core/CacheKeys.cs new file mode 100644 index 00000000..b5a335c1 --- /dev/null +++ b/src/slskd/Core/CacheKeys.cs @@ -0,0 +1,24 @@ +// <copyright file="CacheKeys.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 +{ + public static class CacheKeys + { + public static readonly string UserStatisticsToken = nameof(UserStatisticsToken); + } +} diff --git a/src/slskd/Core/CoreExtensions.cs b/src/slskd/Core/CoreExtensions.cs new file mode 100644 index 00000000..aef187b8 --- /dev/null +++ b/src/slskd/Core/CoreExtensions.cs @@ -0,0 +1,75 @@ +// <copyright file="CoreExtensions.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 +{ + using System; + using System.Net.Sockets; + using Soulseek; + + /// <summary> + /// Core extensions; extensions for types specific to Soulseek or slskd. + /// </summary> + public static class CoreExtensions + { + /// <summary> + /// Redacts this instance of Options, replacing properties marked with <see cref="SecretAttribute"/> with '*****'. + /// </summary> + /// <remarks> + /// Creates a deep clone before redacting. + /// </remarks> + /// <param name="options">The Options instance to redact.</param> + /// <returns>A redacted instance.</returns> + public static Options Redact(this Options options) + { + var redacted = options.ToJson().FromJson<Options>(); + Redactor.Redact(redacted, redactWith: "*****"); + return redacted; + } + + /// <summary> + /// Creates a copy of this instance with the specified parameters changed. + /// </summary> + /// <param name="o">The options instance to copy.</param> + /// <param name="readBufferSize">The read buffer size for underlying TCP connections.</param> + /// <param name="writeBufferSize">The write buffer size for underlying TCP connections.</param> + /// <param name="writeQueueSize">The size of the write queue for double buffered writes.</param> + /// <param name="connectTimeout">The connection timeout, in milliseconds, for client and peer TCP connections.</param> + /// <param name="inactivityTimeout">The inactivity timeout, in milliseconds, for peer TCP connections.</param> + /// <param name="proxyOptions">Optional SOCKS 5 proxy configuration options.</param> + /// <param name="configureSocketAction"> + /// The delegate invoked during instantiation to configure the server Socket instance. + /// </param> + /// <returns>The new instance.</returns> + public static ConnectionOptions With( + this ConnectionOptions o, + int? readBufferSize = null, + int? writeBufferSize = null, + int? writeQueueSize = null, + int? connectTimeout = null, + int? inactivityTimeout = null, + ProxyOptions proxyOptions = null, + Action<Socket> configureSocketAction = null) => new ConnectionOptions( + readBufferSize: readBufferSize ?? o.ReadBufferSize, + writeBufferSize: writeBufferSize ?? o.WriteBufferSize, + writeQueueSize: writeQueueSize ?? o.WriteQueueSize, + connectTimeout: connectTimeout ?? o.ConnectTimeout, + inactivityTimeout: inactivityTimeout ?? o.InactivityTimeout, + proxyOptions: proxyOptions ?? o.ProxyOptions, + configureSocket: configureSocketAction ?? o.ConfigureSocket); + } +} diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs new file mode 100644 index 00000000..6543d748 --- /dev/null +++ b/src/slskd/Core/Options.cs @@ -0,0 +1,1340 @@ +// <copyright file="Options.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Text.Json.Serialization; + using System.Text.RegularExpressions; + using FluentFTP; + using slskd.Configuration; + using slskd.Core; + using slskd.Validation; + using Soulseek.Diagnostics; + using Utility.CommandLine; + using Utility.EnvironmentVariables; + using YamlDotNet.Serialization; + + /// <summary> + /// Disambiguates options derived at startup from options that may update at run time. + /// </summary> + /// <remarks> + /// This class is added directly to dependency injection, but <see cref="Options"/> is not, so consumers must inject <see cref="OptionsAtStartup"/> + /// instead of <see cref="Options"/> to make it clear that these options will not change. Options that may change should be accessed by injecting + /// <see cref="IOptionsMonitor{T}"/> or <see cref="IOptionsSnapshot{T}"/>, depending on the lifetime of the component. + /// </remarks> + public class OptionsAtStartup : Options + { + } + + /// <summary> + /// Application options. + /// </summary> + /// <remarks> + /// <para> + /// This class contains all application options, which may be sourced from (in order of precedence): + /// <list type="bullet"> + /// <item> + /// <term>Defaults</term> + /// <description>Default values, statically defined in this class.</description> + /// </item> + /// <item> + /// <term>Environment Variables</term> + /// <description>Environment variables set at either the system or user scope.</description> + /// </item> + /// <item> + /// <term>YAML Configuration File</term> + /// <description>A YAML file containing a mapping of this class.</description> + /// </item> + /// <item> + /// <term>Command Line</term> + /// <description>Options provided via the command line when starting the application.</description> + /// </item> + /// </list> + /// </para> + /// <para> + /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting + /// <see cref="IOptionsMonitor{T}"/> in components with a singleton lifetime, or <see cref="IOptionsSnapshot{T}"/> for transient or scoped lifetimes. + /// </para> + /// <para> + /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject <see cref="OptionsAtStartup"/>. + /// </para> + /// <para> + /// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable + /// nature of the command line string after the application is started. + /// </para> + /// </remarks> + public class Options + { + /// <summary> + /// Gets a value indicating whether to display the application version. + /// </summary> + [Argument('v', "version")] + [Description("display version information")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool ShowVersion { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to display a list of command line arguments. + /// </summary> + [Argument('h', "help")] + [Description("display command line usage")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool ShowHelp { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to display a list of configuration environment variables. + /// </summary> + [Argument('e', "envars")] + [Description("display environment variables")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool ShowEnvironmentVariables { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to generate an X509 certificate and password. + /// </summary> + [Argument('g', "generate-cert")] + [Description("generate X509 certificate and password for HTTPS")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool GenerateCertificate { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should run in debug mode. + /// </summary> + [Argument('d', "debug")] + [EnvironmentVariable("DEBUG")] + [Description("run in debug mode")] + [RequiresRestart] + public bool Debug { get; init; } = Debugger.IsAttached; + + /// <summary> + /// Gets a value indicating whether the logo should be suppressed on startup. + /// </summary> + [Argument('n', "no-logo")] + [EnvironmentVariable("NO_LOGO")] + [Description("suppress logo on startup")] + [RequiresRestart] + public bool NoLogo { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should quit after initialization. + /// </summary> + [Argument('x', "no-start")] + [EnvironmentVariable("NO_START")] + [Description("quit the application after initialization")] + [RequiresRestart] + public bool NoStart { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should connect to the Soulseek network on startup. + /// </summary> + [Argument(default, "no-connect")] + [EnvironmentVariable("NO_CONNECT")] + [Description("do not connect to the Soulseek network on startup")] + [RequiresRestart] + public bool NoConnect { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should scan shared directories on startup. + /// </summary> + [Argument(default, "no-share-scan")] + [EnvironmentVariable("NO_SHARE_SCAN")] + [Description("do not scan shares on startup")] + [RequiresRestart] + public bool NoShareScan { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the application should check for a newer version on startup. + /// </summary> + [Argument(default, "no-version-check")] + [EnvironmentVariable("NO_VERSION_CHECK")] + [Description("do not check for newer version at startup")] + [RequiresRestart] + public bool NoVersionCheck { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether remote configuration of options is allowed. + /// </summary> + [Argument(default, "remote-configuration")] + [EnvironmentVariable("REMOTE_CONFIGURATION")] + [Description("allow remote configuration")] + public bool RemoteConfiguration { get; init; } = false; + + /// <summary> + /// Gets the unique name for this instance. + /// </summary> + [Argument('i', "instance-name")] + [EnvironmentVariable("INSTANCE_NAME")] + [Description("optional; a unique name for this instance")] + [RequiresRestart] + public string InstanceName { get; init; } = "default"; + + /// <summary> + /// Gets the path where application data is saved. + /// </summary> + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public string AppDirectory { get; init; } = Program.DefaultAppDirectory; + + /// <summary> + /// Gets the path where application data is saved. + /// </summary> + [Argument('c', "config")] + [EnvironmentVariable("CONFIG")] + [Description("path to configuration file")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile; + + /// <summary> + /// Gets directory options. + /// </summary> + [Validate] + [RequiresRestart] + public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); + + /// <summary> + /// Gets global options. + /// </summary> + [Validate] + public GlobalOptions Global { get; init; } = new GlobalOptions(); + + /// <summary> + /// Gets user groups. + /// </summary> + [Validate] + public GroupsOptions Groups { get; init; } = new GroupsOptions(); + + /// <summary> + /// Gets filter options. + /// </summary> + [Validate] + public FiltersOptions Filters { get; init; } = new FiltersOptions(); + + /// <summary> + /// Gets a list of rooms to automatically join upon connection. + /// </summary> + [Argument(default, "rooms")] + [EnvironmentVariable("ROOMS")] + [Description("a list of rooms to automatically join")] + public string[] Rooms { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Gets options for the web UI. + /// </summary> + [Validate] + public WebOptions Web { get; init; } = new WebOptions(); + + /// <summary> + /// Gets logger options. + /// </summary> + [Validate] + [RequiresRestart] + public LoggerOptions Logger { get; init; } = new LoggerOptions(); + + /// <summary> + /// Gets feature options. + /// </summary> + [Validate] + [RequiresRestart] + public FeatureOptions Feature { get; init; } = new FeatureOptions(); + + /// <summary> + /// Gets options for the Soulseek client. + /// </summary> + [Validate] + public SoulseekOptions Soulseek { get; init; } = new SoulseekOptions(); + + /// <summary> + /// Gets options for external integrations. + /// </summary> + [Validate] + public IntegrationOptions Integration { get; init; } = new IntegrationOptions(); + + /// <summary> + /// Directory options. + /// </summary> + public class DirectoriesOptions : IValidatableObject + { + /// <summary> + /// Gets the path where incomplete downloads are saved. + /// </summary> + [Argument(default, "incomplete")] + [EnvironmentVariable("INCOMPLETE_DIR")] + [Description("path where incomplete downloads are saved")] + [DirectoryExists(ensureWriteable: true)] + [RequiresRestart] + public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; + + /// <summary> + /// Gets the path where downloaded files are saved. + /// </summary> + [Argument('o', "downloads")] + [EnvironmentVariable("DOWNLOADS_DIR")] + [Description("path where downloaded files are saved")] + [DirectoryExists(ensureWriteable: true)] + [RequiresRestart] + public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; + + /// <summary> + /// Gets the list of paths to shared files. + /// </summary> + [Argument('s', "shared")] + [EnvironmentVariable("SHARED_DIR")] + [Description("path to shared files")] + public string[] Shared { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + bool IsBlankPath(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])$"); + Shared.Where(share => IsBlankPath(share)).ToList() + .ForEach(blank => results.Add(new ValidationResult($"Share {blank} doees not specify a path"))); + + bool IsRootMount(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])/$"); + Shared.Where(share => IsRootMount(share)).ToList() + .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); + + // starts with '/', 'X:', or '\\' + bool IsAbsolutePath(string share) => Regex.IsMatch(share.ToLocalOSPath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + Shared.Where(share => !IsAbsolutePath(share)).ToList() + .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + + (string Raw, string Alias, string Path) Digest(string share) + { + var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); + + if (matches.Any()) + { + return (share, matches[0].Groups[2].Value, matches[0].Groups[3].Value); + } + + return (share, share.Split(new[] { '/', '\\' }).Last(), share); + } + + var digestedShared = Shared + .Select(share => Digest(share.TrimEnd('/', '\\'))) + .ToHashSet(); + + // make sure all aliases are distinct + digestedShared.GroupBy(share => share.Alias).Where(group => group.Count() > 1).ToList() + .ForEach(overlap => results.Add(new ValidationResult($"Shares {string.Join(", ", overlap.Select(s => $"'{s.Raw}'"))} collide. Specify an alias for one or both to disambiguate them."))); + + // make sure the same path hasn't been specified twice, under different aliases + digestedShared.GroupBy(share => share.Path).Where(group => group.Count() > 1).ToList() + .ForEach(dupe => results.Add(new ValidationResult($"Shares {string.Join(", ", dupe.Select(s => $"'{s.Raw}'"))} alias the same path"))); + + // make sure each share has an alias, or is alias-able, and that the alias is valid + foreach (var share in digestedShared) + { + if (string.IsNullOrWhiteSpace(share.Alias)) + { + results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; alias may not be null, empty or consist of only whitespace")); + } + else if (share.Alias.Contains('\\') || share.Alias.Contains('/')) + { + results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'")); + } + } + + return results; + } + } + + /// <summary> + /// Global options. + /// </summary> + public class GlobalOptions + { + /// <summary> + /// Gets global upload options. + /// </summary> + [Validate] + public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); + + /// <summary> + /// Gets global download options. + /// </summary> + [Validate] + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); + + /// <summary> + /// Global upload options. + /// </summary> + public class GlobalUploadOptions + { + /// <summary> + /// Gets the limit for the total number of upload slots. + /// </summary> + [Argument(default, "upload-slots")] + [EnvironmentVariable("UPLOAD_SLOTS")] + [Description("the total number of upload slots")] + [RequiresRestart] + [Range(1, int.MaxValue)] + public int Slots { get; init; } = 10; + + /// <summary> + /// Gets the total upload speed limit. + /// </summary> + [Argument(default, "upload-speed-limit")] + [EnvironmentVariable("UPLOAD_SPEED_LIMIT")] + [Description("the total upload speed limit")] + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + + /// <summary> + /// Gets global download options. + /// </summary> + public class GlobalDownloadOptions + { + /// <summary> + /// Gets the limit for the total number of download slots. + /// </summary> + [Argument(default, "download-slots")] + [EnvironmentVariable("DOWNLOAD_SLOTS")] + [Description("the total number of download slots")] + [RequiresRestart] + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// <summary> + /// Gets the total download speed limit. + /// </summary> + [Argument(default, "download-speed-limit")] + [EnvironmentVariable("DOWNLOAD_SPEED_LIMIT")] + [Description("the total download speed limit")] + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + } + + /// <summary> + /// User groups. + /// </summary> + public class GroupsOptions : IValidatableObject + { + /// <summary> + /// Gets options for the default user group. + /// </summary> + /// <remarks> + /// These options apply to users that are not privileged, have not been identified as leechers, + /// and have not been added as a member of any group. + /// </remarks> + [Validate] + public BuiltInOptions Default { get; init; } = new BuiltInOptions(); + + /// <summary> + /// Gets options for the leecher user group. + /// </summary> + /// <remarks> + /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. + /// </remarks> + [Validate] + public LeecherOptions Leechers { get; init; } = new LeecherOptions(); + + /// <summary> + /// Gets user defined groups and options. + /// </summary> + [Validate] + public Dictionary<string, UserDefinedOptions> UserDefined { get; init; } = new Dictionary<string, UserDefinedOptions>(); + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup }; + var intersection = UserDefined.Keys.Intersect(builtInGroups); + + return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); + } + + /// <summary> + /// Built in user group options. + /// </summary> + public class BuiltInOptions + { + /// <summary> + /// Gets upload options. + /// </summary> + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + } + + /// <summary> + /// Built in leecher group options. + /// </summary> + public class LeecherOptions + { + /// <summary> + /// Gets leecher threshold options. + /// </summary> + [Validate] + public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); + + /// <summary> + /// Gets upload options. + /// </summary> + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + } + + /// <summary> + /// Leecher threshold options. + /// </summary> + public class ThresholdOptions + { + /// <summary> + /// Gets the minimum number of shared files required to avoid being classified as a leecher. + /// </summary> + [Range(1, int.MaxValue)] + public int Files { get; init; } = 1; + + /// <summary> + /// Gets the minimum number of shared directories required to avoid being classified as a leecher. + /// </summary> + [Range(1, int.MaxValue)] + public int Directories { get; init; } = 1; + } + + /// <summary> + /// User defined user group options. + /// </summary> + public class UserDefinedOptions + { + /// <summary> + /// Gets upload options. + /// </summary> + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + + /// <summary> + /// Gets the list of group member usernames. + /// </summary> + public string[] Members { get; init; } = Array.Empty<string>(); + } + + /// <summary> + /// User group upload options. + /// </summary> + public class UploadOptions + { + /// <summary> + /// Gets the priority of the group. + /// </summary> + [Range(1, int.MaxValue)] + public int Priority { get; init; } = 1; + + /// <summary> + /// Gets the queue strategy for the group. + /// </summary> + [Enum(typeof(QueueStrategy))] + public string Strategy { get; init; } = QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets the limit for the total number of upload slots for the group. + /// </summary> + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// <summary> + /// Gets the total upload speed limit for the group. + /// </summary> + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + } + + /// <summary> + /// Feature options. + /// </summary> + public class FeatureOptions + { + /// <summary> + /// Gets a value indicating whether prometheus metrics should be collected and published. + /// </summary> + [Argument(default, "prometheus")] + [EnvironmentVariable("PROMETHEUS")] + [Description("enable collection and publishing of prometheus metrics")] + [RequiresRestart] + public bool Prometheus { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether swagger documentation and UI should be enabled. + /// </summary> + [Argument(default, "swagger")] + [EnvironmentVariable("SWAGGER")] + [Description("enable swagger documentation and UI")] + [RequiresRestart] + public bool Swagger { get; init; } = false; + } + + /// <summary> + /// Filter options. + /// </summary> + public class FiltersOptions : IValidatableObject + { + /// <summary> + /// Gets the list of shared file filters. + /// </summary> + [Argument(default, "share-filter")] + [EnvironmentVariable("SHARE_FILTER")] + [Description("regular expressions to filter files from shares")] + public string[] Share { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + foreach (var filter in Share) + { + if (!filter.IsValidRegex()) + { + results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); + } + } + + return results; + } + } + + /// <summary> + /// Logger options. + /// </summary> + public class LoggerOptions + { + /// <summary> + /// Gets the URL to a Grafana Loki instance to which to log. + /// </summary> + [Argument(default, "loki")] + [EnvironmentVariable("LOKI")] + [Description("optional; url to a Grafana Loki instance to which to log")] + [RequiresRestart] + public string Loki { get; init; } = null; + } + + /// <summary> + /// Soulseek client options. + /// </summary> + public class SoulseekOptions + { + /// <summary> + /// Gets the username for the Soulseek network. + /// </summary> + [Argument(default, "slsk-username")] + [EnvironmentVariable("SLSK_USERNAME")] + [Description("username for the Soulseek network")] + [RequiresReconnect] + public string Username { get; init; } = null; + + /// <summary> + /// Gets the password for the Soulseek network. + /// </summary> + [Argument(default, "slsk-password")] + [EnvironmentVariable("SLSK_PASSWORD")] + [Description("password for the Soulseek network")] + [Secret] + [RequiresReconnect] + public string Password { get; init; } = null; + + /// <summary> + /// Gets the description of the Soulseek user. + /// </summary> + [Argument(default, "slsk-description")] + [EnvironmentVariable("SLSK_DESCRIPTION")] + [Description("user description for the Soulseek network")] + public string Description { get; init; } = "A slskd user. https://github.com/slskd/slskd"; + + /// <summary> + /// Gets the port on which to listen for incoming connections. + /// </summary> + [Argument(default, "slsk-listen-port")] + [EnvironmentVariable("SLSK_LISTEN_PORT")] + [Description("port on which to listen for incoming connections")] + [Range(1024, 65535)] + public int ListenPort { get; init; } = 50000; + + /// <summary> + /// Gets the minimum diagnostic level. + /// </summary> + [Argument(default, "slsk-diag-level")] + [EnvironmentVariable("SLSK_DIAG_LEVEL")] + [Description("minimum diagnostic level (None, Warning, Info, Debug)")] + [RequiresRestart] + public DiagnosticLevel DiagnosticLevel { get; init; } = DiagnosticLevel.Info; + + /// <summary> + /// Gets options for the distributed network. + /// </summary> + [Validate] + public DistributedNetworkOptions DistributedNetwork { get; init; } = new DistributedNetworkOptions(); + + /// <summary> + /// Gets connection options. + /// </summary> + [Validate] + public ConnectionOptions Connection { get; init; } = new ConnectionOptions(); + + /// <summary> + /// Connection options. + /// </summary> + public class ConnectionOptions + { + /// <summary> + /// Gets connection timeout options. + /// </summary> + [Validate] + public TimeoutOptions Timeout { get; init; } = new TimeoutOptions(); + + /// <summary> + /// Gets connection buffer options. + /// </summary> + [Validate] + public BufferOptions Buffer { get; init; } = new BufferOptions(); + + /// <summary> + /// Gets connection proxy options. + /// </summary> + [Validate] + public ProxyOptions Proxy { get; init; } = new ProxyOptions(); + + /// <summary> + /// Connection buffer options. + /// </summary> + public class BufferOptions + { + /// <summary> + /// Gets the connection read buffer size, in bytes. + /// </summary> + [Argument(default, "slsk-read-buffer")] + [EnvironmentVariable("SLSK_READ_BUFFER")] + [Description("read buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Read { get; init; } = 16384; + + /// <summary> + /// Gets the connection write buffer size, in bytes. + /// </summary> + [Argument(default, "slsk-write-buffer")] + [EnvironmentVariable("SLSK_WRITE_BUFFER")] + [Description("write buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Write { get; init; } = 16384; + + /// <summary> + /// Gets the read/write buffer size for transfers, in bytes. + /// </summary> + [Argument(default, "slsk-transfer-buffer")] + [EnvironmentVariable("SLSK_TRANSFER_BUFFER")] + [Description("read/write buffer size for transfers")] + [Range(81920, int.MaxValue)] + public int Transfer { get; init; } = 262144; + + /// <summary> + /// Gets the size of the queue for double buffered writes. + /// </summary> + [Argument(default, "slsk-write-queue")] + [EnvironmentVariable("SLSK_WRITE_QUEUE")] + [Description("queue size for double buffered writes")] + [Range(5, 5000)] + public int WriteQueue { get; init; } = 50; + } + + /// <summary> + /// Connection timeout options. + /// </summary> + public class TimeoutOptions + { + /// <summary> + /// Gets the connection timeout value, in milliseconds. + /// </summary> + [Argument(default, "slsk-connection-timeout")] + [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] + [Description("connection timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Connect { get; init; } = 10000; + + /// <summary> + /// Gets the connection inactivity timeout, in milliseconds. + /// </summary> + [Argument(default, "slsk-inactivity-timeout")] + [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] + [Description("connection inactivity timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Inactivity { get; init; } = 15000; + } + + /// <summary> + /// Connection proxy options. + /// </summary> + public class ProxyOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the proxy is enabled. + /// </summary> + [Argument(default, "slsk-proxy")] + [EnvironmentVariable("SLSK_PROXY_ENABLED")] + [Description("enable connection proxy")] + public bool Enabled { get; init; } = false; + + /// <summary> + /// Gets the proxy address. + /// </summary> + [Argument(default, "slsk-proxy-address")] + [EnvironmentVariable("SLSK_PROXY_ADDRESS")] + [Description("connection proxy address")] + [StringLength(255, MinimumLength = 1)] + public string Address { get; init; } + + /// <summary> + /// Gets the proxy port. + /// </summary> + [Argument(default, "slsk-proxy-port")] + [EnvironmentVariable("SLSK_PROXY_PORT")] + [Description("connection proxy port")] + [Range(1, 65535)] + public int? Port { get; init; } + + /// <summary> + /// Gets the proxy username, if applicable. + /// </summary> + [Argument(default, "slsk-proxy-username")] + [EnvironmentVariable("SLSK_PROXY_USERNAME")] + [Description("connection proxy username")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; init; } + + /// <summary> + /// Gets the proxy password, if applicable. + /// </summary> + [Argument(default, "slsk-proxy-password")] + [EnvironmentVariable("SLSK_PROXY_PASSWORD")] + [Description("connection proxy password")] + [StringLength(255, MinimumLength = 1)] + [Secret] + public string Password { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + if (Enabled && !Port.HasValue) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Port has been specified.")); + } + + return results; + } + } + } + + /// <summary> + /// Distributed network options. + /// </summary> + public class DistributedNetworkOptions + { + /// <summary> + /// Gets a value indicating whether the distributed network should be disabled. + /// </summary> + [Argument(default, "slsk-no-dnet")] + [EnvironmentVariable("SLSK_NO_DNET")] + [Description("disable the distributed network")] + public bool Disabled { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to accept distributed child connections. + /// </summary> + [Argument(default, "slsk-dnet-no-children")] + [EnvironmentVariable("SLSK_DNET_NO_CHILDREN")] + [Description("do not accept distributed children")] + public bool DisableChildren { get; init; } = false; + + /// <summary> + /// Gets the distributed child connection limit. + /// </summary> + [Argument(default, "slsk-dnet-children")] + [EnvironmentVariable("SLSK_DNET_CHILDREN")] + [Description("max number of distributed children")] + [Range(1, int.MaxValue)] + public int ChildLimit { get; init; } = 25; + + /// <summary> + /// Gets a value indicating whether distributed network logging should be enabled. + /// </summary> + [Argument(default, "slsk-dnet-logging")] + [EnvironmentVariable("SLSK_DNET_LOGGING")] + [Description("enable distributed network logging")] + public bool Logging { get; init; } = false; + } + } + + /// <summary> + /// Web server options. + /// </summary> + public class WebOptions + { + /// <summary> + /// Gets the HTTP listen port. + /// </summary> + [Argument('l', "http-port")] + [EnvironmentVariable("HTTP_PORT")] + [Description("HTTP listen port for web UI")] + [Range(1, 65535)] + [RequiresRestart] + public int Port { get; init; } = 5000; + + /// <summary> + /// Gets HTTPS options. + /// </summary> + [Validate] + [RequiresRestart] + public HttpsOptions Https { get; init; } = new HttpsOptions(); + + /// <summary> + /// Gets the base url for web requests. + /// </summary> + [Argument(default, "url-base")] + [EnvironmentVariable("URL_BASE")] + [Description("base url for web requests")] + [RequiresRestart] + public string UrlBase { get; init; } = "/"; + + /// <summary> + /// Gets the path to static web content. + /// </summary> + [Argument(default, "content-path")] + [EnvironmentVariable("CONTENT_PATH")] + [Description("path to static web content")] + [StringLength(255, MinimumLength = 1)] + [DirectoryExists] + [RequiresRestart] + public string ContentPath { get; init; } = "wwwroot"; + + /// <summary> + /// Gets a value indicating whether HTTP request logging should be enabled. + /// </summary> + [Argument(default, "http-logging")] + [EnvironmentVariable("HTTP_LOGGING")] + [Description("enable http request logging")] + [RequiresRestart] + public bool Logging { get; init; } = false; + + /// <summary> + /// Gets authentication options. + /// </summary> + [Validate] + public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + + /// <summary> + /// Authentication options. + /// </summary> + public class AuthenticationOptions + { + /// <summary> + /// Gets a value indicating whether authentication should be disabled. + /// </summary> + [Argument('X', "no-auth")] + [EnvironmentVariable("NO_AUTH")] + [Description("disable authentication for web requests")] + [RequiresRestart] + public bool Disabled { get; init; } = false; + + /// <summary> + /// Gets the username for the web UI. + /// </summary> + [Argument('u', "username")] + [EnvironmentVariable("USERNAME")] + [Description("username for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; init; } = Program.AppName; + + /// <summary> + /// Gets the password for the web UI. + /// </summary> + [Argument('p', "password")] + [EnvironmentVariable("PASSWORD")] + [Description("password for web UI")] + [StringLength(255, MinimumLength = 1)] + [Secret] + public string Password { get; init; } = Program.AppName; + + /// <summary> + /// Gets JWT options. + /// </summary> + [Validate] + [RequiresRestart] + public JwtOptions Jwt { get; init; } = new JwtOptions(); + + /// <summary> + /// JWT options. + /// </summary> + public class JwtOptions + { + /// <summary> + /// Gets the key with which to sign JWTs. + /// </summary> + [Argument(default, "jwt-key")] + [EnvironmentVariable("JWT_KEY")] + [Description("JWT signing key")] + [StringLength(255, MinimumLength = 16)] + [Secret] + [RequiresRestart] + public string Key { get; init; } = Cryptography.Random.GetBytes(16).ToBase62String(); + + /// <summary> + /// Gets the TTL for JWTs, in milliseconds. + /// </summary> + [Argument(default, "jwt-ttl")] + [EnvironmentVariable("JWT_TTL")] + [Description("TTL for JWTs")] + [Range(3600, int.MaxValue)] + [RequiresRestart] + public int Ttl { get; init; } = 604800000; + } + } + + /// <summary> + /// HTTPS options. + /// </summary> + public class HttpsOptions + { + /// <summary> + /// Gets a value indicating whether HTTPS should be disabled. + /// </summary> + [Argument(default, "no-https")] + [EnvironmentVariable("NO_HTTPS")] + [Description("disable HTTPS")] + [RequiresRestart] + public bool Disabled { get; init; } = false; + + /// <summary> + /// Gets the HTTPS listen port. + /// </summary> + [Argument('L', "https-port")] + [EnvironmentVariable("HTTPS_PORT")] + [Description("HTTPS listen port for web UI")] + [Range(1, 65535)] + [RequiresRestart] + public int Port { get; init; } = 5001; + + /// <summary> + /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. + /// </summary> + [Argument('f', "force-https")] + [EnvironmentVariable("HTTPS_FORCE")] + [Description("redirect HTTP to HTTPS")] + [RequiresRestart] + public bool Force { get; init; } = false; + + /// <summary> + /// Gets certificate options. + /// </summary> + [Validate] + [RequiresRestart] + public CertificateOptions Certificate { get; init; } = new CertificateOptions(); + + /// <summary> + /// Certificate options. + /// </summary> + [X509Certificate] + public class CertificateOptions + { + /// <summary> + /// Gets the path to the the X509 certificate .pfx file. + /// </summary> + [Argument(default, "https-cert-pfx")] + [EnvironmentVariable("HTTPS_CERT_PFX")] + [Description("path to X509 certificate .pfx")] + [FileExists] + [RequiresRestart] + public string Pfx { get; init; } + + /// <summary> + /// Gets the password for the X509 certificate. + /// </summary> + [Argument(default, "https-cert-password")] + [EnvironmentVariable("HTTPS_CERT_PASSWORD")] + [Description("X509 certificate password")] + [RequiresRestart] + [Secret] + public string Password { get; init; } + } + } + } + + /// <summary> + /// Options for external integrations. + /// </summary> + public class IntegrationOptions + { + /// <summary> + /// Gets FTP options. + /// </summary> + [Validate] + public FtpOptions Ftp { get; init; } = new FtpOptions(); + + /// <summary> + /// Gets Pushbullet options. + /// </summary> + [Validate] + public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); + + /// <summary> + /// FTP options. + /// </summary> + public class FtpOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the FTP integration is enabled. + /// </summary> + [Argument(default, "ftp")] + [EnvironmentVariable("FTP")] + [Description("enable FTP integration")] + public bool Enabled { get; init; } + + /// <summary> + /// Gets the FTP address. + /// </summary> + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; init; } + + /// <summary> + /// Gets the FTP port. + /// </summary> + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; init; } = 21; + + /// <summary> + /// Gets the FTP encryption mode. + /// </summary> + [Argument(default, "ftp-encryption-mode")] + [EnvironmentVariable("FTP_ENCRYPTION_MODE")] + [Description("FTP encryption mode; none, implicit, explicit, auto")] + [Enum(typeof(FtpEncryptionMode))] + public string EncryptionMode { get; init; } = FtpEncryptionMode.Auto.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// </summary> + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; init; } = false; + + /// <summary> + /// Gets the FTP username. + /// </summary> + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; init; } + + /// <summary> + /// Gets the FTP password. + /// </summary> + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + [Secret] + public string Password { get; init; } + + /// <summary> + /// Gets the remote path for uploads. + /// </summary> + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; init; } = "/"; + + /// <summary> + /// Gets a value indicating whether existing files should be overwritten. + /// </summary> + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; init; } = true; + + /// <summary> + /// Gets the connection timeout value, in milliseconds. + /// </summary> + [Argument(default, "ftp-connection-timeout")] + [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] + [Description("FTP connection timeout, in milliseconds")] + [Range(0, int.MaxValue)] + public int ConnectionTimeout { get; init; } = 5000; + + /// <summary> + /// Gets the number of times failing uploads will be retried. + /// </summary> + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("number of times failing FTP uploads will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; init; } = 3; + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + + /// <summary> + /// Pushbullet options. + /// </summary> + public class PushbulletOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// </summary> + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; init; } = false; + + /// <summary> + /// Gets the Pushbullet API access token. + /// </summary> + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + [Secret] + public string AccessToken { get; init; } + + /// <summary> + /// Gets the prefix for Pushbullet notification titles. + /// </summary> + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; init; } = "From slskd:"; + + /// <summary> + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// </summary> + [Argument(default, "pushbullet-notify-on-pm")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] + [Description("send Pushbullet notifications when private messages are received")] + public bool NotifyOnPrivateMessage { get; init; } = true; + + /// <summary> + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// </summary> + [Argument(default, "pushbullet-notify-on-room-mention")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] + [Description("send Pushbullet notifications when your username is mentioned in a room")] + public bool NotifyOnRoomMention { get; init; } = true; + + /// <summary> + /// Gets the number of times failing Pushbullet notifications will be retried. + /// </summary> + [Argument(default, "pushbullet-retry-attempts")] + [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] + [Description("number of times failing Pushbullet notifications will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; init; } = 3; + + /// <summary> + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// </summary> + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; init; } = 900000; // 15 minutes + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/QueueStrategy.cs b/src/slskd/Core/QueueStrategy.cs new file mode 100644 index 00000000..50f6cce1 --- /dev/null +++ b/src/slskd/Core/QueueStrategy.cs @@ -0,0 +1,35 @@ +// <copyright file="QueueStrategy.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 +{ + /// <summary> + /// Queue strategies. + /// </summary> + public enum QueueStrategy + { + /// <summary> + /// Uploads are prioritized based on the time they became ready. + /// </summary> + RoundRobin = 0, + + /// <summary> + /// Uploads are prioritized based on the time they were enqueued. + /// </summary> + FirstInFirstOut = 1, + } +} diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs new file mode 100644 index 00000000..b15ce7fa --- /dev/null +++ b/src/slskd/Core/State.cs @@ -0,0 +1,134 @@ +// <copyright file="State.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 +{ + using System; + using System.Collections.Generic; + using System.Net; + using System.Text.Json.Serialization; + using slskd.Shares; + using slskd.Users; + using Soulseek; + + /// <summary> + /// Application service state. + /// </summary> + public record State + { + public VersionState Version { get; init; } = new VersionState(); + public bool PendingReconnect { get; init; } + public bool PendingRestart { get; init; } + public ServerState Server { get; init; } = new ServerState(); + public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); + public ShareState Shares { get; init; } = new ShareState(); + public string[] Rooms { get; init; } = Array.Empty<string>(); + public User[] Users { get; init; } = Array.Empty<User>(); + } + + public record VersionState + { + public string Full { get; init; } = Program.FullVersion; + public string Current { get; init; } = Program.SemanticVersion; + public string Latest { get; init; } = null; + public bool? IsUpdateAvailable { get; init; } = null; + public bool IsCanary { get; init; } = Program.IsCanary; + public bool IsDevelopment { get; init; } = Program.IsDevelopment; + } + + public record ServerState + { + public string Address { get; init; } + + [JsonConverter(typeof(IPEndPointConverter))] + public IPEndPoint IPEndPoint { get; init; } + public SoulseekClientStates State { get; init; } + public string Username { get; init; } + public UserStatistics Statistics { get; init; } + public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); + public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); + public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); + } + + public record DistributedNetworkState + { + public int BranchLevel { get; init; } + public string BranchRoot { get; init; } + public bool CanAcceptChildren { get; init; } + public int ChildLimit { get; init; } + public IReadOnlyCollection<string> Children { get; init; } = new List<string>().AsReadOnly(); + public bool HasParent { get; init; } + public bool IsBranchRoot { get; init; } + public string Parent { get; init; } + } + + /// <summary> + /// Share state. + /// </summary> + public record ShareState + { + public bool ScanPending { get; init; } + public bool Scanning { get; init; } + public bool Faulted { get; init; } + public double ScanProgress { get; init; } + public int Directories { get; init; } + public int Files { get; init; } + } + + public record SharedFileCacheState + { + /// <summary> + /// Gets a value indicating whether the cache is being filled. + /// </summary> + public bool Filling { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the cache is filled. + /// </summary> + public bool Filled { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the cache is faulted. + /// </summary> + public bool Faulted { get; init; } = false; + + /// <summary> + /// Gets the current fill progress. + /// </summary> + public double FillProgress { get; init; } + + /// <summary> + /// Gets the number of cached directories. + /// </summary> + public int Directories { get; init; } + + /// <summary> + /// Gets the number of cached files. + /// </summary> + public int Files { get; init; } + + /// <summary> + /// Gets the number of directories excluded by filters. + /// </summary> + public int ExcludedDirectories { get; init; } + + /// <summary> + /// Gets the list of shares stored in the cache. + /// </summary> + public IReadOnlyCollection<Share> Shares { get; init; } = new List<Share>().AsReadOnly(); + } +}
\ No newline at end of file |
