//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
namespace slskd
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
///
/// Common extensions; things not specific to Soulseek or slskd.
///
public static class CommonExtensions
{
private static readonly JsonSerializerOptions DefaultJsonSerializerOptions = GetJsonSerializerOptions();
///
/// Times this Task out after the specified TimeSpan.
///
/// The result type.
/// The task.
/// The timeout.
/// The operation context.
/// Thrown when the task times out.
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task;
}
else
{
throw new TimeoutException("The operation has timed out.");
}
}
///
/// Times this Task out after the specified TimeSpan.
///
/// The task.
/// The timeout.
/// The operation context.
/// Thrown when the task times out.
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{
using var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
await task;
}
else
{
throw new TimeoutException("The operation has timed out.");
}
}
///
/// 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 is null || right is null)
{
if (left is null == right is null)
{
return [];
}
return [(null, parentFqn ?? string.Empty, left, right)];
}
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 (leftVal is null || rightVal is null)
{
if (leftVal is null == rightVal is null)
{
continue;
}
differences.Add((prop, fqn, leftVal, rightVal));
continue;
}
if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
if (leftVal.ToJson() != rightVal.ToJson())
{
differences.Add((prop, fqn, leftVal, rightVal));
}
}
else if (propType.IsPrimitive || propType.IsEnum || 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;
}
///
/// Makes a best-guess determination of the directory separator character used by a remote system,
/// based on the characters present in the specified .
///
/// The fully qualified remote filename to inspect.
/// The guessed directory separator.
public static char GuessDirectorySeparator(this string remoteFilename)
{
// forward slash is a forbidden character on all operating systems; if the specified string contains it,
// then it is coming from the OS's directory separator
if (remoteFilename.Contains('/'))
{
return '/';
}
// if the given string doesn't contain any forward slashes, it either lacks a directory separator at all
// (potentially impossible?) or it is using backspaces. backspaces are used by all major clients, so
// this should be a safe assumption.
return '\\';
}
///
/// Returns the directory name of the given , using the specified
/// to split and join directories and filename.
///
/// The path for which to return the directory name.
/// The directory separator character.
/// The specified path, less the last segment.
public static string GetDirectoryName(this string path, char directorySeparator)
{
return string.Join(directorySeparator, path.Split(directorySeparator).SkipLast(1));
}
///
/// Returns the directory from the given path, regardless of separator format.
///
/// The path.
/// The directory.
public static string DirectoryName(this string path)
{
return path.GetDirectoryName(path.GuessDirectorySeparator());
}
///
/// Safely disposes this object without throwing if it is already exposed.
///
/// The object.
public static void TryDispose(this IDisposable obj)
{
try
{
obj?.Dispose();
}
catch (ObjectDisposedException)
{
// no-op; something else beat us to it
}
}
///
/// Safely cancels this without throwing if it is disposed.
///
/// The CancellationTokenSource instance.
/// A value indicating whether to swallow ObjectDisposedException, if it occurs.
/// A value indicating whether the cancellation completed successfully.
public static bool Cancel(this CancellationTokenSource cts, bool swallowObjectDisposedException)
{
try
{
cts.Cancel();
return true;
}
catch (ObjectDisposedException) when (swallowObjectDisposedException)
{
return false;
}
}
///
/// 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 occurrence 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);
}
///
/// Serializes the JWT.
///
/// The JWT.
/// The serialized string.
public static string Serialize(this JwtSecurityToken jwt)
=> new JwtSecurityTokenHandler().WriteToken(jwt);
///
/// 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, DefaultJsonSerializerOptions);
///
/// 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 deserialized from the string.
public static T FromYaml(this string str) => new DeserializerBuilder()
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.Build()
.Deserialize(str);
///
/// Converts the given path to the normalized format (normalizes path separators to backslashes).
///
///
/// Various Soulseek clients (including this one) assume paths to use backslashes, regardless of the host system.
///
/// The path to convert.
/// The converted path.
public static string NormalizePathForSoulseek(this string path)
{
return path.Replace('/', '\\');
}
///
/// , but for paths normalized to use backslashes.
///
///
///
public static string GetNormalizedDirectoryName(this string path)
{
return string.Join('\\', path.Split('\\').SkipLast(1));
}
///
/// , but for paths normalized to use backslashes.
///
///
///
public static string GetNormalizedFileName(this string path)
{
return path.Split('\\').TakeLast(1).First();
}
///
/// Converts a ModelStateDictionary into a human-readable format.
///
/// The ModelStateDictionary to format.
/// The formatted error string.
public static string GetReadableString(this ModelStateDictionary dictionary)
{
if (dictionary == null || dictionary.IsValid)
{
return string.Empty;
}
return dictionary.Values
.Where(v => v.Errors.Any())
.Select(v =>
v.Errors
.Select(e => GetErrorAndOrExceptionMessage(e))
.Aggregate((a, b) => string.Join(", ", new[] { a, b })))
.Aggregate((a, b) => string.Join(" ", new[] { a, b }));
}
///
/// Returns the , the for the ModelError, or both if both are present.
///
/// The ModelError from which to retrieve the error message.
/// The retrieved error message.
public static string GetErrorAndOrExceptionMessage(this ModelError error)
{
var ex = error?.Exception?.Message;
return string.IsNullOrEmpty(error?.ErrorMessage) ? ex :
string.IsNullOrEmpty(ex) ? error?.ErrorMessage : $"{error?.ErrorMessage} ({ex})";
}
///
/// 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<,>));
}
///
/// Casts the string to .
///
/// The Enum type to which to cast.
/// The string to cast.
/// The cast enum.
public static T ToEnum(this string str)
{
return (T)Enum.Parse(typeof(T), str, ignoreCase: true);
}
///
/// 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 deserialized from the string.
public static T FromJson(this string str) => JsonSerializer.Deserialize(str, DefaultJsonSerializerOptions);
///
/// Applies the standard json serializer options to the specified instance.
///
/// The instance.
/// The instances with the standard options applied.
public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt)
=> GetJsonSerializerOptions(opt);
private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null)
{
var options = opt ?? new JsonSerializerOptions();
options.Converters.Add(new IPAddressConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new KnownUnsupportedTypeConverter());
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
return options;
}
}
}