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 +++++++++++++++++++++++++++++++++++ 1 file changed, 370 insertions(+) create mode 100644 src/slskd/Common/CommonExtensions.cs (limited to 'src/slskd/Common/CommonExtensions.cs') 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 -- cgit v1.2.3