jellyfin/Emby.Server.Implementations/Library/PathExtensions.cs

195 lines
8.2 KiB
C#
Raw Normal View History

using System;
using System.Diagnostics.CodeAnalysis;
2023-03-30 07:59:21 -07:00
using System.IO;
using MediaBrowser.Common.Providers;
2014-12-01 05:43:34 -07:00
namespace Emby.Server.Implementations.Library
2014-12-01 05:43:34 -07:00
{
2019-11-01 10:38:54 -07:00
/// <summary>
/// Class providing extension methods for working with paths.
/// </summary>
2014-12-01 05:43:34 -07:00
public static class PathExtensions
{
/// <summary>
/// Gets the attribute value.
/// </summary>
/// <param name="str">The STR.</param>
2020-04-19 06:18:28 -07:00
/// <param name="attribute">The attrib.</param>
2014-12-01 05:43:34 -07:00
/// <returns>System.String.</returns>
2020-04-21 01:18:26 -07:00
/// <exception cref="ArgumentException"><paramref name="str" /> or <paramref name="attribute" /> is empty.</exception>
2021-11-27 16:10:43 -07:00
public static string? GetAttributeValue(this ReadOnlySpan<char> str, ReadOnlySpan<char> attribute)
2014-12-01 05:43:34 -07:00
{
2020-04-19 06:18:28 -07:00
if (str.Length == 0)
2014-12-01 05:43:34 -07:00
{
2020-04-19 06:18:28 -07:00
throw new ArgumentException("String can't be empty.", nameof(str));
2014-12-01 05:43:34 -07:00
}
2020-04-19 06:18:28 -07:00
if (attribute.Length == 0)
2014-12-01 05:43:34 -07:00
{
2020-04-19 06:18:28 -07:00
throw new ArgumentException("String can't be empty.", nameof(attribute));
2014-12-01 05:43:34 -07:00
}
2021-12-09 08:38:00 -07:00
var attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
2021-12-09 08:06:06 -07:00
// Must be at least 3 characters after the attribute =, ], any character,
// then we offset it by 1, because we want the index and not length.
var maxIndex = str.Length - attribute.Length - 2;
2021-12-09 08:06:06 -07:00
while (attributeIndex > -1 && attributeIndex < maxIndex)
2014-12-01 05:43:34 -07:00
{
2021-12-09 08:06:06 -07:00
var attributeEnd = attributeIndex + attribute.Length;
if (attributeIndex > 0
&& str[attributeIndex - 1] == '['
2021-12-31 08:51:50 -07:00
&& (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
2021-11-27 16:10:43 -07:00
{
2021-12-09 08:06:06 -07:00
var closingIndex = str[attributeEnd..].IndexOf(']');
2021-12-11 20:35:43 -07:00
// Must be at least 1 character before the closing bracket.
if (closingIndex > 1)
2021-12-09 08:06:06 -07:00
{
return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
}
2021-11-27 16:10:43 -07:00
}
2021-12-09 08:06:06 -07:00
str = str[attributeEnd..];
2021-12-09 08:38:00 -07:00
attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
2014-12-01 05:43:34 -07:00
}
2019-11-01 10:38:54 -07:00
2015-01-02 07:29:20 -07:00
// for imdbid we also accept pattern matching
2021-11-27 16:10:43 -07:00
if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
2015-01-02 07:29:20 -07:00
{
var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
return match ? imdbId.ToString() : null;
2015-01-02 07:29:20 -07:00
}
2015-01-04 07:34:15 -07:00
2014-12-01 05:43:34 -07:00
return null;
}
/// <summary>
/// Replaces a sub path with another sub path and normalizes the final path.
/// </summary>
/// <param name="path">The original path.</param>
/// <param name="subPath">The original sub path.</param>
/// <param name="newSubPath">The new sub path.</param>
2021-10-02 10:59:58 -07:00
/// <param name="newPath">The result of the sub path replacement.</param>
/// <returns>The path after replacing the sub path.</returns>
/// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramref name="newSubPath" /> is empty.</exception>
public static bool TryReplaceSubPath(
[NotNullWhen(true)] this string? path,
[NotNullWhen(true)] string? subPath,
[NotNullWhen(true)] string? newSubPath,
[NotNullWhen(true)] out string? newPath)
{
2021-03-06 11:07:02 -07:00
newPath = null;
if (string.IsNullOrEmpty(path)
|| string.IsNullOrEmpty(subPath)
|| string.IsNullOrEmpty(newSubPath)
|| subPath.Length > path.Length)
{
2021-03-06 11:07:02 -07:00
return false;
}
2023-04-01 03:59:07 -07:00
subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
path = path.NormalizePath(newDirectorySeparatorChar);
// We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
// when the sub path matches a similar but in-complete subpath
2021-03-06 06:01:37 -07:00
var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (path.Length > subPath.Length
&& !oldSubPathEndsWithSeparator
&& path[subPath.Length] != newDirectorySeparatorChar)
{
return false;
}
2023-04-01 04:03:55 -07:00
var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
2021-03-06 06:01:37 -07:00
// Ensure that the path with the old subpath removed starts with a leading dir separator
int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
return true;
}
2023-03-30 07:59:21 -07:00
/// <summary>
/// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorChar"/>.
/// </summary>
/// <param name="path">The path to canonicalize.</param>
/// <returns>The fully expanded, normalized path.</returns>
public static string Canonicalize(this string path)
{
2023-04-01 04:03:55 -07:00
return Path.GetFullPath(path).NormalizePath();
2023-03-30 07:59:21 -07:00
}
/// <summary>
/// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySeparatorChar"/>.
/// </summary>
/// <param name="path">The path to normalize.</param>
/// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
2023-04-01 03:59:07 -07:00
[return: NotNullIfNotNull(nameof(path))]
2023-03-30 07:59:21 -07:00
public static string? NormalizePath(this string? path)
{
return path.NormalizePath(Path.DirectorySeparatorChar);
}
/// <summary>
/// Normalizes the path's directory separator character.
/// </summary>
/// <param name="path">The path to normalize.</param>
/// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
/// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
2023-04-01 03:59:07 -07:00
[return: NotNullIfNotNull(nameof(path))]
2023-03-30 07:59:21 -07:00
public static string? NormalizePath(this string? path, out char separator)
{
if (string.IsNullOrEmpty(path))
{
separator = default;
return path;
}
var newSeparator = '\\';
// True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
// The reasoning behind this is that a forward slash likely means it's a Linux path and
// so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
if (path.Contains('/', StringComparison.Ordinal))
{
newSeparator = '/';
}
separator = newSeparator;
2023-04-01 04:03:55 -07:00
return path.NormalizePath(newSeparator);
2023-03-30 07:59:21 -07:00
}
/// <summary>
/// Normalizes the path's directory separator character to the specified character.
/// </summary>
/// <param name="path">The path to normalize.</param>
/// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separator.</param>
/// <returns>The normalized path.</returns>
/// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exception>
2023-04-01 03:59:07 -07:00
[return: NotNullIfNotNull(nameof(path))]
2023-03-30 07:59:21 -07:00
public static string? NormalizePath(this string? path, char newSeparator)
{
const char Bs = '\\';
const char Fs = '/';
if (!(newSeparator == Bs || newSeparator == Fs))
{
throw new ArgumentException("The character must be a directory separator.");
}
if (string.IsNullOrEmpty(path))
{
return path;
}
2023-04-01 03:59:07 -07:00
return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
2023-03-30 07:59:21 -07:00
}
2014-12-01 05:43:34 -07:00
}
}