From 54e94a56000ef44a2d0d59b0eecb6840829e485a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 18:28:49 -0500 Subject: fetch upload speed from server and provide it in search results --- src/slskd/Application.cs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 3e30c029..fc064df3 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -31,6 +31,7 @@ namespace slskd using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; + using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; @@ -70,6 +71,11 @@ namespace slskd private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + private class CacheKeys + { + public static readonly string AverageUploadSpeed = nameof(CacheKeys.AverageUploadSpeed); + } + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -160,6 +166,7 @@ namespace slskd private IHubContext LogHub { get; set; } private IUserService Users { get; set; } private IShareService Shares { get; set; } + private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); public void CollectGarbage() { @@ -442,6 +449,19 @@ namespace slskd } } + private async Task GetAverageUploadSpeedFromServer() + { + if (Cache.TryGetValue(CacheKeys.AverageUploadSpeed, out int averageUploadSpeed)) + { + return averageUploadSpeed; + } + + var stats = await Client.GetUserStatisticsAsync(OptionsAtStartup.Soulseek.Username); + Cache.Set(CacheKeys.AverageUploadSpeed, stats.AverageSpeed, TimeSpan.FromHours(12)); + + return stats.AverageSpeed; + } + private void Client_LoggedIn(object sender, EventArgs e) { Log.Information("Logged in to the Soulseek server as {Username}", Client.Username); @@ -449,6 +469,9 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero // initially, but we'll update them when the cache is filled. _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); + + // fetch our average upload speed from the server, so we can provide it along with search results + _ = GetAverageUploadSpeedFromServer(); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -836,12 +859,13 @@ namespace slskd if (results.Any()) { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); + var averageUploadSpeed = await GetAverageUploadSpeedFromServer(); return new SearchResponse( Client.Username, token, freeUploadSlots: 1, - uploadSpeed: 0, + uploadSpeed: averageUploadSpeed, queueLength: 0, fileList: results); } -- cgit v1.2.3 From 037c6b2bbb37442fb09eb5163ecfe84f2adb3fa9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 18:43:39 -0500 Subject: disable stupid rule --- src/slskd/Properties/analysis.ruleset | 1 + src/slskd/Transfers/Uploads/UploadQueue.cs | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset index 3e0f3586..4c308cbf 100644 --- a/src/slskd/Properties/analysis.ruleset +++ b/src/slskd/Properties/analysis.ruleset @@ -38,6 +38,7 @@ + diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index de8cc031..e5b8c5f5 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -199,9 +199,7 @@ namespace slskd.Transfers } } -#pragma warning disable S3241 // Methods should not return values that are never used private Upload Process() -#pragma warning restore S3241 // Methods should not return values that are never used { SyncRoot.Wait(); -- cgit v1.2.3 From a8deb4361362ed01c930447dcfa92a9b756d03c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 19:10:27 -0500 Subject: move some things into Core --- src/slskd/Common/CommonExtensions.cs | 370 ++++++++++ src/slskd/Common/Compute.cs | 17 - src/slskd/Common/Extensions.cs | 419 ----------- src/slskd/Common/QueueStrategy.cs | 35 - src/slskd/Core/CacheKeys.cs | 24 + src/slskd/Core/CoreExtensions.cs | 75 ++ src/slskd/Core/Options.cs | 1340 ++++++++++++++++++++++++++++++++++ src/slskd/Core/QueueStrategy.cs | 35 + src/slskd/Core/State.cs | 134 ++++ src/slskd/Options.cs | 1339 --------------------------------- src/slskd/State.cs | 133 ---- 11 files changed, 1978 insertions(+), 1943 deletions(-) create mode 100644 src/slskd/Common/CommonExtensions.cs delete mode 100644 src/slskd/Common/Extensions.cs delete mode 100644 src/slskd/Common/QueueStrategy.cs create mode 100644 src/slskd/Core/CacheKeys.cs create mode 100644 src/slskd/Core/CoreExtensions.cs create mode 100644 src/slskd/Core/Options.cs create mode 100644 src/slskd/Core/QueueStrategy.cs create mode 100644 src/slskd/Core/State.cs delete mode 100644 src/slskd/Options.cs delete mode 100644 src/slskd/State.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs new file mode 100644 index 00000000..65949016 --- /dev/null +++ b/src/slskd/Common/CommonExtensions.cs @@ -0,0 +1,370 @@ +// +// 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/. +// + +namespace slskd +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Numerics; + using System.Reflection; + using System.Text; + using System.Text.Json; + using System.Text.Json.Serialization; + using System.Text.RegularExpressions; + using YamlDotNet.Serialization; + using YamlDotNet.Serialization.NamingConventions; + + /// + /// Common extensions; things not specific to Soulseek or slskd. + /// + public static class CommonExtensions + { + /// + /// Deeply compares this object with the specified object and returns a list of properties that are different. + /// + /// The left side of the comparison. + /// The right side of the comparison. + /// The root path for recursive calls. + /// A list of differences between the two objects. + public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) + { + if (left?.GetType() != right?.GetType()) + { + throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); + } + + var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); + + foreach (var prop in left?.GetType().GetProperties()) + { + var leftVal = prop.GetValue(left); + var rightVal = prop.GetValue(right); + var propType = prop.PropertyType; + var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); + + if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>))) + { + if (leftVal.ToJson() != rightVal.ToJson()) + { + differences.Add((prop, fqn, leftVal, rightVal)); + } + } + else if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType)) + { + if (!Equals(leftVal, rightVal)) + { + differences.Add((prop, fqn, leftVal, rightVal)); + } + } + else + { + differences.AddRange(DiffWith(leftVal, rightVal, fqn)); + } + } + + return differences; + } + + /// + /// Returns the directory from the given path, regardless of separator format. + /// + /// The path. + /// The directory. + public static string DirectoryName(this string path) + { + var separator = path.Contains('\\') ? '\\' : '/'; + var parts = path.Split(separator); + return string.Join(separator, parts.Take(parts.Length - 1)); + } + + /// + /// Recursively retrieves all properties. + /// + /// The type from which to retrieve properties. + /// The list of properties. + public static IEnumerable GetPropertiesRecursively(this Type type) + { + var props = new List(); + + foreach (var prop in type.GetProperties()) + { + if (prop.PropertyType.IsPrimitive || prop.PropertyType.IsArray || Nullable.GetUnderlyingType(prop.PropertyType) != null || new[] { typeof(string), typeof(decimal) }.Contains(prop.PropertyType)) + { + props.Add(prop); + } + else + { + props.AddRange(prop.PropertyType.GetPropertiesRecursively()); + } + } + + return props; + } + + /// + /// Determines whether the string is a valid regular expression. + /// + /// The string to validate. + /// A value indicating whether the string is a valid regular expression. + public static bool IsValidRegex(this string pattern) + { + if (string.IsNullOrWhiteSpace(pattern)) + { + return false; + } + + try + { + Regex.Match(string.Empty, pattern); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + + /// + /// Replaces the first occurance of in the string with . + /// + /// The string on which to perform the replacement. + /// The phrase or substring to replace. + /// The replacement string. + /// The string, with the desired phrase replaced. + public static string ReplaceFirst(this string str, string phrase, string replacement) + { + int pos = str.IndexOf(phrase); + + if (pos < 0) + { + return str; + } + + return str.Substring(0, pos) + replacement + str.Substring(pos + phrase.Length); + } + + /// + /// Formats byte to nearest size (KB, MB, etc.) + /// + /// The value to format. + /// The number of decimal places to include. + /// The formatted string. + public static string SizeSuffix(this double value, int decimalPlaces = 1) + { + string[] sizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; + + if (value < 0) + { + return "-" + SizeSuffix(-value); + } + + if (value == 0) + { + return string.Format("{0:n" + decimalPlaces + "} bytes", 0); + } + + // mag is 0 for bytes, 1 for KB, 2, for MB, etc. + int mag = (int)Math.Log(value, 1024); + + // 1L << (mag * 10) == 2 ^ (10 * mag) [i.e. the number of bytes in the unit corresponding to mag] + decimal adjustedSize = (decimal)value / (1L << (mag * 10)); + + // make adjustment when the value is large enough that it would round up to 1000 or more + if (Math.Round(adjustedSize, decimalPlaces) >= 1000) + { + mag += 1; + adjustedSize /= 1024; + } + + return string.Format( + "{0:n" + decimalPlaces + "} {1}", + adjustedSize, + sizeSuffixes[mag]); + } + + /// + /// Returns a "pretty" string representation of the provided Type; specifically, corrects the naming of generic Types + /// and appends the type parameters for the type to the name as it appears in the code editor. + /// + /// The type for which the colloquial name should be created. + /// A "pretty" string representation of the provided Type. + public static string ToColloquialString(this Type type) + { + return !type.IsGenericType ? type.Name : type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(a => a.ToColloquialString())) + ">"; + } + + /// + /// Serializes this object to json. + /// + /// The object to serialize. + /// A string containing the serialized object. + public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); + + /// + /// Serializes this object to yaml. + /// + /// The object to serialize. + /// A string containing the serialized object. + public static string ToYaml(this object obj) => new SerializerBuilder() + .WithNamingConvention(UnderscoredNamingConvention.Instance) + .Build() + .Serialize(obj); + + /// + /// Deserializes this string from yaml to an object of type . + /// + /// The type to which to deserialize the string. + /// The string to deserialize. + /// The new object deserialzied from the string. + public static T FromYaml(this string str) => new DeserializerBuilder() + .WithNamingConvention(UnderscoredNamingConvention.Instance) + .Build() + .Deserialize(str); + + /// + /// Converts a fully qualified remote filename to a local filename based in the provided + /// , swapping directory characters for those specific to the local OS, removing any + /// characters that are invalid for the local OS, and making the path relative to the remote store (including the + /// filename and the parent folder). + /// + /// The fully qualified remote filename to convert. + /// The base directory for the local filename. + /// The converted filename. + public static string ToLocalFilename(this string remoteFilename, string baseDirectory) + { + return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); + } + + /// + /// Converts the given path to the local format (normalizes path separators). + /// + /// The path to convert. + /// The converted path. + public static string ToLocalOSPath(this string path) + { + return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); + } + + /// + /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific + /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the + /// remote store (including the filename and the parent folder). + /// + /// The fully qualified remote filename to convert. + /// The converted filename. + public static string ToLocalRelativeFilename(this string remoteFilename) + { + if (string.IsNullOrWhiteSpace(remoteFilename)) + { + throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename)); + } + + // normalize path separators + var localizedRemoteFilename = remoteFilename.ToLocalOSPath(); + + var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); + + if (parts.Length == 1) + { + return parts.First().ReplaceInvalidFileNameCharacters(); + } + + var file = parts.Last().ReplaceInvalidFileNameCharacters(); + var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); + + return Path.Combine(directory, file); + } + + /// + /// Replaces any occurance of an invalid filename character with the specified . + /// + /// The path to sanitize. + /// The character with which to replace invalid characters. + /// The sanitized path. + public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_') + { + var sanitized = path; + + foreach (var c in Path.GetInvalidFileNameChars()) + { + sanitized = sanitized.Replace(c, replacement); + } + + return sanitized; + } + + /// + /// Converts the byte array into a base 62 encoded string. + /// + /// The bytes to convert. + /// The converted bytes as a base 62 string. + public static string ToBase62String(this byte[] bytes) + { + const string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + BigInteger dividend = new BigInteger(bytes); + var builder = new StringBuilder(); + + while (dividend != 0) + { + dividend = BigInteger.DivRem(dividend, alphabet.Length, out BigInteger remainder); + builder.Insert(0, alphabet[Math.Abs((int)remainder)]); + } + + return builder.ToString(); + } + + /// + /// Determines whether the given object is a . + /// + /// The object to check. + /// A value indicating whether the given object is a dictionary. + public static bool IsDictionary(this object obj) + { + if (obj == null) + { + return false; + } + + return obj is IDictionary && + obj.GetType().IsGenericType && + obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); + } + + /// + /// Deserializes this string from json to an object of type . + /// + /// The type to which to deserialize the string. + /// The string to deserialize. + /// The new object deserialzied from the string. + public static T FromJson(this string str) => JsonSerializer.Deserialize(str, GetJsonSerializerOptions()); + + private static JsonSerializerOptions GetJsonSerializerOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new IPAddressConverter()); + options.Converters.Add(new JsonStringEnumConverter()); + options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + return options; + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index eacaedf1..b9dc882a 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -44,22 +44,5 @@ namespace slskd using var sha1 = SHA1.Create(); return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } - - public static string MaskHash(string str) - { - var hash = Sha1Hash(str); - hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(hash)); - hash = Regex.Replace(hash, @"[\d=]", string.Empty).ToLowerInvariant(); - - // in some very unlucky circumstances, the sha1 might end up being all or mostly numbers. - // if this is the case the resulting hash could be fewer than the 5 characters we need, - // so copy it until we get to 5 - while (hash.Length < 5) - { - hash += hash; - } - - return $"@@{hash.Substring(0, 5)}"; - } } } \ No newline at end of file diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs deleted file mode 100644 index eafc59ff..00000000 --- a/src/slskd/Common/Extensions.cs +++ /dev/null @@ -1,419 +0,0 @@ -// -// 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/. -// - -namespace slskd -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Sockets; - using System.Numerics; - using System.Reflection; - using System.Security.Cryptography; - using System.Text; - using System.Text.Json; - using System.Text.Json.Serialization; - using System.Text.RegularExpressions; - using Soulseek; - using YamlDotNet.Serialization; - using YamlDotNet.Serialization.NamingConventions; - - /// - /// Extensions. - /// - public static class Extensions - { - /// - /// Deeply compares this object with the specified object and returns a list of properties that are different. - /// - /// The left side of the comparison. - /// The right side of the comparison. - /// The root path for recursive calls. - /// A list of differences between the two objects. - public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) - { - if (left?.GetType() != right?.GetType()) - { - throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); - } - - var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); - - foreach (var prop in left?.GetType().GetProperties()) - { - var leftVal = prop.GetValue(left); - var rightVal = prop.GetValue(right); - var propType = prop.PropertyType; - var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); - - if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>))) - { - if (leftVal.ToJson() != rightVal.ToJson()) - { - differences.Add((prop, fqn, leftVal, rightVal)); - } - } - else if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType)) - { - if (!Equals(leftVal, rightVal)) - { - differences.Add((prop, fqn, leftVal, rightVal)); - } - } - else - { - differences.AddRange(DiffWith(leftVal, rightVal, fqn)); - } - } - - return differences; - } - - /// - /// Returns the directory from the given path, regardless of separator format. - /// - /// The path. - /// The directory. - public static string DirectoryName(this string path) - { - var separator = path.Contains('\\') ? '\\' : '/'; - var parts = path.Split(separator); - return string.Join(separator, parts.Take(parts.Length - 1)); - } - - /// - /// Recursively retrieves all properties. - /// - /// The type from which to retrieve properties. - /// The list of properties. - public static IEnumerable GetPropertiesRecursively(this Type type) - { - var props = new List(); - - foreach (var prop in type.GetProperties()) - { - if (prop.PropertyType.IsPrimitive || prop.PropertyType.IsArray || Nullable.GetUnderlyingType(prop.PropertyType) != null || new[] { typeof(string), typeof(decimal) }.Contains(prop.PropertyType)) - { - props.Add(prop); - } - else - { - props.AddRange(prop.PropertyType.GetPropertiesRecursively()); - } - } - - return props; - } - - /// - /// Determines whether the string is a valid regular expression. - /// - /// The string to validate. - /// A value indicating whether the string is a valid regular expression. - public static bool IsValidRegex(this string pattern) - { - if (string.IsNullOrWhiteSpace(pattern)) - { - return false; - } - - try - { - Regex.Match(string.Empty, pattern); - } - catch (ArgumentException) - { - return false; - } - - return true; - } - - /// - /// Replaces the first occurance of in the string with . - /// - /// The string on which to perform the replacement. - /// The phrase or substring to replace. - /// The replacement string. - /// The string, with the desired phrase replaced. - public static string ReplaceFirst(this string str, string phrase, string replacement) - { - int pos = str.IndexOf(phrase); - - if (pos < 0) - { - return str; - } - - return str.Substring(0, pos) + replacement + str.Substring(pos + phrase.Length); - } - - /// - /// Formats byte to nearest size (KB, MB, etc.) - /// - /// The value to format. - /// The number of decimal places to include. - /// The formatted string. - public static string SizeSuffix(this double value, int decimalPlaces = 1) - { - string[] sizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; - - if (value < 0) - { - return "-" + SizeSuffix(-value); - } - - if (value == 0) - { - return string.Format("{0:n" + decimalPlaces + "} bytes", 0); - } - - // mag is 0 for bytes, 1 for KB, 2, for MB, etc. - int mag = (int)Math.Log(value, 1024); - - // 1L << (mag * 10) == 2 ^ (10 * mag) [i.e. the number of bytes in the unit corresponding to mag] - decimal adjustedSize = (decimal)value / (1L << (mag * 10)); - - // make adjustment when the value is large enough that it would round up to 1000 or more - if (Math.Round(adjustedSize, decimalPlaces) >= 1000) - { - mag += 1; - adjustedSize /= 1024; - } - - return string.Format( - "{0:n" + decimalPlaces + "} {1}", - adjustedSize, - sizeSuffixes[mag]); - } - - /// - /// Returns a "pretty" string representation of the provided Type; specifically, corrects the naming of generic Types - /// and appends the type parameters for the type to the name as it appears in the code editor. - /// - /// The type for which the colloquial name should be created. - /// A "pretty" string representation of the provided Type. - public static string ToColloquialString(this Type type) - { - return !type.IsGenericType ? type.Name : type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(a => a.ToColloquialString())) + ">"; - } - - /// - /// Serializes this object to json. - /// - /// The object to serialize. - /// A string containing the serialized object. - public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); - - /// - /// Serializes this object to yaml. - /// - /// The object to serialize. - /// A string containing the serialized object. - public static string ToYaml(this object obj) => new SerializerBuilder() - .WithNamingConvention(UnderscoredNamingConvention.Instance) - .Build() - .Serialize(obj); - - /// - /// Deserializes this string from yaml to an object of type . - /// - /// The type to which to deserialize the string. - /// The string to deserialize. - /// The new object deserialzied from the string. - public static T FromYaml(this string str) => new DeserializerBuilder() - .WithNamingConvention(UnderscoredNamingConvention.Instance) - .Build() - .Deserialize(str); - - /// - /// Converts a fully qualified remote filename to a local filename based in the provided - /// , swapping directory characters for those specific to the local OS, removing any - /// characters that are invalid for the local OS, and making the path relative to the remote store (including the - /// filename and the parent folder). - /// - /// The fully qualified remote filename to convert. - /// The base directory for the local filename. - /// The converted filename. - public static string ToLocalFilename(this string remoteFilename, string baseDirectory) - { - return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); - } - - /// - /// Converts the given path to the local format (normalizes path separators). - /// - /// The path to convert. - /// The converted path. - public static string ToLocalOSPath(this string path) - { - return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); - } - - /// - /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific - /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the - /// remote store (including the filename and the parent folder). - /// - /// The fully qualified remote filename to convert. - /// The converted filename. - public static string ToLocalRelativeFilename(this string remoteFilename) - { - if (string.IsNullOrWhiteSpace(remoteFilename)) - { - throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename)); - } - - // normalize path separators - var localizedRemoteFilename = remoteFilename.ToLocalOSPath(); - - var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); - - if (parts.Length == 1) - { - return parts.First().ReplaceInvalidFileNameCharacters(); - } - - var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - - return Path.Combine(directory, file); - } - - /// - /// Replaces any occurance of an invalid filename character with the specified . - /// - /// The path to sanitize. - /// The character with which to replace invalid characters. - /// The sanitized path. - public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidFileNameChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - - /// - /// Converts the byte array into a base 62 encoded string. - /// - /// The bytes to convert. - /// The converted bytes as a base 62 string. - public static string ToBase62String(this byte[] bytes) - { - const string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - BigInteger dividend = new BigInteger(bytes); - var builder = new StringBuilder(); - - while (dividend != 0) - { - dividend = BigInteger.DivRem(dividend, alphabet.Length, out BigInteger remainder); - builder.Insert(0, alphabet[Math.Abs((int)remainder)]); - } - - return builder.ToString(); - } - - /// - /// Determines whether the given object is a . - /// - /// The object to check. - /// A value indicating whether the given object is a dictionary. - public static bool IsDictionary(this object obj) - { - if (obj == null) - { - return false; - } - - return obj is IDictionary && - obj.GetType().IsGenericType && - obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); - } - - /// - /// Redacts this instance of Options, replacing properties marked with with '*****'. - /// - /// - /// Creates a deep clone before redacting. - /// - /// The Options instance to redact. - /// A redacted instance. - public static Options Redact(this Options options) - { - var redacted = options.ToJson().FromJson(); - Redactor.Redact(redacted, redactWith: "*****"); - return redacted; - } - - /// - /// Creates a copy of this instance with the specified parameters changed. - /// - /// The options instance to copy. - /// The read buffer size for underlying TCP connections. - /// The write buffer size for underlying TCP connections. - /// The size of the write queue for double buffered writes. - /// The connection timeout, in milliseconds, for client and peer TCP connections. - /// The inactivity timeout, in milliseconds, for peer TCP connections. - /// Optional SOCKS 5 proxy configuration options. - /// - /// The delegate invoked during instantiation to configure the server Socket instance. - /// - /// The new instance. - 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 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); - - /// - /// Deserializes this string from json to an object of type . - /// - /// The type to which to deserialize the string. - /// The string to deserialize. - /// The new object deserialzied from the string. - public static T FromJson(this string str) => JsonSerializer.Deserialize(str, GetJsonSerializerOptions()); - - private static JsonSerializerOptions GetJsonSerializerOptions() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new IPAddressConverter()); - options.Converters.Add(new JsonStringEnumConverter()); - options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; - options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - return options; - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/QueueStrategy.cs b/src/slskd/Common/QueueStrategy.cs deleted file mode 100644 index 50f6cce1..00000000 --- a/src/slskd/Common/QueueStrategy.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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/. -// - -namespace slskd -{ - /// - /// Queue strategies. - /// - public enum QueueStrategy - { - /// - /// Uploads are prioritized based on the time they became ready. - /// - RoundRobin = 0, - - /// - /// Uploads are prioritized based on the time they were enqueued. - /// - FirstInFirstOut = 1, - } -} 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 (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/. +// + +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 (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/. +// + +namespace slskd +{ + using System; + using System.Net.Sockets; + using Soulseek; + + /// + /// Core extensions; extensions for types specific to Soulseek or slskd. + /// + public static class CoreExtensions + { + /// + /// Redacts this instance of Options, replacing properties marked with with '*****'. + /// + /// + /// Creates a deep clone before redacting. + /// + /// The Options instance to redact. + /// A redacted instance. + public static Options Redact(this Options options) + { + var redacted = options.ToJson().FromJson(); + Redactor.Redact(redacted, redactWith: "*****"); + return redacted; + } + + /// + /// Creates a copy of this instance with the specified parameters changed. + /// + /// The options instance to copy. + /// The read buffer size for underlying TCP connections. + /// The write buffer size for underlying TCP connections. + /// The size of the write queue for double buffered writes. + /// The connection timeout, in milliseconds, for client and peer TCP connections. + /// The inactivity timeout, in milliseconds, for peer TCP connections. + /// Optional SOCKS 5 proxy configuration options. + /// + /// The delegate invoked during instantiation to configure the server Socket instance. + /// + /// The new instance. + 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 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 (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/. +// + +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; + + /// + /// Disambiguates options derived at startup from options that may update at run time. + /// + /// + /// This class is added directly to dependency injection, but is not, so consumers must inject + /// instead of to make it clear that these options will not change. Options that may change should be accessed by injecting + /// or , depending on the lifetime of the component. + /// + public class OptionsAtStartup : Options + { + } + + /// + /// Application options. + /// + /// + /// + /// This class contains all application options, which may be sourced from (in order of precedence): + /// + /// + /// Defaults + /// Default values, statically defined in this class. + /// + /// + /// Environment Variables + /// Environment variables set at either the system or user scope. + /// + /// + /// YAML Configuration File + /// A YAML file containing a mapping of this class. + /// + /// + /// Command Line + /// Options provided via the command line when starting the application. + /// + /// + /// + /// + /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting + /// in components with a singleton lifetime, or for transient or scoped lifetimes. + /// + /// + /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject . + /// + /// + /// 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. + /// + /// + public class Options + { + /// + /// Gets a value indicating whether to display the application version. + /// + [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; + + /// + /// Gets a value indicating whether to display a list of command line arguments. + /// + [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; + + /// + /// Gets a value indicating whether to display a list of configuration environment variables. + /// + [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; + + /// + /// Gets a value indicating whether to generate an X509 certificate and password. + /// + [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; + + /// + /// Gets a value indicating whether the application should run in debug mode. + /// + [Argument('d', "debug")] + [EnvironmentVariable("DEBUG")] + [Description("run in debug mode")] + [RequiresRestart] + public bool Debug { get; init; } = Debugger.IsAttached; + + /// + /// Gets a value indicating whether the logo should be suppressed on startup. + /// + [Argument('n', "no-logo")] + [EnvironmentVariable("NO_LOGO")] + [Description("suppress logo on startup")] + [RequiresRestart] + public bool NoLogo { get; init; } = false; + + /// + /// Gets a value indicating whether the application should quit after initialization. + /// + [Argument('x', "no-start")] + [EnvironmentVariable("NO_START")] + [Description("quit the application after initialization")] + [RequiresRestart] + public bool NoStart { get; init; } = false; + + /// + /// Gets a value indicating whether the application should connect to the Soulseek network on startup. + /// + [Argument(default, "no-connect")] + [EnvironmentVariable("NO_CONNECT")] + [Description("do not connect to the Soulseek network on startup")] + [RequiresRestart] + public bool NoConnect { get; init; } = false; + + /// + /// Gets a value indicating whether the application should scan shared directories on startup. + /// + [Argument(default, "no-share-scan")] + [EnvironmentVariable("NO_SHARE_SCAN")] + [Description("do not scan shares on startup")] + [RequiresRestart] + public bool NoShareScan { get; init; } = false; + + /// + /// Gets a value indicating whether the application should check for a newer version on startup. + /// + [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; + + /// + /// Gets a value indicating whether remote configuration of options is allowed. + /// + [Argument(default, "remote-configuration")] + [EnvironmentVariable("REMOTE_CONFIGURATION")] + [Description("allow remote configuration")] + public bool RemoteConfiguration { get; init; } = false; + + /// + /// Gets the unique name for this instance. + /// + [Argument('i', "instance-name")] + [EnvironmentVariable("INSTANCE_NAME")] + [Description("optional; a unique name for this instance")] + [RequiresRestart] + public string InstanceName { get; init; } = "default"; + + /// + /// Gets the path where application data is saved. + /// + [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; + + /// + /// Gets the path where application data is saved. + /// + [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; + + /// + /// Gets directory options. + /// + [Validate] + [RequiresRestart] + public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); + + /// + /// Gets global options. + /// + [Validate] + public GlobalOptions Global { get; init; } = new GlobalOptions(); + + /// + /// Gets user groups. + /// + [Validate] + public GroupsOptions Groups { get; init; } = new GroupsOptions(); + + /// + /// Gets filter options. + /// + [Validate] + public FiltersOptions Filters { get; init; } = new FiltersOptions(); + + /// + /// Gets a list of rooms to automatically join upon connection. + /// + [Argument(default, "rooms")] + [EnvironmentVariable("ROOMS")] + [Description("a list of rooms to automatically join")] + public string[] Rooms { get; init; } = Array.Empty(); + + /// + /// Gets options for the web UI. + /// + [Validate] + public WebOptions Web { get; init; } = new WebOptions(); + + /// + /// Gets logger options. + /// + [Validate] + [RequiresRestart] + public LoggerOptions Logger { get; init; } = new LoggerOptions(); + + /// + /// Gets feature options. + /// + [Validate] + [RequiresRestart] + public FeatureOptions Feature { get; init; } = new FeatureOptions(); + + /// + /// Gets options for the Soulseek client. + /// + [Validate] + public SoulseekOptions Soulseek { get; init; } = new SoulseekOptions(); + + /// + /// Gets options for external integrations. + /// + [Validate] + public IntegrationOptions Integration { get; init; } = new IntegrationOptions(); + + /// + /// Directory options. + /// + public class DirectoriesOptions : IValidatableObject + { + /// + /// Gets the path where incomplete downloads are saved. + /// + [Argument(default, "incomplete")] + [EnvironmentVariable("INCOMPLETE_DIR")] + [Description("path where incomplete downloads are saved")] + [DirectoryExists(ensureWriteable: true)] + [RequiresRestart] + public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; + + /// + /// Gets the path where downloaded files are saved. + /// + [Argument('o', "downloads")] + [EnvironmentVariable("DOWNLOADS_DIR")] + [Description("path where downloaded files are saved")] + [DirectoryExists(ensureWriteable: true)] + [RequiresRestart] + public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; + + /// + /// Gets the list of paths to shared files. + /// + [Argument('s', "shared")] + [EnvironmentVariable("SHARED_DIR")] + [Description("path to shared files")] + public string[] Shared { get; init; } = Array.Empty(); + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + + /// + /// Global options. + /// + public class GlobalOptions + { + /// + /// Gets global upload options. + /// + [Validate] + public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); + + /// + /// Gets global download options. + /// + [Validate] + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); + + /// + /// Global upload options. + /// + public class GlobalUploadOptions + { + /// + /// Gets the limit for the total number of upload slots. + /// + [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; + + /// + /// Gets the total upload speed limit. + /// + [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; + } + + /// + /// Gets global download options. + /// + public class GlobalDownloadOptions + { + /// + /// Gets the limit for the total number of download slots. + /// + [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; + + /// + /// Gets the total download speed limit. + /// + [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; + } + } + + /// + /// User groups. + /// + public class GroupsOptions : IValidatableObject + { + /// + /// Gets options for the default user group. + /// + /// + /// 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. + /// + [Validate] + public BuiltInOptions Default { get; init; } = new BuiltInOptions(); + + /// + /// Gets options for the leecher user group. + /// + /// + /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. + /// + [Validate] + public LeecherOptions Leechers { get; init; } = new LeecherOptions(); + + /// + /// Gets user defined groups and options. + /// + [Validate] + public Dictionary UserDefined { get; init; } = new Dictionary(); + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable 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.")); + } + + /// + /// Built in user group options. + /// + public class BuiltInOptions + { + /// + /// Gets upload options. + /// + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + } + + /// + /// Built in leecher group options. + /// + public class LeecherOptions + { + /// + /// Gets leecher threshold options. + /// + [Validate] + public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); + + /// + /// Gets upload options. + /// + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + } + + /// + /// Leecher threshold options. + /// + public class ThresholdOptions + { + /// + /// Gets the minimum number of shared files required to avoid being classified as a leecher. + /// + [Range(1, int.MaxValue)] + public int Files { get; init; } = 1; + + /// + /// Gets the minimum number of shared directories required to avoid being classified as a leecher. + /// + [Range(1, int.MaxValue)] + public int Directories { get; init; } = 1; + } + + /// + /// User defined user group options. + /// + public class UserDefinedOptions + { + /// + /// Gets upload options. + /// + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + + /// + /// Gets the list of group member usernames. + /// + public string[] Members { get; init; } = Array.Empty(); + } + + /// + /// User group upload options. + /// + public class UploadOptions + { + /// + /// Gets the priority of the group. + /// + [Range(1, int.MaxValue)] + public int Priority { get; init; } = 1; + + /// + /// Gets the queue strategy for the group. + /// + [Enum(typeof(QueueStrategy))] + public string Strategy { get; init; } = QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + + /// + /// Gets the limit for the total number of upload slots for the group. + /// + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// + /// Gets the total upload speed limit for the group. + /// + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + } + + /// + /// Feature options. + /// + public class FeatureOptions + { + /// + /// Gets a value indicating whether prometheus metrics should be collected and published. + /// + [Argument(default, "prometheus")] + [EnvironmentVariable("PROMETHEUS")] + [Description("enable collection and publishing of prometheus metrics")] + [RequiresRestart] + public bool Prometheus { get; init; } = false; + + /// + /// Gets a value indicating whether swagger documentation and UI should be enabled. + /// + [Argument(default, "swagger")] + [EnvironmentVariable("SWAGGER")] + [Description("enable swagger documentation and UI")] + [RequiresRestart] + public bool Swagger { get; init; } = false; + } + + /// + /// Filter options. + /// + public class FiltersOptions : IValidatableObject + { + /// + /// Gets the list of shared file filters. + /// + [Argument(default, "share-filter")] + [EnvironmentVariable("SHARE_FILTER")] + [Description("regular expressions to filter files from shares")] + public string[] Share { get; init; } = Array.Empty(); + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + foreach (var filter in Share) + { + if (!filter.IsValidRegex()) + { + results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); + } + } + + return results; + } + } + + /// + /// Logger options. + /// + public class LoggerOptions + { + /// + /// Gets the URL to a Grafana Loki instance to which to log. + /// + [Argument(default, "loki")] + [EnvironmentVariable("LOKI")] + [Description("optional; url to a Grafana Loki instance to which to log")] + [RequiresRestart] + public string Loki { get; init; } = null; + } + + /// + /// Soulseek client options. + /// + public class SoulseekOptions + { + /// + /// Gets the username for the Soulseek network. + /// + [Argument(default, "slsk-username")] + [EnvironmentVariable("SLSK_USERNAME")] + [Description("username for the Soulseek network")] + [RequiresReconnect] + public string Username { get; init; } = null; + + /// + /// Gets the password for the Soulseek network. + /// + [Argument(default, "slsk-password")] + [EnvironmentVariable("SLSK_PASSWORD")] + [Description("password for the Soulseek network")] + [Secret] + [RequiresReconnect] + public string Password { get; init; } = null; + + /// + /// Gets the description of the Soulseek user. + /// + [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"; + + /// + /// Gets the port on which to listen for incoming connections. + /// + [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; + + /// + /// Gets the minimum diagnostic level. + /// + [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; + + /// + /// Gets options for the distributed network. + /// + [Validate] + public DistributedNetworkOptions DistributedNetwork { get; init; } = new DistributedNetworkOptions(); + + /// + /// Gets connection options. + /// + [Validate] + public ConnectionOptions Connection { get; init; } = new ConnectionOptions(); + + /// + /// Connection options. + /// + public class ConnectionOptions + { + /// + /// Gets connection timeout options. + /// + [Validate] + public TimeoutOptions Timeout { get; init; } = new TimeoutOptions(); + + /// + /// Gets connection buffer options. + /// + [Validate] + public BufferOptions Buffer { get; init; } = new BufferOptions(); + + /// + /// Gets connection proxy options. + /// + [Validate] + public ProxyOptions Proxy { get; init; } = new ProxyOptions(); + + /// + /// Connection buffer options. + /// + public class BufferOptions + { + /// + /// Gets the connection read buffer size, in bytes. + /// + [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; + + /// + /// Gets the connection write buffer size, in bytes. + /// + [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; + + /// + /// Gets the read/write buffer size for transfers, in bytes. + /// + [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; + + /// + /// Gets the size of the queue for double buffered writes. + /// + [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; + } + + /// + /// Connection timeout options. + /// + public class TimeoutOptions + { + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "slsk-connection-timeout")] + [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] + [Description("connection timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Connect { get; init; } = 10000; + + /// + /// Gets the connection inactivity timeout, in milliseconds. + /// + [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; + } + + /// + /// Connection proxy options. + /// + public class ProxyOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the proxy is enabled. + /// + [Argument(default, "slsk-proxy")] + [EnvironmentVariable("SLSK_PROXY_ENABLED")] + [Description("enable connection proxy")] + public bool Enabled { get; init; } = false; + + /// + /// Gets the proxy address. + /// + [Argument(default, "slsk-proxy-address")] + [EnvironmentVariable("SLSK_PROXY_ADDRESS")] + [Description("connection proxy address")] + [StringLength(255, MinimumLength = 1)] + public string Address { get; init; } + + /// + /// Gets the proxy port. + /// + [Argument(default, "slsk-proxy-port")] + [EnvironmentVariable("SLSK_PROXY_PORT")] + [Description("connection proxy port")] + [Range(1, 65535)] + public int? Port { get; init; } + + /// + /// Gets the proxy username, if applicable. + /// + [Argument(default, "slsk-proxy-username")] + [EnvironmentVariable("SLSK_PROXY_USERNAME")] + [Description("connection proxy username")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; init; } + + /// + /// Gets the proxy password, if applicable. + /// + [Argument(default, "slsk-proxy-password")] + [EnvironmentVariable("SLSK_PROXY_PASSWORD")] + [Description("connection proxy password")] + [StringLength(255, MinimumLength = 1)] + [Secret] + public string Password { get; init; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } + + /// + /// Distributed network options. + /// + public class DistributedNetworkOptions + { + /// + /// Gets a value indicating whether the distributed network should be disabled. + /// + [Argument(default, "slsk-no-dnet")] + [EnvironmentVariable("SLSK_NO_DNET")] + [Description("disable the distributed network")] + public bool Disabled { get; init; } = false; + + /// + /// Gets a value indicating whether to accept distributed child connections. + /// + [Argument(default, "slsk-dnet-no-children")] + [EnvironmentVariable("SLSK_DNET_NO_CHILDREN")] + [Description("do not accept distributed children")] + public bool DisableChildren { get; init; } = false; + + /// + /// Gets the distributed child connection limit. + /// + [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; + + /// + /// Gets a value indicating whether distributed network logging should be enabled. + /// + [Argument(default, "slsk-dnet-logging")] + [EnvironmentVariable("SLSK_DNET_LOGGING")] + [Description("enable distributed network logging")] + public bool Logging { get; init; } = false; + } + } + + /// + /// Web server options. + /// + public class WebOptions + { + /// + /// Gets the HTTP listen port. + /// + [Argument('l', "http-port")] + [EnvironmentVariable("HTTP_PORT")] + [Description("HTTP listen port for web UI")] + [Range(1, 65535)] + [RequiresRestart] + public int Port { get; init; } = 5000; + + /// + /// Gets HTTPS options. + /// + [Validate] + [RequiresRestart] + public HttpsOptions Https { get; init; } = new HttpsOptions(); + + /// + /// Gets the base url for web requests. + /// + [Argument(default, "url-base")] + [EnvironmentVariable("URL_BASE")] + [Description("base url for web requests")] + [RequiresRestart] + public string UrlBase { get; init; } = "/"; + + /// + /// Gets the path to static web content. + /// + [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"; + + /// + /// Gets a value indicating whether HTTP request logging should be enabled. + /// + [Argument(default, "http-logging")] + [EnvironmentVariable("HTTP_LOGGING")] + [Description("enable http request logging")] + [RequiresRestart] + public bool Logging { get; init; } = false; + + /// + /// Gets authentication options. + /// + [Validate] + public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + + /// + /// Authentication options. + /// + public class AuthenticationOptions + { + /// + /// Gets a value indicating whether authentication should be disabled. + /// + [Argument('X', "no-auth")] + [EnvironmentVariable("NO_AUTH")] + [Description("disable authentication for web requests")] + [RequiresRestart] + public bool Disabled { get; init; } = false; + + /// + /// Gets the username for the web UI. + /// + [Argument('u', "username")] + [EnvironmentVariable("USERNAME")] + [Description("username for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; init; } = Program.AppName; + + /// + /// Gets the password for the web UI. + /// + [Argument('p', "password")] + [EnvironmentVariable("PASSWORD")] + [Description("password for web UI")] + [StringLength(255, MinimumLength = 1)] + [Secret] + public string Password { get; init; } = Program.AppName; + + /// + /// Gets JWT options. + /// + [Validate] + [RequiresRestart] + public JwtOptions Jwt { get; init; } = new JwtOptions(); + + /// + /// JWT options. + /// + public class JwtOptions + { + /// + /// Gets the key with which to sign JWTs. + /// + [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(); + + /// + /// Gets the TTL for JWTs, in milliseconds. + /// + [Argument(default, "jwt-ttl")] + [EnvironmentVariable("JWT_TTL")] + [Description("TTL for JWTs")] + [Range(3600, int.MaxValue)] + [RequiresRestart] + public int Ttl { get; init; } = 604800000; + } + } + + /// + /// HTTPS options. + /// + public class HttpsOptions + { + /// + /// Gets a value indicating whether HTTPS should be disabled. + /// + [Argument(default, "no-https")] + [EnvironmentVariable("NO_HTTPS")] + [Description("disable HTTPS")] + [RequiresRestart] + public bool Disabled { get; init; } = false; + + /// + /// Gets the HTTPS listen port. + /// + [Argument('L', "https-port")] + [EnvironmentVariable("HTTPS_PORT")] + [Description("HTTPS listen port for web UI")] + [Range(1, 65535)] + [RequiresRestart] + public int Port { get; init; } = 5001; + + /// + /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. + /// + [Argument('f', "force-https")] + [EnvironmentVariable("HTTPS_FORCE")] + [Description("redirect HTTP to HTTPS")] + [RequiresRestart] + public bool Force { get; init; } = false; + + /// + /// Gets certificate options. + /// + [Validate] + [RequiresRestart] + public CertificateOptions Certificate { get; init; } = new CertificateOptions(); + + /// + /// Certificate options. + /// + [X509Certificate] + public class CertificateOptions + { + /// + /// Gets the path to the the X509 certificate .pfx file. + /// + [Argument(default, "https-cert-pfx")] + [EnvironmentVariable("HTTPS_CERT_PFX")] + [Description("path to X509 certificate .pfx")] + [FileExists] + [RequiresRestart] + public string Pfx { get; init; } + + /// + /// Gets the password for the X509 certificate. + /// + [Argument(default, "https-cert-password")] + [EnvironmentVariable("HTTPS_CERT_PASSWORD")] + [Description("X509 certificate password")] + [RequiresRestart] + [Secret] + public string Password { get; init; } + } + } + } + + /// + /// Options for external integrations. + /// + public class IntegrationOptions + { + /// + /// Gets FTP options. + /// + [Validate] + public FtpOptions Ftp { get; init; } = new FtpOptions(); + + /// + /// Gets Pushbullet options. + /// + [Validate] + public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); + + /// + /// FTP options. + /// + public class FtpOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the FTP integration is enabled. + /// + [Argument(default, "ftp")] + [EnvironmentVariable("FTP")] + [Description("enable FTP integration")] + public bool Enabled { get; init; } + + /// + /// Gets the FTP address. + /// + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; init; } + + /// + /// Gets the FTP port. + /// + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; init; } = 21; + + /// + /// Gets the FTP encryption mode. + /// + [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(); + + /// + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; init; } = false; + + /// + /// Gets the FTP username. + /// + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; init; } + + /// + /// Gets the FTP password. + /// + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + [Secret] + public string Password { get; init; } + + /// + /// Gets the remote path for uploads. + /// + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; init; } = "/"; + + /// + /// Gets a value indicating whether existing files should be overwritten. + /// + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; init; } = true; + + /// + /// Gets the connection timeout value, in milliseconds. + /// + [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; + + /// + /// Gets the number of times failing uploads will be retried. + /// + [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; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + + /// + /// Pushbullet options. + /// + public class PushbulletOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; init; } = false; + + /// + /// Gets the Pushbullet API access token. + /// + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + [Secret] + public string AccessToken { get; init; } + + /// + /// Gets the prefix for Pushbullet notification titles. + /// + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; init; } = "From slskd:"; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// + [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; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// + [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; + + /// + /// Gets the number of times failing Pushbullet notifications will be retried. + /// + [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; + + /// + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; init; } = 900000; // 15 minutes + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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 (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/. +// + +namespace slskd +{ + /// + /// Queue strategies. + /// + public enum QueueStrategy + { + /// + /// Uploads are prioritized based on the time they became ready. + /// + RoundRobin = 0, + + /// + /// Uploads are prioritized based on the time they were enqueued. + /// + 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 (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/. +// + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.Net; + using System.Text.Json.Serialization; + using slskd.Shares; + using slskd.Users; + using Soulseek; + + /// + /// Application service state. + /// + 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(); + public User[] Users { get; init; } = Array.Empty(); + } + + 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 Children { get; init; } = new List().AsReadOnly(); + public bool HasParent { get; init; } + public bool IsBranchRoot { get; init; } + public string Parent { get; init; } + } + + /// + /// Share state. + /// + 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 + { + /// + /// Gets a value indicating whether the cache is being filled. + /// + public bool Filling { get; init; } = false; + + /// + /// Gets a value indicating whether the cache is filled. + /// + public bool Filled { get; init; } = false; + + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; + + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } + + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } + + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } + + /// + /// Gets the number of directories excluded by filters. + /// + public int ExcludedDirectories { get; init; } + + /// + /// Gets the list of shares stored in the cache. + /// + public IReadOnlyCollection Shares { get; init; } = new List().AsReadOnly(); + } +} \ No newline at end of file diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs deleted file mode 100644 index c4de3554..00000000 --- a/src/slskd/Options.cs +++ /dev/null @@ -1,1339 +0,0 @@ -// -// 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/. -// - -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.Validation; - using Soulseek.Diagnostics; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - using YamlDotNet.Serialization; - - /// - /// Disambiguates options derived at startup from options that may update at run time. - /// - /// - /// This class is added directly to dependency injection, but is not, so consumers must inject - /// instead of to make it clear that these options will not change. Options that may change should be accessed by injecting - /// or , depending on the lifetime of the component. - /// - public class OptionsAtStartup : Options - { - } - - /// - /// Application options. - /// - /// - /// - /// This class contains all application options, which may be sourced from (in order of precedence): - /// - /// - /// Defaults - /// Default values, statically defined in this class. - /// - /// - /// Environment Variables - /// Environment variables set at either the system or user scope. - /// - /// - /// YAML Configuration File - /// A YAML file containing a mapping of this class. - /// - /// - /// Command Line - /// Options provided via the command line when starting the application. - /// - /// - /// - /// - /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting - /// in components with a singleton lifetime, or for transient or scoped lifetimes. - /// - /// - /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject . - /// - /// - /// 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. - /// - /// - public class Options - { - /// - /// Gets a value indicating whether to display the application version. - /// - [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; - - /// - /// Gets a value indicating whether to display a list of command line arguments. - /// - [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; - - /// - /// Gets a value indicating whether to display a list of configuration environment variables. - /// - [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; - - /// - /// Gets a value indicating whether to generate an X509 certificate and password. - /// - [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; - - /// - /// Gets a value indicating whether the application should run in debug mode. - /// - [Argument('d', "debug")] - [EnvironmentVariable("DEBUG")] - [Description("run in debug mode")] - [RequiresRestart] - public bool Debug { get; init; } = Debugger.IsAttached; - - /// - /// Gets a value indicating whether the logo should be suppressed on startup. - /// - [Argument('n', "no-logo")] - [EnvironmentVariable("NO_LOGO")] - [Description("suppress logo on startup")] - [RequiresRestart] - public bool NoLogo { get; init; } = false; - - /// - /// Gets a value indicating whether the application should quit after initialization. - /// - [Argument('x', "no-start")] - [EnvironmentVariable("NO_START")] - [Description("quit the application after initialization")] - [RequiresRestart] - public bool NoStart { get; init; } = false; - - /// - /// Gets a value indicating whether the application should connect to the Soulseek network on startup. - /// - [Argument(default, "no-connect")] - [EnvironmentVariable("NO_CONNECT")] - [Description("do not connect to the Soulseek network on startup")] - [RequiresRestart] - public bool NoConnect { get; init; } = false; - - /// - /// Gets a value indicating whether the application should scan shared directories on startup. - /// - [Argument(default, "no-share-scan")] - [EnvironmentVariable("NO_SHARE_SCAN")] - [Description("do not scan shares on startup")] - [RequiresRestart] - public bool NoShareScan { get; init; } = false; - - /// - /// Gets a value indicating whether the application should check for a newer version on startup. - /// - [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; - - /// - /// Gets a value indicating whether remote configuration of options is allowed. - /// - [Argument(default, "remote-configuration")] - [EnvironmentVariable("REMOTE_CONFIGURATION")] - [Description("allow remote configuration")] - public bool RemoteConfiguration { get; init; } = false; - - /// - /// Gets the unique name for this instance. - /// - [Argument('i', "instance-name")] - [EnvironmentVariable("INSTANCE_NAME")] - [Description("optional; a unique name for this instance")] - [RequiresRestart] - public string InstanceName { get; init; } = "default"; - - /// - /// Gets the path where application data is saved. - /// - [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; - - /// - /// Gets the path where application data is saved. - /// - [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; - - /// - /// Gets directory options. - /// - [Validate] - [RequiresRestart] - public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); - - /// - /// Gets global options. - /// - [Validate] - public GlobalOptions Global { get; init; } = new GlobalOptions(); - - /// - /// Gets user groups. - /// - [Validate] - public GroupsOptions Groups { get; init; } = new GroupsOptions(); - - /// - /// Gets filter options. - /// - [Validate] - public FiltersOptions Filters { get; init; } = new FiltersOptions(); - - /// - /// Gets a list of rooms to automatically join upon connection. - /// - [Argument(default, "rooms")] - [EnvironmentVariable("ROOMS")] - [Description("a list of rooms to automatically join")] - public string[] Rooms { get; init; } = Array.Empty(); - - /// - /// Gets options for the web UI. - /// - [Validate] - public WebOptions Web { get; init; } = new WebOptions(); - - /// - /// Gets logger options. - /// - [Validate] - [RequiresRestart] - public LoggerOptions Logger { get; init; } = new LoggerOptions(); - - /// - /// Gets feature options. - /// - [Validate] - [RequiresRestart] - public FeatureOptions Feature { get; init; } = new FeatureOptions(); - - /// - /// Gets options for the Soulseek client. - /// - [Validate] - public SoulseekOptions Soulseek { get; init; } = new SoulseekOptions(); - - /// - /// Gets options for external integrations. - /// - [Validate] - public IntegrationOptions Integration { get; init; } = new IntegrationOptions(); - - /// - /// Directory options. - /// - public class DirectoriesOptions : IValidatableObject - { - /// - /// Gets the path where incomplete downloads are saved. - /// - [Argument(default, "incomplete")] - [EnvironmentVariable("INCOMPLETE_DIR")] - [Description("path where incomplete downloads are saved")] - [DirectoryExists(ensureWriteable: true)] - [RequiresRestart] - public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; - - /// - /// Gets the path where downloaded files are saved. - /// - [Argument('o', "downloads")] - [EnvironmentVariable("DOWNLOADS_DIR")] - [Description("path where downloaded files are saved")] - [DirectoryExists(ensureWriteable: true)] - [RequiresRestart] - public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; - - /// - /// Gets the list of paths to shared files. - /// - [Argument('s', "shared")] - [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - public string[] Shared { get; init; } = Array.Empty(); - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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; - } - } - - /// - /// Global options. - /// - public class GlobalOptions - { - /// - /// Gets global upload options. - /// - [Validate] - public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); - - /// - /// Gets global download options. - /// - [Validate] - public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); - - /// - /// Global upload options. - /// - public class GlobalUploadOptions - { - /// - /// Gets the limit for the total number of upload slots. - /// - [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; - - /// - /// Gets the total upload speed limit. - /// - [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; - } - - /// - /// Gets global download options. - /// - public class GlobalDownloadOptions - { - /// - /// Gets the limit for the total number of download slots. - /// - [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; - - /// - /// Gets the total download speed limit. - /// - [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; - } - } - - /// - /// User groups. - /// - public class GroupsOptions : IValidatableObject - { - /// - /// Gets options for the default user group. - /// - /// - /// 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. - /// - [Validate] - public BuiltInOptions Default { get; init; } = new BuiltInOptions(); - - /// - /// Gets options for the leecher user group. - /// - /// - /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. - /// - [Validate] - public LeecherOptions Leechers { get; init; } = new LeecherOptions(); - - /// - /// Gets user defined groups and options. - /// - [Validate] - public Dictionary UserDefined { get; init; } = new Dictionary(); - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable 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.")); - } - - /// - /// Built in user group options. - /// - public class BuiltInOptions - { - /// - /// Gets upload options. - /// - [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); - } - - /// - /// Built in leecher group options. - /// - public class LeecherOptions - { - /// - /// Gets leecher threshold options. - /// - [Validate] - public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); - - /// - /// Gets upload options. - /// - [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); - } - - /// - /// Leecher threshold options. - /// - public class ThresholdOptions - { - /// - /// Gets the minimum number of shared files required to avoid being classified as a leecher. - /// - [Range(1, int.MaxValue)] - public int Files { get; init; } = 1; - - /// - /// Gets the minimum number of shared directories required to avoid being classified as a leecher. - /// - [Range(1, int.MaxValue)] - public int Directories { get; init; } = 1; - } - - /// - /// User defined user group options. - /// - public class UserDefinedOptions - { - /// - /// Gets upload options. - /// - [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); - - /// - /// Gets the list of group member usernames. - /// - public string[] Members { get; init; } = Array.Empty(); - } - - /// - /// User group upload options. - /// - public class UploadOptions - { - /// - /// Gets the priority of the group. - /// - [Range(1, int.MaxValue)] - public int Priority { get; init; } = 1; - - /// - /// Gets the queue strategy for the group. - /// - [Enum(typeof(QueueStrategy))] - public string Strategy { get; init; } = QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); - - /// - /// Gets the limit for the total number of upload slots for the group. - /// - [Range(1, int.MaxValue)] - public int Slots { get; init; } = int.MaxValue; - - /// - /// Gets the total upload speed limit for the group. - /// - [Range(1, int.MaxValue)] - public int SpeedLimit { get; init; } = int.MaxValue; - } - } - - /// - /// Feature options. - /// - public class FeatureOptions - { - /// - /// Gets a value indicating whether prometheus metrics should be collected and published. - /// - [Argument(default, "prometheus")] - [EnvironmentVariable("PROMETHEUS")] - [Description("enable collection and publishing of prometheus metrics")] - [RequiresRestart] - public bool Prometheus { get; init; } = false; - - /// - /// Gets a value indicating whether swagger documentation and UI should be enabled. - /// - [Argument(default, "swagger")] - [EnvironmentVariable("SWAGGER")] - [Description("enable swagger documentation and UI")] - [RequiresRestart] - public bool Swagger { get; init; } = false; - } - - /// - /// Filter options. - /// - public class FiltersOptions : IValidatableObject - { - /// - /// Gets the list of shared file filters. - /// - [Argument(default, "share-filter")] - [EnvironmentVariable("SHARE_FILTER")] - [Description("regular expressions to filter files from shares")] - public string[] Share { get; init; } = Array.Empty(); - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - foreach (var filter in Share) - { - if (!filter.IsValidRegex()) - { - results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression")); - } - } - - return results; - } - } - - /// - /// Logger options. - /// - public class LoggerOptions - { - /// - /// Gets the URL to a Grafana Loki instance to which to log. - /// - [Argument(default, "loki")] - [EnvironmentVariable("LOKI")] - [Description("optional; url to a Grafana Loki instance to which to log")] - [RequiresRestart] - public string Loki { get; init; } = null; - } - - /// - /// Soulseek client options. - /// - public class SoulseekOptions - { - /// - /// Gets the username for the Soulseek network. - /// - [Argument(default, "slsk-username")] - [EnvironmentVariable("SLSK_USERNAME")] - [Description("username for the Soulseek network")] - [RequiresReconnect] - public string Username { get; init; } = null; - - /// - /// Gets the password for the Soulseek network. - /// - [Argument(default, "slsk-password")] - [EnvironmentVariable("SLSK_PASSWORD")] - [Description("password for the Soulseek network")] - [Secret] - [RequiresReconnect] - public string Password { get; init; } = null; - - /// - /// Gets the description of the Soulseek user. - /// - [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"; - - /// - /// Gets the port on which to listen for incoming connections. - /// - [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; - - /// - /// Gets the minimum diagnostic level. - /// - [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; - - /// - /// Gets options for the distributed network. - /// - [Validate] - public DistributedNetworkOptions DistributedNetwork { get; init; } = new DistributedNetworkOptions(); - - /// - /// Gets connection options. - /// - [Validate] - public ConnectionOptions Connection { get; init; } = new ConnectionOptions(); - - /// - /// Connection options. - /// - public class ConnectionOptions - { - /// - /// Gets connection timeout options. - /// - [Validate] - public TimeoutOptions Timeout { get; init; } = new TimeoutOptions(); - - /// - /// Gets connection buffer options. - /// - [Validate] - public BufferOptions Buffer { get; init; } = new BufferOptions(); - - /// - /// Gets connection proxy options. - /// - [Validate] - public ProxyOptions Proxy { get; init; } = new ProxyOptions(); - - /// - /// Connection buffer options. - /// - public class BufferOptions - { - /// - /// Gets the connection read buffer size, in bytes. - /// - [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; - - /// - /// Gets the connection write buffer size, in bytes. - /// - [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; - - /// - /// Gets the read/write buffer size for transfers, in bytes. - /// - [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; - - /// - /// Gets the size of the queue for double buffered writes. - /// - [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; - } - - /// - /// Connection timeout options. - /// - public class TimeoutOptions - { - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "slsk-connection-timeout")] - [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] - [Description("connection timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Connect { get; init; } = 10000; - - /// - /// Gets the connection inactivity timeout, in milliseconds. - /// - [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; - } - - /// - /// Connection proxy options. - /// - public class ProxyOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the proxy is enabled. - /// - [Argument(default, "slsk-proxy")] - [EnvironmentVariable("SLSK_PROXY_ENABLED")] - [Description("enable connection proxy")] - public bool Enabled { get; init; } = false; - - /// - /// Gets the proxy address. - /// - [Argument(default, "slsk-proxy-address")] - [EnvironmentVariable("SLSK_PROXY_ADDRESS")] - [Description("connection proxy address")] - [StringLength(255, MinimumLength = 1)] - public string Address { get; init; } - - /// - /// Gets the proxy port. - /// - [Argument(default, "slsk-proxy-port")] - [EnvironmentVariable("SLSK_PROXY_PORT")] - [Description("connection proxy port")] - [Range(1, 65535)] - public int? Port { get; init; } - - /// - /// Gets the proxy username, if applicable. - /// - [Argument(default, "slsk-proxy-username")] - [EnvironmentVariable("SLSK_PROXY_USERNAME")] - [Description("connection proxy username")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; init; } - - /// - /// Gets the proxy password, if applicable. - /// - [Argument(default, "slsk-proxy-password")] - [EnvironmentVariable("SLSK_PROXY_PASSWORD")] - [Description("connection proxy password")] - [StringLength(255, MinimumLength = 1)] - [Secret] - public string Password { get; init; } - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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; - } - } - } - - /// - /// Distributed network options. - /// - public class DistributedNetworkOptions - { - /// - /// Gets a value indicating whether the distributed network should be disabled. - /// - [Argument(default, "slsk-no-dnet")] - [EnvironmentVariable("SLSK_NO_DNET")] - [Description("disable the distributed network")] - public bool Disabled { get; init; } = false; - - /// - /// Gets a value indicating whether to accept distributed child connections. - /// - [Argument(default, "slsk-dnet-no-children")] - [EnvironmentVariable("SLSK_DNET_NO_CHILDREN")] - [Description("do not accept distributed children")] - public bool DisableChildren { get; init; } = false; - - /// - /// Gets the distributed child connection limit. - /// - [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; - - /// - /// Gets a value indicating whether distributed network logging should be enabled. - /// - [Argument(default, "slsk-dnet-logging")] - [EnvironmentVariable("SLSK_DNET_LOGGING")] - [Description("enable distributed network logging")] - public bool Logging { get; init; } = false; - } - } - - /// - /// Web server options. - /// - public class WebOptions - { - /// - /// Gets the HTTP listen port. - /// - [Argument('l', "http-port")] - [EnvironmentVariable("HTTP_PORT")] - [Description("HTTP listen port for web UI")] - [Range(1, 65535)] - [RequiresRestart] - public int Port { get; init; } = 5000; - - /// - /// Gets HTTPS options. - /// - [Validate] - [RequiresRestart] - public HttpsOptions Https { get; init; } = new HttpsOptions(); - - /// - /// Gets the base url for web requests. - /// - [Argument(default, "url-base")] - [EnvironmentVariable("URL_BASE")] - [Description("base url for web requests")] - [RequiresRestart] - public string UrlBase { get; init; } = "/"; - - /// - /// Gets the path to static web content. - /// - [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"; - - /// - /// Gets a value indicating whether HTTP request logging should be enabled. - /// - [Argument(default, "http-logging")] - [EnvironmentVariable("HTTP_LOGGING")] - [Description("enable http request logging")] - [RequiresRestart] - public bool Logging { get; init; } = false; - - /// - /// Gets authentication options. - /// - [Validate] - public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); - - /// - /// Authentication options. - /// - public class AuthenticationOptions - { - /// - /// Gets a value indicating whether authentication should be disabled. - /// - [Argument('X', "no-auth")] - [EnvironmentVariable("NO_AUTH")] - [Description("disable authentication for web requests")] - [RequiresRestart] - public bool Disabled { get; init; } = false; - - /// - /// Gets the username for the web UI. - /// - [Argument('u', "username")] - [EnvironmentVariable("USERNAME")] - [Description("username for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; init; } = Program.AppName; - - /// - /// Gets the password for the web UI. - /// - [Argument('p', "password")] - [EnvironmentVariable("PASSWORD")] - [Description("password for web UI")] - [StringLength(255, MinimumLength = 1)] - [Secret] - public string Password { get; init; } = Program.AppName; - - /// - /// Gets JWT options. - /// - [Validate] - [RequiresRestart] - public JwtOptions Jwt { get; init; } = new JwtOptions(); - - /// - /// JWT options. - /// - public class JwtOptions - { - /// - /// Gets the key with which to sign JWTs. - /// - [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(); - - /// - /// Gets the TTL for JWTs, in milliseconds. - /// - [Argument(default, "jwt-ttl")] - [EnvironmentVariable("JWT_TTL")] - [Description("TTL for JWTs")] - [Range(3600, int.MaxValue)] - [RequiresRestart] - public int Ttl { get; init; } = 604800000; - } - } - - /// - /// HTTPS options. - /// - public class HttpsOptions - { - /// - /// Gets a value indicating whether HTTPS should be disabled. - /// - [Argument(default, "no-https")] - [EnvironmentVariable("NO_HTTPS")] - [Description("disable HTTPS")] - [RequiresRestart] - public bool Disabled { get; init; } = false; - - /// - /// Gets the HTTPS listen port. - /// - [Argument('L', "https-port")] - [EnvironmentVariable("HTTPS_PORT")] - [Description("HTTPS listen port for web UI")] - [Range(1, 65535)] - [RequiresRestart] - public int Port { get; init; } = 5001; - - /// - /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. - /// - [Argument('f', "force-https")] - [EnvironmentVariable("HTTPS_FORCE")] - [Description("redirect HTTP to HTTPS")] - [RequiresRestart] - public bool Force { get; init; } = false; - - /// - /// Gets certificate options. - /// - [Validate] - [RequiresRestart] - public CertificateOptions Certificate { get; init; } = new CertificateOptions(); - - /// - /// Certificate options. - /// - [X509Certificate] - public class CertificateOptions - { - /// - /// Gets the path to the the X509 certificate .pfx file. - /// - [Argument(default, "https-cert-pfx")] - [EnvironmentVariable("HTTPS_CERT_PFX")] - [Description("path to X509 certificate .pfx")] - [FileExists] - [RequiresRestart] - public string Pfx { get; init; } - - /// - /// Gets the password for the X509 certificate. - /// - [Argument(default, "https-cert-password")] - [EnvironmentVariable("HTTPS_CERT_PASSWORD")] - [Description("X509 certificate password")] - [RequiresRestart] - [Secret] - public string Password { get; init; } - } - } - } - - /// - /// Options for external integrations. - /// - public class IntegrationOptions - { - /// - /// Gets FTP options. - /// - [Validate] - public FtpOptions Ftp { get; init; } = new FtpOptions(); - - /// - /// Gets Pushbullet options. - /// - [Validate] - public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); - - /// - /// FTP options. - /// - public class FtpOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the FTP integration is enabled. - /// - [Argument(default, "ftp")] - [EnvironmentVariable("FTP")] - [Description("enable FTP integration")] - public bool Enabled { get; init; } - - /// - /// Gets the FTP address. - /// - [Argument(default, "ftp-address")] - [EnvironmentVariable("FTP_ADDRESS")] - [Description("FTP address")] - public string Address { get; init; } - - /// - /// Gets the FTP port. - /// - [Argument(default, "ftp-port")] - [EnvironmentVariable("FTP_PORT")] - [Description("FTP port")] - [Range(1, 65535)] - public int Port { get; init; } = 21; - - /// - /// Gets the FTP encryption mode. - /// - [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(); - - /// - /// Gets a value indicating whether FTP certificate errors should be ignored. - /// - [Argument(default, "ftp-ignore-certificate-errors")] - [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] - [Description("ignore FTP certificate errors")] - public bool IgnoreCertificateErrors { get; init; } = false; - - /// - /// Gets the FTP username. - /// - [Argument(default, "ftp-username")] - [EnvironmentVariable("FTP_USERNAME")] - [Description("FTP username")] - public string Username { get; init; } - - /// - /// Gets the FTP password. - /// - [Argument(default, "ftp-password")] - [EnvironmentVariable("FTP_PASSWORD")] - [Description("FTP password")] - [Secret] - public string Password { get; init; } - - /// - /// Gets the remote path for uploads. - /// - [Argument(default, "ftp-remote-path")] - [EnvironmentVariable("FTP_REMOTE_PATH")] - [Description("remote path for FTP uploads")] - public string RemotePath { get; init; } = "/"; - - /// - /// Gets a value indicating whether existing files should be overwritten. - /// - [Argument(default, "ftp-overwrite-existing")] - [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] - [Description("overwrite existing files when uploading to FTP")] - public bool OverwriteExisting { get; init; } = true; - - /// - /// Gets the connection timeout value, in milliseconds. - /// - [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; - - /// - /// Gets the number of times failing uploads will be retried. - /// - [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; - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(Address)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); - } - - return results; - } - } - - /// - /// Pushbullet options. - /// - public class PushbulletOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the Pushbullet integration is enabled. - /// - [Argument(default, "pushbullet")] - [EnvironmentVariable("PUSHBULLET")] - [Description("enable Pushbullet integration")] - public bool Enabled { get; init; } = false; - - /// - /// Gets the Pushbullet API access token. - /// - [Argument(default, "pushbullet-token")] - [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] - [Description("Pushbullet access token")] - [Secret] - public string AccessToken { get; init; } - - /// - /// Gets the prefix for Pushbullet notification titles. - /// - [Argument(default, "pushbullet-prefix")] - [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] - [Description("prefix for Pushbullet notification titles")] - public string NotificationPrefix { get; init; } = "From slskd:"; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. - /// - [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; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged - /// in user's username is mentioned in a room. - /// - [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; - - /// - /// Gets the number of times failing Pushbullet notifications will be retried. - /// - [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; - - /// - /// Gets the cooldown time for Pushbullet notifications, in milliseconds. - /// - [Argument(default, "pushbullet-cooldown")] - [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] - [Description("cooldown time for Pushbullet notifications, in milliseconds")] - public int CooldownTime { get; init; } = 900000; // 15 minutes - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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/State.cs b/src/slskd/State.cs deleted file mode 100644 index 10ed80f6..00000000 --- a/src/slskd/State.cs +++ /dev/null @@ -1,133 +0,0 @@ -// -// 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/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Text.Json.Serialization; - using slskd.Shares; - using slskd.Users; - using Soulseek; - - /// - /// Application service state. - /// - 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(); - public User[] Users { get; init; } = Array.Empty(); - } - - 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 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 Children { get; init; } = new List().AsReadOnly(); - public bool HasParent { get; init; } - public bool IsBranchRoot { get; init; } - public string Parent { get; init; } - } - - /// - /// Share state. - /// - 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 - { - /// - /// Gets a value indicating whether the cache is being filled. - /// - public bool Filling { get; init; } = false; - - /// - /// Gets a value indicating whether the cache is filled. - /// - public bool Filled { get; init; } = false; - - /// - /// Gets a value indicating whether the cache is faulted. - /// - public bool Faulted { get; init; } = false; - - /// - /// Gets the current fill progress. - /// - public double FillProgress { get; init; } - - /// - /// Gets the number of cached directories. - /// - public int Directories { get; init; } - - /// - /// Gets the number of cached files. - /// - public int Files { get; init; } - - /// - /// Gets the number of directories excluded by filters. - /// - public int ExcludedDirectories { get; init; } - - /// - /// Gets the list of shares stored in the cache. - /// - public IReadOnlyCollection Shares { get; init; } = new List().AsReadOnly(); - } -} \ No newline at end of file -- cgit v1.2.3 From b1388b97f3ce4d7778103c7cae038978c3fa1284 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 19:10:55 -0500 Subject: stash statstics in state, use cache as a flag --- src/slskd/Application.cs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fc064df3..9a9bf1f8 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -71,11 +71,6 @@ namespace slskd private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - private class CacheKeys - { - public static readonly string AverageUploadSpeed = nameof(CacheKeys.AverageUploadSpeed); - } - public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -449,17 +444,22 @@ namespace slskd } } - private async Task GetAverageUploadSpeedFromServer() + private async Task RefreshUserStatisticsIfNeeded(bool force = false) { - if (Cache.TryGetValue(CacheKeys.AverageUploadSpeed, out int averageUploadSpeed)) + if (force || !Cache.TryGetValue(CacheKeys.UserStatisticsToken, out _)) { - return averageUploadSpeed; - } + var stats = await Client.GetUserStatisticsAsync(OptionsAtStartup.Soulseek.Username); - var stats = await Client.GetUserStatisticsAsync(OptionsAtStartup.Soulseek.Username); - Cache.Set(CacheKeys.AverageUploadSpeed, stats.AverageSpeed, TimeSpan.FromHours(12)); + State.SetValue(state => state with + { + Server = state.Server with + { + Statistics = stats, + }, + }); - return stats.AverageSpeed; + Cache.Set(CacheKeys.UserStatisticsToken, true, TimeSpan.FromHours(4)); + } } private void Client_LoggedIn(object sender, EventArgs e) @@ -471,7 +471,7 @@ namespace slskd _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); // fetch our average upload speed from the server, so we can provide it along with search results - _ = GetAverageUploadSpeedFromServer(); + _ = RefreshUserStatisticsIfNeeded(force: true); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -859,13 +859,13 @@ namespace slskd if (results.Any()) { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - var averageUploadSpeed = await GetAverageUploadSpeedFromServer(); + await RefreshUserStatisticsIfNeeded(); return new SearchResponse( Client.Username, token, freeUploadSlots: 1, - uploadSpeed: averageUploadSpeed, + uploadSpeed: State.CurrentValue.Server.Statistics.AverageSpeed, queueLength: 0, fileList: results); } -- cgit v1.2.3 From baa6460ad3b2961b80a707d640c93097c3894d5a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 19:12:25 -0500 Subject: remove blacklist --- src/slskd/Application.cs | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9a9bf1f8..305f5e0e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -841,13 +841,6 @@ namespace slskd /// A Task resolving a SearchResponse, or null. private async Task SearchResponseResolver(string username, int token, SearchQuery query) { - // some bots continually query for very common strings. blacklist known names here. - var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; - if (blacklist.Contains(username)) - { - return null; - } - // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. if (query.Query.Length < 3) { -- cgit v1.2.3 From 093d75736d19c9e353368bc890d7f74cfd7e5bf0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Jun 2022 19:22:55 -0500 Subject: remove unused usings --- src/slskd/Core/Options.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6543d748..9deababa 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -24,13 +24,11 @@ namespace slskd 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; -- cgit v1.2.3 From 851dcdfa4824d6b06287959d89484db16f3a4d91 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Jun 2022 15:37:34 -0500 Subject: move stuff again --- src/slskd/Core/CacheKeys.cs | 24 -------- src/slskd/Core/QueueStrategy.cs | 35 ----------- src/slskd/Core/Types/CacheKeys.cs | 24 ++++++++ src/slskd/Core/Types/QueueStrategy.cs | 35 +++++++++++ src/slskd/Messaging/Domain/PrivateMessage.cs | 71 ---------------------- src/slskd/Messaging/Domain/Room.cs | 75 ----------------------- src/slskd/Messaging/Domain/RoomMessage.cs | 59 ------------------ src/slskd/Messaging/Types/PrivateMessage.cs | 71 ++++++++++++++++++++++ src/slskd/Messaging/Types/Room.cs | 75 +++++++++++++++++++++++ src/slskd/Messaging/Types/RoomMessage.cs | 59 ++++++++++++++++++ src/slskd/Search/Domain/File.cs | 51 ---------------- src/slskd/Search/Domain/Response.cs | 51 ---------------- src/slskd/Search/Domain/Search.cs | 60 ------------------ src/slskd/Search/Types/File.cs | 51 ++++++++++++++++ src/slskd/Search/Types/Response.cs | 51 ++++++++++++++++ src/slskd/Search/Types/Search.cs | 60 ++++++++++++++++++ src/slskd/Shares/Domain/Share.cs | 91 ---------------------------- src/slskd/Shares/Types/Share.cs | 91 ++++++++++++++++++++++++++++ src/slskd/Users/Domain/Info.cs | 29 --------- src/slskd/Users/Domain/Statistics.cs | 42 ------------- src/slskd/Users/Domain/Status.cs | 37 ----------- src/slskd/Users/Domain/User.cs | 42 ------------- src/slskd/Users/Types/Info.cs | 29 +++++++++ src/slskd/Users/Types/Statistics.cs | 42 +++++++++++++ src/slskd/Users/Types/Status.cs | 37 +++++++++++ src/slskd/Users/Types/User.cs | 42 +++++++++++++ 26 files changed, 667 insertions(+), 667 deletions(-) delete mode 100644 src/slskd/Core/CacheKeys.cs delete mode 100644 src/slskd/Core/QueueStrategy.cs create mode 100644 src/slskd/Core/Types/CacheKeys.cs create mode 100644 src/slskd/Core/Types/QueueStrategy.cs delete mode 100644 src/slskd/Messaging/Domain/PrivateMessage.cs delete mode 100644 src/slskd/Messaging/Domain/Room.cs delete mode 100644 src/slskd/Messaging/Domain/RoomMessage.cs create mode 100644 src/slskd/Messaging/Types/PrivateMessage.cs create mode 100644 src/slskd/Messaging/Types/Room.cs create mode 100644 src/slskd/Messaging/Types/RoomMessage.cs delete mode 100644 src/slskd/Search/Domain/File.cs delete mode 100644 src/slskd/Search/Domain/Response.cs delete mode 100644 src/slskd/Search/Domain/Search.cs create mode 100644 src/slskd/Search/Types/File.cs create mode 100644 src/slskd/Search/Types/Response.cs create mode 100644 src/slskd/Search/Types/Search.cs delete mode 100644 src/slskd/Shares/Domain/Share.cs create mode 100644 src/slskd/Shares/Types/Share.cs delete mode 100644 src/slskd/Users/Domain/Info.cs delete mode 100644 src/slskd/Users/Domain/Statistics.cs delete mode 100644 src/slskd/Users/Domain/Status.cs delete mode 100644 src/slskd/Users/Domain/User.cs create mode 100644 src/slskd/Users/Types/Info.cs create mode 100644 src/slskd/Users/Types/Statistics.cs create mode 100644 src/slskd/Users/Types/Status.cs create mode 100644 src/slskd/Users/Types/User.cs (limited to 'src') diff --git a/src/slskd/Core/CacheKeys.cs b/src/slskd/Core/CacheKeys.cs deleted file mode 100644 index b5a335c1..00000000 --- a/src/slskd/Core/CacheKeys.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// 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/. -// - -namespace slskd -{ - public static class CacheKeys - { - public static readonly string UserStatisticsToken = nameof(UserStatisticsToken); - } -} diff --git a/src/slskd/Core/QueueStrategy.cs b/src/slskd/Core/QueueStrategy.cs deleted file mode 100644 index 50f6cce1..00000000 --- a/src/slskd/Core/QueueStrategy.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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/. -// - -namespace slskd -{ - /// - /// Queue strategies. - /// - public enum QueueStrategy - { - /// - /// Uploads are prioritized based on the time they became ready. - /// - RoundRobin = 0, - - /// - /// Uploads are prioritized based on the time they were enqueued. - /// - FirstInFirstOut = 1, - } -} diff --git a/src/slskd/Core/Types/CacheKeys.cs b/src/slskd/Core/Types/CacheKeys.cs new file mode 100644 index 00000000..b5a335c1 --- /dev/null +++ b/src/slskd/Core/Types/CacheKeys.cs @@ -0,0 +1,24 @@ +// +// 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/. +// + +namespace slskd +{ + public static class CacheKeys + { + public static readonly string UserStatisticsToken = nameof(UserStatisticsToken); + } +} diff --git a/src/slskd/Core/Types/QueueStrategy.cs b/src/slskd/Core/Types/QueueStrategy.cs new file mode 100644 index 00000000..50f6cce1 --- /dev/null +++ b/src/slskd/Core/Types/QueueStrategy.cs @@ -0,0 +1,35 @@ +// +// 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/. +// + +namespace slskd +{ + /// + /// Queue strategies. + /// + public enum QueueStrategy + { + /// + /// Uploads are prioritized based on the time they became ready. + /// + RoundRobin = 0, + + /// + /// Uploads are prioritized based on the time they were enqueued. + /// + FirstInFirstOut = 1, + } +} diff --git a/src/slskd/Messaging/Domain/PrivateMessage.cs b/src/slskd/Messaging/Domain/PrivateMessage.cs deleted file mode 100644 index 236632aa..00000000 --- a/src/slskd/Messaging/Domain/PrivateMessage.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// 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/. -// - -namespace slskd.Messaging -{ - using System; - using Soulseek; - - /// - /// A private message. - /// - public class PrivateMessage - { - /// - /// A value indicating whether the message has been acknowledged. - /// - public bool Acknowledged { get; set; } = false; - - /// - /// The unique message id, used to acknowledge receipt. - /// - public int Id { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// A value indicating whether the message was replayed. - /// - public bool Replayed { get; set; } - - /// - /// The UTC timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) - { - return new PrivateMessage() - { - Id = eventArgs.Id, - Timestamp = eventArgs.Timestamp, - Username = eventArgs.Username, - Message = eventArgs.Message, - Acknowledged = false, - Replayed = eventArgs.Replayed, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Messaging/Domain/Room.cs b/src/slskd/Messaging/Domain/Room.cs deleted file mode 100644 index 459dea2c..00000000 --- a/src/slskd/Messaging/Domain/Room.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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/. -// - -namespace slskd.Messaging -{ - using System.Collections.Generic; - using System.Linq; - using Soulseek; - - public class Room - { - /// - /// The room name. - /// - public string Name { get; set; } - - /// - /// A value indicating whether the room is private. - /// - public bool IsPrivate { get; set; } - - /// - /// The number of operators in the room, if private. - /// - public int? OperatorCount { get; set; } - - /// - /// The operators in the room, if private. - /// - public IList Operators { get; set; } - - /// - /// The owner of the room, if private. - /// - public string Owner { get; set; } - - /// - /// The list of users in the room. - /// - public IList Users { get; set; } = new List(); - - /// - /// The list of messages. - /// - public IList Messages { get; set; } = new List(); - - public static Room FromRoomData(RoomData roomData) - { - return new Room() - { - Name = roomData.Name, - IsPrivate = roomData.IsPrivate, - OperatorCount = roomData.OperatorCount, - Operators = roomData.Operators?.ToList(), - Owner = roomData.Owner, - Users = roomData.Users?.ToList(), - Messages = new List(), - }; - } - } -} diff --git a/src/slskd/Messaging/Domain/RoomMessage.cs b/src/slskd/Messaging/Domain/RoomMessage.cs deleted file mode 100644 index 7a06a192..00000000 --- a/src/slskd/Messaging/Domain/RoomMessage.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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/. -// - -namespace slskd.Messaging -{ - using System; - using Soulseek; - - /// - /// A message sent to a room. - /// - public class RoomMessage - { - /// - /// The timestamp of the message. - /// - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - - /// - /// The username of the user who sent the message. - /// - public string Username { get; set; } - - /// - /// The message. - /// - public string Message { get; set; } - - /// - /// The room to which the message pertains. - /// - public string RoomName { get; set; } - - public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) - { - return new RoomMessage() - { - Timestamp = timestamp ?? DateTime.UtcNow, - Username = eventArgs.Username, - Message = eventArgs.Message, - RoomName = eventArgs.RoomName, - }; - } - } -} diff --git a/src/slskd/Messaging/Types/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs new file mode 100644 index 00000000..236632aa --- /dev/null +++ b/src/slskd/Messaging/Types/PrivateMessage.cs @@ -0,0 +1,71 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// + /// A private message. + /// + public class PrivateMessage + { + /// + /// A value indicating whether the message has been acknowledged. + /// + public bool Acknowledged { get; set; } = false; + + /// + /// The unique message id, used to acknowledge receipt. + /// + public int Id { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// A value indicating whether the message was replayed. + /// + public bool Replayed { get; set; } + + /// + /// The UTC timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + public static PrivateMessage FromEventArgs(PrivateMessageReceivedEventArgs eventArgs) + { + return new PrivateMessage() + { + Id = eventArgs.Id, + Timestamp = eventArgs.Timestamp, + Username = eventArgs.Username, + Message = eventArgs.Message, + Acknowledged = false, + Replayed = eventArgs.Replayed, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Messaging/Types/Room.cs b/src/slskd/Messaging/Types/Room.cs new file mode 100644 index 00000000..459dea2c --- /dev/null +++ b/src/slskd/Messaging/Types/Room.cs @@ -0,0 +1,75 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + using System.Collections.Generic; + using System.Linq; + using Soulseek; + + public class Room + { + /// + /// The room name. + /// + public string Name { get; set; } + + /// + /// A value indicating whether the room is private. + /// + public bool IsPrivate { get; set; } + + /// + /// The number of operators in the room, if private. + /// + public int? OperatorCount { get; set; } + + /// + /// The operators in the room, if private. + /// + public IList Operators { get; set; } + + /// + /// The owner of the room, if private. + /// + public string Owner { get; set; } + + /// + /// The list of users in the room. + /// + public IList Users { get; set; } = new List(); + + /// + /// The list of messages. + /// + public IList Messages { get; set; } = new List(); + + public static Room FromRoomData(RoomData roomData) + { + return new Room() + { + Name = roomData.Name, + IsPrivate = roomData.IsPrivate, + OperatorCount = roomData.OperatorCount, + Operators = roomData.Operators?.ToList(), + Owner = roomData.Owner, + Users = roomData.Users?.ToList(), + Messages = new List(), + }; + } + } +} diff --git a/src/slskd/Messaging/Types/RoomMessage.cs b/src/slskd/Messaging/Types/RoomMessage.cs new file mode 100644 index 00000000..7a06a192 --- /dev/null +++ b/src/slskd/Messaging/Types/RoomMessage.cs @@ -0,0 +1,59 @@ +// +// 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/. +// + +namespace slskd.Messaging +{ + using System; + using Soulseek; + + /// + /// A message sent to a room. + /// + public class RoomMessage + { + /// + /// The timestamp of the message. + /// + public DateTime Timestamp { get; set; } = DateTime.UtcNow; + + /// + /// The username of the user who sent the message. + /// + public string Username { get; set; } + + /// + /// The message. + /// + public string Message { get; set; } + + /// + /// The room to which the message pertains. + /// + public string RoomName { get; set; } + + public static RoomMessage FromEventArgs(RoomMessageReceivedEventArgs eventArgs, DateTime? timestamp = null) + { + return new RoomMessage() + { + Timestamp = timestamp ?? DateTime.UtcNow, + Username = eventArgs.Username, + Message = eventArgs.Message, + RoomName = eventArgs.RoomName, + }; + } + } +} diff --git a/src/slskd/Search/Domain/File.cs b/src/slskd/Search/Domain/File.cs deleted file mode 100644 index 0a86eec3..00000000 --- a/src/slskd/Search/Domain/File.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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/. -// - -namespace slskd.Search -{ - using SoulseekFile = Soulseek.File; - - public class File - { - public int? BitDepth { get; init; } - public int? BitRate { get; init; } - public int Code { get; init; } - public string Extension { get; init; } - public string Filename { get; init; } - public bool? IsVariableBitRate { get; init; } - public int? Length { get; init; } - public int? SampleRate { get; init; } - public long Size { get; init; } - public bool IsLocked { get; init; } - - public static File FromSoulseekFile(SoulseekFile file) - { - return new File() - { - BitDepth = file.BitDepth, - BitRate = file.BitRate, - Code = file.Code, - Extension = file.Extension, - Filename = file.Filename, - IsVariableBitRate = file.IsVariableBitRate, - Length = file.Length, - SampleRate = file.SampleRate, - Size = file.Size, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Search/Domain/Response.cs b/src/slskd/Search/Domain/Response.cs deleted file mode 100644 index ea2e8993..00000000 --- a/src/slskd/Search/Domain/Response.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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/. -// - -namespace slskd.Search -{ - using System.Collections.Generic; - using System.Linq; - - public class Response - { - public int FileCount { get; init; } - public ICollection Files { get; init; } = new List(); - public int FreeUploadSlots { get; init; } - public int LockedFileCount { get; init; } - public ICollection LockedFiles { get; init; } = new List(); - public long QueueLength { get; init; } - public int Token { get; init; } - public int UploadSpeed { get; init; } - public string Username { get; init; } - - public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse) - { - return new Response() - { - FileCount = searchResponse.FileCount, - Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), - FreeUploadSlots = searchResponse.FreeUploadSlots, - LockedFileCount = searchResponse.LockedFileCount, - LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), - QueueLength = searchResponse.QueueLength, - Token = searchResponse.Token, - UploadSpeed = searchResponse.UploadSpeed, - Username = searchResponse.Username, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Search/Domain/Search.cs b/src/slskd/Search/Domain/Search.cs deleted file mode 100644 index 52f97075..00000000 --- a/src/slskd/Search/Domain/Search.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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/. -// - -namespace slskd.Search -{ - using System; - using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Text.Json; - using System.Text.Json.Serialization; - using Soulseek; - - public class Search - { - public DateTime? EndedAt { get; set; } - public int FileCount { get; set; } - - [Key] - public Guid Id { get; init; } - - [NotMapped] - public bool IsComplete => State.HasFlag(SearchStates.Completed); - - public int LockedFileCount { get; set; } - public int ResponseCount { get; set; } - - [NotMapped] - public IEnumerable Responses { get; set; } = new List(); - - [JsonIgnore] - public string ResponsesJson - { - get => JsonSerializer.Serialize(Responses); - set - { - Responses = JsonSerializer.Deserialize>(value); - } - } - - public string SearchText { get; init; } - public DateTime StartedAt { get; init; } = DateTime.Now; - public SearchStates State { get; set; } - public int Token { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Search/Types/File.cs b/src/slskd/Search/Types/File.cs new file mode 100644 index 00000000..0a86eec3 --- /dev/null +++ b/src/slskd/Search/Types/File.cs @@ -0,0 +1,51 @@ +// +// 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/. +// + +namespace slskd.Search +{ + using SoulseekFile = Soulseek.File; + + public class File + { + public int? BitDepth { get; init; } + public int? BitRate { get; init; } + public int Code { get; init; } + public string Extension { get; init; } + public string Filename { get; init; } + public bool? IsVariableBitRate { get; init; } + public int? Length { get; init; } + public int? SampleRate { get; init; } + public long Size { get; init; } + public bool IsLocked { get; init; } + + public static File FromSoulseekFile(SoulseekFile file) + { + return new File() + { + BitDepth = file.BitDepth, + BitRate = file.BitRate, + Code = file.Code, + Extension = file.Extension, + Filename = file.Filename, + IsVariableBitRate = file.IsVariableBitRate, + Length = file.Length, + SampleRate = file.SampleRate, + Size = file.Size, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Types/Response.cs b/src/slskd/Search/Types/Response.cs new file mode 100644 index 00000000..ea2e8993 --- /dev/null +++ b/src/slskd/Search/Types/Response.cs @@ -0,0 +1,51 @@ +// +// 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/. +// + +namespace slskd.Search +{ + using System.Collections.Generic; + using System.Linq; + + public class Response + { + public int FileCount { get; init; } + public ICollection Files { get; init; } = new List(); + public int FreeUploadSlots { get; init; } + public int LockedFileCount { get; init; } + public ICollection LockedFiles { get; init; } = new List(); + public long QueueLength { get; init; } + public int Token { get; init; } + public int UploadSpeed { get; init; } + public string Username { get; init; } + + public static Response FromSoulseekSearchResponse(Soulseek.SearchResponse searchResponse) + { + return new Response() + { + FileCount = searchResponse.FileCount, + Files = searchResponse.Files.Select(file => File.FromSoulseekFile(file)).ToList(), + FreeUploadSlots = searchResponse.FreeUploadSlots, + LockedFileCount = searchResponse.LockedFileCount, + LockedFiles = searchResponse.LockedFiles.Select(file => File.FromSoulseekFile(file)).ToList(), + QueueLength = searchResponse.QueueLength, + Token = searchResponse.Token, + UploadSpeed = searchResponse.UploadSpeed, + Username = searchResponse.Username, + }; + } + } +} \ No newline at end of file diff --git a/src/slskd/Search/Types/Search.cs b/src/slskd/Search/Types/Search.cs new file mode 100644 index 00000000..52f97075 --- /dev/null +++ b/src/slskd/Search/Types/Search.cs @@ -0,0 +1,60 @@ +// +// 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/. +// + +namespace slskd.Search +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json; + using System.Text.Json.Serialization; + using Soulseek; + + public class Search + { + public DateTime? EndedAt { get; set; } + public int FileCount { get; set; } + + [Key] + public Guid Id { get; init; } + + [NotMapped] + public bool IsComplete => State.HasFlag(SearchStates.Completed); + + public int LockedFileCount { get; set; } + public int ResponseCount { get; set; } + + [NotMapped] + public IEnumerable Responses { get; set; } = new List(); + + [JsonIgnore] + public string ResponsesJson + { + get => JsonSerializer.Serialize(Responses); + set + { + Responses = JsonSerializer.Deserialize>(value); + } + } + + public string SearchText { get; init; } + public DateTime StartedAt { get; init; } = DateTime.Now; + public SearchStates State { get; set; } + public int Token { get; init; } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs deleted file mode 100644 index 6a6d1f66..00000000 --- a/src/slskd/Shares/Domain/Share.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// 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/. -// - -namespace slskd.Shares -{ - using System.Linq; - using System.Text.Json.Serialization; - using System.Text.RegularExpressions; - - /// - /// A file share. - /// - public sealed class Share - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - /// - /// - /// - [JsonConstructor] - public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath) - { - Id = id; - Alias = alias; - IsExcluded = isExcluded; - LocalPath = localPath; - Raw = raw; - RemotePath = remotePath; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public Share(string share) - { - Raw = share; - IsExcluded = share.StartsWith('-') || share.StartsWith('!'); - - if (IsExcluded) - { - share = share[1..]; - } - - // test to see whether an alias has been specified - var matches = Regex.Matches(share, @"^\[(.*)\](.*)$"); - - if (matches.Any()) - { - // split the alias from the path, and validate the alias - var groups = matches[0].Groups; - Alias = groups[1].Value; - LocalPath = groups[2].Value; - } - else - { - Alias = share.Split(new[] { '/', '\\' }).Last(); - LocalPath = share; - } - - RemotePath = Alias; - - Id = Compute.Sha1Hash(RemotePath); - } - - public string Id { get; init; } - public string Alias { get; init; } - public bool IsExcluded { get; init; } - public string LocalPath { get; init; } - public string Raw { get; init; } - public string RemotePath { get; init; } - } -} diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs new file mode 100644 index 00000000..6a6d1f66 --- /dev/null +++ b/src/slskd/Shares/Types/Share.cs @@ -0,0 +1,91 @@ +// +// 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/. +// + +namespace slskd.Shares +{ + using System.Linq; + using System.Text.Json.Serialization; + using System.Text.RegularExpressions; + + /// + /// A file share. + /// + public sealed class Share + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + /// + /// + [JsonConstructor] + public Share (string id, string alias, bool isExcluded, string localPath, string raw, string remotePath) + { + Id = id; + Alias = alias; + IsExcluded = isExcluded; + LocalPath = localPath; + Raw = raw; + RemotePath = remotePath; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public Share(string share) + { + Raw = share; + IsExcluded = share.StartsWith('-') || share.StartsWith('!'); + + if (IsExcluded) + { + share = share[1..]; + } + + // test to see whether an alias has been specified + var matches = Regex.Matches(share, @"^\[(.*)\](.*)$"); + + if (matches.Any()) + { + // split the alias from the path, and validate the alias + var groups = matches[0].Groups; + Alias = groups[1].Value; + LocalPath = groups[2].Value; + } + else + { + Alias = share.Split(new[] { '/', '\\' }).Last(); + LocalPath = share; + } + + RemotePath = Alias; + + Id = Compute.Sha1Hash(RemotePath); + } + + public string Id { get; init; } + public string Alias { get; init; } + public bool IsExcluded { get; init; } + public string LocalPath { get; init; } + public string Raw { get; init; } + public string RemotePath { get; init; } + } +} diff --git a/src/slskd/Users/Domain/Info.cs b/src/slskd/Users/Domain/Info.cs deleted file mode 100644 index e3969f17..00000000 --- a/src/slskd/Users/Domain/Info.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// 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/. -// - -namespace slskd.Users -{ - public record Info - { - public string Description { get; init; } - public bool HasFreeUploadSlot { get; init; } - public bool HasPicture { get; init; } - public byte[] Picture { get; init; } - public int QueueLength { get; init; } - public int UploadSlots { get; init; } - } -} diff --git a/src/slskd/Users/Domain/Statistics.cs b/src/slskd/Users/Domain/Statistics.cs deleted file mode 100644 index a415d3d5..00000000 --- a/src/slskd/Users/Domain/Statistics.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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/. -// - -namespace slskd.Users -{ - public record Statistics - { - /// - /// Gets the average upload speed of the user. - /// - public int AverageSpeed { get; init; } - - /// - /// Gets the number of directories shared by the user. - /// - public int DirectoryCount { get; init; } - - /// - /// Gets the number of files shared by the user. - /// - public int FileCount { get; init; } - - /// - /// Gets the number of uploads tracked by the server for this user. - /// - public long UploadCount { get; init; } - } -} diff --git a/src/slskd/Users/Domain/Status.cs b/src/slskd/Users/Domain/Status.cs deleted file mode 100644 index 890afb74..00000000 --- a/src/slskd/Users/Domain/Status.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// 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/. -// - -namespace slskd.Users -{ - using Soulseek; - - /// - /// User status. - /// - public record Status - { - /// - /// Gets a value indicating whether the user is privileged. - /// - public bool IsPrivileged { get; init; } - - /// - /// Gets the user's presence. - /// - public UserPresence Presence { get; init; } - } -} diff --git a/src/slskd/Users/Domain/User.cs b/src/slskd/Users/Domain/User.cs deleted file mode 100644 index 2913620c..00000000 --- a/src/slskd/Users/Domain/User.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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/. -// - -namespace slskd.Users -{ - public record User - { - /// - /// Gets the username of the user. - /// - public string Username { get; init; } - - /// - /// Gets the user's configured group. - /// - public string Group { get; init; } - - /// - /// Gets the user's statistics. - /// - public Statistics Statistics { get; init; } - - /// - /// Gets the user's status. - /// - public Status Status { get; init; } - } -} diff --git a/src/slskd/Users/Types/Info.cs b/src/slskd/Users/Types/Info.cs new file mode 100644 index 00000000..e3969f17 --- /dev/null +++ b/src/slskd/Users/Types/Info.cs @@ -0,0 +1,29 @@ +// +// 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/. +// + +namespace slskd.Users +{ + public record Info + { + public string Description { get; init; } + public bool HasFreeUploadSlot { get; init; } + public bool HasPicture { get; init; } + public byte[] Picture { get; init; } + public int QueueLength { get; init; } + public int UploadSlots { get; init; } + } +} diff --git a/src/slskd/Users/Types/Statistics.cs b/src/slskd/Users/Types/Statistics.cs new file mode 100644 index 00000000..a415d3d5 --- /dev/null +++ b/src/slskd/Users/Types/Statistics.cs @@ -0,0 +1,42 @@ +// +// 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/. +// + +namespace slskd.Users +{ + public record Statistics + { + /// + /// Gets the average upload speed of the user. + /// + public int AverageSpeed { get; init; } + + /// + /// Gets the number of directories shared by the user. + /// + public int DirectoryCount { get; init; } + + /// + /// Gets the number of files shared by the user. + /// + public int FileCount { get; init; } + + /// + /// Gets the number of uploads tracked by the server for this user. + /// + public long UploadCount { get; init; } + } +} diff --git a/src/slskd/Users/Types/Status.cs b/src/slskd/Users/Types/Status.cs new file mode 100644 index 00000000..890afb74 --- /dev/null +++ b/src/slskd/Users/Types/Status.cs @@ -0,0 +1,37 @@ +// +// 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/. +// + +namespace slskd.Users +{ + using Soulseek; + + /// + /// User status. + /// + public record Status + { + /// + /// Gets a value indicating whether the user is privileged. + /// + public bool IsPrivileged { get; init; } + + /// + /// Gets the user's presence. + /// + public UserPresence Presence { get; init; } + } +} diff --git a/src/slskd/Users/Types/User.cs b/src/slskd/Users/Types/User.cs new file mode 100644 index 00000000..2913620c --- /dev/null +++ b/src/slskd/Users/Types/User.cs @@ -0,0 +1,42 @@ +// +// 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/. +// + +namespace slskd.Users +{ + public record User + { + /// + /// Gets the username of the user. + /// + public string Username { get; init; } + + /// + /// Gets the user's configured group. + /// + public string Group { get; init; } + + /// + /// Gets the user's statistics. + /// + public Statistics Statistics { get; init; } + + /// + /// Gets the user's status. + /// + public Status Status { get; init; } + } +} -- cgit v1.2.3 From 8d0a803562aa57f5540ed5922cb658b0bdfd6eb2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Jun 2022 19:08:04 -0500 Subject: add IsSlotAvailable and EstimatePosition --- src/slskd/Transfers/Uploads/UploadQueue.cs | 328 ++++++++++++++++++++--------- 1 file changed, 225 insertions(+), 103 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index e5b8c5f5..1e732674 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -35,12 +35,6 @@ namespace slskd.Transfers /// public interface IUploadQueue { - /// - /// Enqueues an upload. - /// - /// The upload to enqueue. - void Enqueue(Transfer transfer); - /// /// Awaits the start of an upload. /// @@ -53,6 +47,35 @@ namespace slskd.Transfers /// /// The completed upload. void Complete(Transfer transfer); + + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. + void Enqueue(Transfer transfer); + + /// + /// Computes the estimated queue position of the specified if they were to enqueue a file. + /// + /// The username for which to estimate. + /// The estimated queue position if the user were to enqueue a file. + int EstimatePosition(string username); + + /// + /// Computes the estimated queue position of the specified for the specified . + /// + /// The username associated with the file. + /// The filename of the file for which the position is to be estimated. + /// The estimated queue position of the file. + /// Thrown if the specified filename is not enqueued. + int EstimatePosition(string username, string filename); + + /// + /// Determines whether an upload slot is available for the specified . + /// + /// The username for which slot availability is to be checked. + /// A value indicating whether an upload slot is available for the specified username. + bool IsSlotAvailable(string username); } /// @@ -77,45 +100,15 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } + private Dictionary Groups { get; set; } = new Dictionary(); + private int LastGlobalSlots { get; set; } + private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private IUserService Users { get; } + private int MaxSlots { get; set; } = 0; private IOptionsMonitor OptionsMonitor { get; } - private string LastOptionsHash { get; set; } - private int LastGlobalSlots { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private int MaxSlots { get; set; } = 0; - private Dictionary Groups { get; set; } = new Dictionary(); private ConcurrentDictionary> Uploads { get; set; } = new ConcurrentDictionary>(); - - /// - /// Enqueues an upload. - /// - /// The upload to enqueue. - public void Enqueue(Transfer transfer) - { - SyncRoot.Wait(); - - try - { - var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; - - Uploads.AddOrUpdate( - key: transfer.Username, - addValue: new List(new[] { upload }), - updateValueFactory: (key, list) => - { - list.Add(upload); - return list; - }); - - Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); - } - finally - { - SyncRoot.Release(); - Process(); - } - } + private IUserService Users { get; } /// /// Awaits the start of an upload. @@ -177,8 +170,8 @@ namespace slskd.Transfers list.Remove(upload); Log.Debug("Complete: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); - // ensure the slot is returned to the group from which it was acquired - // the group may have been removed during the transfer. if so, do nothing. + // ensure the slot is returned to the group from which it was acquired the group may have been removed during the + // transfer. if so, do nothing. if (Groups.ContainsKey(upload.Group ?? string.Empty)) { var group = Groups[upload.Group]; @@ -199,78 +192,135 @@ namespace slskd.Transfers } } - private Upload Process() + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. + public void Enqueue(Transfer transfer) { SyncRoot.Wait(); try { - if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) - { - return null; - } + var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; - // flip the uploads dictionary so that it is keyed by group instead of user. - // wait until just before we process the queue to do this, and fetch each user's - // group as we do, to allow users to move between groups at run time. we delay - // "pinning" an upload to a group (via UsedSlots, below) for the same reason. - var readyUploadsByGroup = Uploads.Aggregate( - seed: new ConcurrentDictionary>(), - func: (groups, user) => + Uploads.AddOrUpdate( + key: transfer.Username, + addValue: new List(new[] { upload }), + updateValueFactory: (key, list) => { - var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue); + list.Add(upload); + return list; + }); - if (ready.Any()) - { - var group = Users.GetGroup(user.Key); + Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + } + finally + { + SyncRoot.Release(); + Process(); + } + } - groups.AddOrUpdate( - key: group, - addValue: new List(ready), - updateValueFactory: (group, list) => - { - list.AddRange(ready); - return list; - }); - } + /// + /// Computes the estimated queue position of the specified if they were to enqueue a file. + /// + /// The username for which to estimate. + /// The estimated queue position if the user were to enqueue a file. + public int EstimatePosition(string username) + { + if (IsSlotAvailable(username)) + { + return 0; + } - return groups; - }); + var group = Users.GetGroup(username); + return Uploads.GetValueOrDefault(group)?.Count ?? 0; + } - // process each group in ascending order of priority, and stop after the first - // ready upload is released. - foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name)) + /// + /// Computes the estimated queue position of the specified for the specified . + /// + /// The username associated with the file. + /// The filename of the file for which the position is to be estimated. + /// The estimated queue position of the file. + /// Thrown if the specified filename is not enqueued. + public int EstimatePosition(string username, string filename) + { + var groupName = Users.GetGroup(username); + var groupRecord = Groups.GetValueOrDefault(groupName); + + // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user + var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + + // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates + // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the + // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files + // are of equal length. + if (groupRecord.Strategy == QueueStrategy.RoundRobin) + { + // find this user's uploads + var uploadsForUser = uploadsForGroup.FirstOrDefault(group => group.Key == username).Value; + + if (uploadsForUser == null || !uploadsForUser.Any()) { - if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) - { - continue; - } + throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + } - var upload = uploads - .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) - .First(); + // find the position of the requested file in the user's queue + var localPosition = uploadsForUser.FindIndex(upload => upload.Username == username && upload.Filename == filename); - // mark the upload as started, and "pin" it to the group from which - // the slot is obtained, so the slot can be returned to the proper place - // upon completion - upload.Started = DateTime.UtcNow; - upload.Group = group.Name; - group.UsedSlots++; + if (localPosition < 0) + { + throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + } - // release the upload - upload.TaskCompletionSource.SetResult(); - Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); - Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + // start the position to the local position within this user's queue; the user's own files must be completed + // before this one can start. + var position = localPosition; - return upload; + // for each other user, add either localPosition or the count of that user's uploads, whichever is less + foreach (var group in uploadsForGroup.Where(group => group.Key != username)) + { + position += Math.Min(localPosition, group.Value.Count); } - return null; + return position; } - finally + + // for FIFO queues, files are uploaded in the order they are enqueued, so the position should be pretty good estimate. + // List ordering is guaranteed, so we are getting an accurate portrayal of where this file is in the queue by order of + // time enqueued. this includes uploads that are in progress. + var flattenedSortedUploadsForGroup = uploadsForGroup + .SelectMany(group => group.Value) + .OrderBy(upload => upload.Enqueued) + .ToList(); + + var globalPosition = flattenedSortedUploadsForGroup.FindIndex(upload => upload.Username == username && upload.Filename == filename); + + if (globalPosition < 0) { - SyncRoot.Release(); + throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); + } + + return globalPosition; + } + + /// + /// Determines whether an upload slot is available for the specified . + /// + /// The username for which slot availability is to be checked. + /// A value indicating whether an upload slot is available for the specified username. + public bool IsSlotAvailable(string username) + { + var group = Users.GetGroup(username); + + if (Groups.TryGetValue(group, out var record)) + { + return record.SlotAvailable; } + + return false; } private void Configure(Options options) @@ -294,11 +344,11 @@ namespace slskd.Transfers // statically add built-in groups var groups = new List() { - // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, - // and a FIFO strategy. all other groups have a minimum priority of 1 (enforced by options validation) - // to ensure that privileged users always take priority, regardless of user configuration. - // the strategy is fixed to FIFO because that gives privileged users the closest experience - // to the official client, as well as the appearance of fairness once the first upload begins. + // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, and a FIFO + // strategy. all other groups have a minimum priority of 1 (enforced by options validation) to ensure that + // privileged users always take priority, regardless of user configuration. the strategy is fixed to FIFO + // because that gives privileged users the closest experience to the official client, as well as the + // appearance of fairness once the first upload begins. new Group() { Name = Application.PrivilegedGroup, @@ -347,24 +397,96 @@ namespace slskd.Transfers } } + private Upload Process() + { + SyncRoot.Wait(); + + try + { + if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) + { + return null; + } + + // flip the uploads dictionary so that it is keyed by group instead of user. wait until just before we process the + // queue to do this, and fetch each user's group as we do, to allow users to move between groups at run time. we + // delay "pinning" an upload to a group (via UsedSlots, below) for the same reason. + var readyUploadsByGroup = Uploads.Aggregate( + seed: new ConcurrentDictionary>(), + func: (groups, user) => + { + var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue); + + if (ready.Any()) + { + var group = Users.GetGroup(user.Key); + + groups.AddOrUpdate( + key: group, + addValue: new List(ready), + updateValueFactory: (group, list) => + { + list.AddRange(ready); + return list; + }); + } + + return groups; + }); + + // process each group in ascending order of priority, and stop after the first ready upload is released. + foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name)) + { + if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) + { + continue; + } + + var upload = uploads + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .First(); + + // mark the upload as started, and "pin" it to the group from which the slot is obtained, so the slot can be + // returned to the proper place upon completion + upload.Started = DateTime.UtcNow; + upload.Group = group.Name; + group.UsedSlots++; + + // release the upload + upload.TaskCompletionSource.SetResult(); + Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + + return upload; + } + + return null; + } + finally + { + SyncRoot.Release(); + } + } + public sealed class Group { public string Name { get; set; } - public int Slots { get; set; } public int Priority { get; set; } + public bool SlotAvailable => UsedSlots < Slots; + public int Slots { get; set; } public QueueStrategy Strategy { get; set; } public int UsedSlots { get; set; } } public sealed class Upload { - public string Username { get; set; } + public DateTime Enqueued { get; set; } = DateTime.UtcNow; public string Filename { get; set; } public string Group { get; set; } - public DateTime Enqueued { get; set; } = DateTime.UtcNow; public DateTime? Ready { get; set; } = null; public DateTime? Started { get; set; } = null; public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); + public string Username { get; set; } } } -} +} \ No newline at end of file -- cgit v1.2.3 From 9225594776afa6635875858ed4dc5c84f64de074 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Jun 2022 19:08:31 -0500 Subject: implement place in queue resolver, send queue stats with search results --- src/slskd/Application.cs | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 305f5e0e..a12e039b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -285,7 +285,8 @@ namespace slskd directoryContentsResolver: DirectoryContentsResponseResolver, enqueueDownload: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), searchResponseCache: new SearchResponseCache(), - searchResponseResolver: SearchResponseResolver); + searchResponseResolver: SearchResponseResolver, + placeInQueueResolver: PlaceInQueueResolver); await Client.ReconfigureOptionsAsync(patch); @@ -573,6 +574,20 @@ namespace slskd Console.WriteLine($"[USER] {args.Username}: {args.Presence}"); } + private Task PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) + { + try + { + var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); + return Task.FromResult((int?)place); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to estimate place in queue for {Filename} requested by {Username}", filename, username); + return Task.FromResult(null); + } + } + /// /// Creates and returns a in response to a remote request. /// @@ -627,7 +642,8 @@ namespace slskd throw new DownloadEnqueueException($"File not shared."); } - if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) + // TODO: fix this; it doesn't work. reproduce by downloading a file, then re-requesting the same file. + if (tracker.TryGet(TransferDirection.Upload, username, localFilename, out _)) { // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); @@ -851,15 +867,19 @@ namespace slskd if (results.Any()) { - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); await RefreshUserStatisticsIfNeeded(); + var hasFreeSlot = Transfers.Uploads.Queue.IsSlotAvailable(username); + var estimatedQueueLength = Transfers.Uploads.Queue.EstimatePosition(username); + + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (free slot?: {hasFreeSlot}, queue length: {estimatedQueueLength})"); + return new SearchResponse( Client.Username, token, - freeUploadSlots: 1, uploadSpeed: State.CurrentValue.Server.Statistics.AverageSpeed, - queueLength: 0, + freeUploadSlots: hasFreeSlot ? 1 : 0, + queueLength: estimatedQueueLength, fileList: results); } -- cgit v1.2.3 From 372d5168b6fbd9df9add8cb4c0dee9434522853f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 07:36:56 -0500 Subject: move types out of UploadQueue --- src/slskd/Transfers/Types/Group.cs | 29 ++++++++++++++++++++++++++ src/slskd/Transfers/Types/Upload.cs | 33 ++++++++++++++++++++++++++++++ src/slskd/Transfers/Uploads/UploadQueue.cs | 21 ------------------- 3 files changed, 62 insertions(+), 21 deletions(-) create mode 100644 src/slskd/Transfers/Types/Group.cs create mode 100644 src/slskd/Transfers/Types/Upload.cs (limited to 'src') diff --git a/src/slskd/Transfers/Types/Group.cs b/src/slskd/Transfers/Types/Group.cs new file mode 100644 index 00000000..c01e4f8a --- /dev/null +++ b/src/slskd/Transfers/Types/Group.cs @@ -0,0 +1,29 @@ +// +// 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/. +// + +namespace slskd.Transfers +{ + public sealed class Group + { + public string Name { get; set; } + public int Priority { get; set; } + public bool SlotAvailable => UsedSlots < Slots; + public int Slots { get; set; } + public QueueStrategy Strategy { get; set; } + public int UsedSlots { get; set; } + } +} diff --git a/src/slskd/Transfers/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs new file mode 100644 index 00000000..bc2b69b1 --- /dev/null +++ b/src/slskd/Transfers/Types/Upload.cs @@ -0,0 +1,33 @@ +// +// 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/. +// + +namespace slskd.Transfers +{ + using System; + using System.Threading.Tasks; + + public sealed class Upload + { + public DateTime Enqueued { get; set; } = DateTime.UtcNow; + public string Filename { get; set; } + public string Group { get; set; } + public DateTime? Ready { get; set; } = null; + public DateTime? Started { get; set; } = null; + public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); + public string Username { get; set; } + } +} diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 1e732674..77eb7758 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -467,26 +467,5 @@ namespace slskd.Transfers SyncRoot.Release(); } } - - public sealed class Group - { - public string Name { get; set; } - public int Priority { get; set; } - public bool SlotAvailable => UsedSlots < Slots; - public int Slots { get; set; } - public QueueStrategy Strategy { get; set; } - public int UsedSlots { get; set; } - } - - public sealed class Upload - { - public DateTime Enqueued { get; set; } = DateTime.UtcNow; - public string Filename { get; set; } - public string Group { get; set; } - public DateTime? Ready { get; set; } = null; - public DateTime? Started { get; set; } = null; - public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); - public string Username { get; set; } - } } } \ No newline at end of file -- cgit v1.2.3 From fec9b55a4ca531f2380efd360cb015ea62071b9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 09:06:39 -0500 Subject: rename Group to UploadGroup --- src/slskd/Transfers/Types/Group.cs | 29 ----------------------------- src/slskd/Transfers/Types/UploadGroup.cs | 29 +++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 29 deletions(-) delete mode 100644 src/slskd/Transfers/Types/Group.cs create mode 100644 src/slskd/Transfers/Types/UploadGroup.cs (limited to 'src') diff --git a/src/slskd/Transfers/Types/Group.cs b/src/slskd/Transfers/Types/Group.cs deleted file mode 100644 index c01e4f8a..00000000 --- a/src/slskd/Transfers/Types/Group.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// 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/. -// - -namespace slskd.Transfers -{ - public sealed class Group - { - public string Name { get; set; } - public int Priority { get; set; } - public bool SlotAvailable => UsedSlots < Slots; - public int Slots { get; set; } - public QueueStrategy Strategy { get; set; } - public int UsedSlots { get; set; } - } -} diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs new file mode 100644 index 00000000..5696b0f1 --- /dev/null +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -0,0 +1,29 @@ +// +// 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/. +// + +namespace slskd.Transfers +{ + public sealed class UploadGroup + { + public string Name { get; set; } + public int Priority { get; set; } + public bool SlotAvailable => UsedSlots < Slots; + public int Slots { get; set; } + public QueueStrategy Strategy { get; set; } + public int UsedSlots { get; set; } + } +} -- cgit v1.2.3 From 08952e1269c9c7e1e5cfae494d3e546219b66f0c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 09:06:58 -0500 Subject: finalize positioning functions --- src/slskd/Transfers/Uploads/UploadQueue.cs | 90 +++++++++++++++--------------- 1 file changed, 46 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 77eb7758..c3b2b3e6 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -54,13 +54,6 @@ namespace slskd.Transfers /// The upload to enqueue. void Enqueue(Transfer transfer); - /// - /// Computes the estimated queue position of the specified if they were to enqueue a file. - /// - /// The username for which to estimate. - /// The estimated queue position if the user were to enqueue a file. - int EstimatePosition(string username); - /// /// Computes the estimated queue position of the specified for the specified . /// @@ -71,11 +64,14 @@ namespace slskd.Transfers int EstimatePosition(string username, string filename); /// - /// Determines whether an upload slot is available for the specified . + /// Computes the estimated queue position of the specified if they were to enqueue a file, + /// or zero if the transfer could start immediately. /// - /// The username for which slot availability is to be checked. - /// A value indicating whether an upload slot is available for the specified username. - bool IsSlotAvailable(string username); + /// The username for which to estimate. + /// + /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. + /// + int ForecastPosition(string username); } /// @@ -100,7 +96,7 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } - private Dictionary Groups { get; set; } = new Dictionary(); + private Dictionary Groups { get; set; } = new Dictionary(); private int LastGlobalSlots { get; set; } private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -222,22 +218,6 @@ namespace slskd.Transfers } } - /// - /// Computes the estimated queue position of the specified if they were to enqueue a file. - /// - /// The username for which to estimate. - /// The estimated queue position if the user were to enqueue a file. - public int EstimatePosition(string username) - { - if (IsSlotAvailable(username)) - { - return 0; - } - - var group = Users.GetGroup(username); - return Uploads.GetValueOrDefault(group)?.Count ?? 0; - } - /// /// Computes the estimated queue position of the specified for the specified . /// @@ -260,15 +240,16 @@ namespace slskd.Transfers if (groupRecord.Strategy == QueueStrategy.RoundRobin) { // find this user's uploads - var uploadsForUser = uploadsForGroup.FirstOrDefault(group => group.Key == username).Value; - - if (uploadsForUser == null || !uploadsForUser.Any()) + if (!Uploads.TryGetValue(username, out var uploadsForUser)) { throw new FileNotFoundException($"File {filename} is not enqueued for user {username}"); } // find the position of the requested file in the user's queue - var localPosition = uploadsForUser.FindIndex(upload => upload.Username == username && upload.Filename == filename); + var localPosition = uploadsForUser + .OrderBy(upload => upload.Enqueued) + .ToList() + .FindIndex(upload => upload.Username == username && upload.Filename == filename); if (localPosition < 0) { @@ -280,6 +261,19 @@ namespace slskd.Transfers var position = localPosition; // for each other user, add either localPosition or the count of that user's uploads, whichever is less + // example: + // + // aaaaa + // bb + // cccccccccccc + // ddddddd + // ^ + // + // if we want the postion of the file over the carat above, first find the position of it + // within its own queue (= 5). assume uploads will process top down, left to right until reaching + // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over + // the carat at position 16. the actual number will vary due to many factors, including where in the + // round-robin ordering d is actually positioned (so +/- number of users downloading). foreach (var group in uploadsForGroup.Where(group => group.Key != username)) { position += Math.Min(localPosition, group.Value.Count); @@ -307,20 +301,28 @@ namespace slskd.Transfers } /// - /// Determines whether an upload slot is available for the specified . + /// Computes the estimated queue position of the specified if they were to enqueue a file, + /// or zero if the transfer could start immediately. /// - /// The username for which slot availability is to be checked. - /// A value indicating whether an upload slot is available for the specified username. - public bool IsSlotAvailable(string username) + /// The username for which to estimate. + /// + /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. + /// + public int ForecastPosition(string username) { var group = Users.GetGroup(username); - if (Groups.TryGetValue(group, out var record)) + // if there's a slot available, the user will enter the queue at position 0 (will start immediately) + if (Groups.TryGetValue(group, out var groupRecord) && groupRecord.SlotAvailable) { - return record.SlotAvailable; + return 0; } - return false; + // no slots are available for this group, so there's at least as many uploads in progress as there are slots. count all + // uploads (in progress or otherwise) + var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == group); + + return uploadsForGroup.Count() + 1; } private void Configure(Options options) @@ -342,14 +344,14 @@ namespace slskd.Transfers MaxSlots = options.Global.Upload.Slots; // statically add built-in groups - var groups = new List() + var groups = new List() { // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, and a FIFO // strategy. all other groups have a minimum priority of 1 (enforced by options validation) to ensure that // privileged users always take priority, regardless of user configuration. the strategy is fixed to FIFO // because that gives privileged users the closest experience to the official client, as well as the // appearance of fairness once the first upload begins. - new Group() + new UploadGroup() { Name = Application.PrivilegedGroup, Priority = 0, @@ -357,7 +359,7 @@ namespace slskd.Transfers UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup), Strategy = QueueStrategy.FirstInFirstOut, }, - new Group() + new UploadGroup() { Name = Application.DefaultGroup, Priority = options.Groups.Default.Upload.Priority, @@ -365,7 +367,7 @@ namespace slskd.Transfers UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true), }, - new Group() + new UploadGroup() { Name = Application.LeecherGroup, Priority = options.Groups.Leechers.Upload.Priority, @@ -376,7 +378,7 @@ namespace slskd.Transfers }; // dynamically add user-defined groups - groups.AddRange(options.Groups.UserDefined.Select(kvp => new Group() + groups.AddRange(options.Groups.UserDefined.Select(kvp => new UploadGroup() { Name = kvp.Key, Priority = kvp.Value.Upload.Priority, -- cgit v1.2.3 From 34265b07a022293a122e313959732805963d41f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 09:09:14 -0500 Subject: use single call to forecast --- src/slskd/Application.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a12e039b..4e6444a3 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -869,17 +869,16 @@ namespace slskd { await RefreshUserStatisticsIfNeeded(); - var hasFreeSlot = Transfers.Uploads.Queue.IsSlotAvailable(username); - var estimatedQueueLength = Transfers.Uploads.Queue.EstimatePosition(username); + var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (free slot?: {hasFreeSlot}, queue length: {estimatedQueueLength})"); + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (forecasted position: {forecastedPosition})"); return new SearchResponse( Client.Username, token, uploadSpeed: State.CurrentValue.Server.Statistics.AverageSpeed, - freeUploadSlots: hasFreeSlot ? 1 : 0, - queueLength: estimatedQueueLength, + freeUploadSlots: forecastedPosition == 0 ? 1 : 0, + queueLength: forecastedPosition, fileList: results); } -- cgit v1.2.3 From 50ccefed96b07455aedd98d75002c84df73275f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 09:53:55 -0500 Subject: add Contains() to TransferTracker --- src/slskd/Transfers/ITransferTracker.cs | 9 +++++++++ src/slskd/Transfers/TransferTracker.cs | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs index 4edbdd63..f8715873 100644 --- a/src/slskd/Transfers/ITransferTracker.cs +++ b/src/slskd/Transfers/ITransferTracker.cs @@ -53,5 +53,14 @@ namespace slskd.Transfers /// /// bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); + + /// + /// Gets a value indicating whether a transfer matching the specified information is tracked. + /// + /// + /// + /// + /// + bool Contains(TransferDirection direction, string username, string filename); } } \ No newline at end of file diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs index d70717dd..358abf6f 100644 --- a/src/slskd/Transfers/TransferTracker.cs +++ b/src/slskd/Transfers/TransferTracker.cs @@ -181,6 +181,26 @@ namespace slskd.Transfers } } + /// + /// Gets a value indicating whether a transfer matching the specified information is tracked. + /// + /// + /// + /// + /// + public bool Contains(TransferDirection direction, string username, string filename) + { + if (Transfers.TryGetValue(direction, out var directionDict)) + { + if (directionDict.TryGetValue(username, out var userDict)) + { + return userDict.Values.Any(record => record.Transfer.Filename == filename); + } + } + + return false; + } + private ConcurrentDictionary GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource) { var r = new ConcurrentDictionary(); -- cgit v1.2.3 From 4143b4e4e9d42ecfbef9e2f7f71629f0c0725cae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 28 Jun 2022 09:54:04 -0500 Subject: fix check of re-download requests --- src/slskd/Application.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 4e6444a3..d7078bde 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -619,6 +619,13 @@ namespace slskd /// private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { + // remote clients might sometimes re-request downloads to check the status. don't try to add the download again + // if it is already tracked. + if (tracker.Contains(TransferDirection.Upload, username, filename)) + { + return; + } + _ = endpoint; string localFilename; FileInfo fileInfo = default; @@ -642,14 +649,6 @@ namespace slskd throw new DownloadEnqueueException($"File not shared."); } - // TODO: fix this; it doesn't work. reproduce by downloading a file, then re-requesting the same file. - if (tracker.TryGet(TransferDirection.Upload, username, localFilename, out _)) - { - // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse - Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); - return; - } - // create a new cancellation token source so that we can cancel the upload from the UI. var cts = new CancellationTokenSource(); var topts = new TransferOptions( -- cgit v1.2.3