PathExtensions.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using MediaBrowser.Common.Providers;
  4. namespace Emby.Server.Implementations.Library
  5. {
  6. /// <summary>
  7. /// Class providing extension methods for working with paths.
  8. /// </summary>
  9. public static class PathExtensions
  10. {
  11. /// <summary>
  12. /// Gets the attribute value.
  13. /// </summary>
  14. /// <param name="str">The STR.</param>
  15. /// <param name="attribute">The attrib.</param>
  16. /// <returns>System.String.</returns>
  17. /// <exception cref="ArgumentException"><paramref name="str" /> or <paramref name="attribute" /> is empty.</exception>
  18. public static string? GetAttributeValue(this ReadOnlySpan<char> str, ReadOnlySpan<char> attribute)
  19. {
  20. if (str.Length == 0)
  21. {
  22. throw new ArgumentException("String can't be empty.", nameof(str));
  23. }
  24. if (attribute.Length == 0)
  25. {
  26. throw new ArgumentException("String can't be empty.", nameof(attribute));
  27. }
  28. var attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
  29. // Must be at least 3 characters after the attribute =, ], any character.
  30. var maxIndex = str.Length - attribute.Length - 3;
  31. while (attributeIndex > -1 && attributeIndex < maxIndex)
  32. {
  33. var attributeEnd = attributeIndex + attribute.Length;
  34. if (attributeIndex > 0
  35. && str[attributeIndex - 1] == '['
  36. && (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
  37. {
  38. var closingIndex = str[attributeEnd..].IndexOf(']');
  39. // Must be at least 1 character before the closing bracket.
  40. if (closingIndex > 1)
  41. {
  42. return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
  43. }
  44. }
  45. str = str[attributeEnd..];
  46. attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
  47. }
  48. // for imdbid we also accept pattern matching
  49. if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
  50. {
  51. var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
  52. return match ? imdbId.ToString() : null;
  53. }
  54. return null;
  55. }
  56. /// <summary>
  57. /// Replaces a sub path with another sub path and normalizes the final path.
  58. /// </summary>
  59. /// <param name="path">The original path.</param>
  60. /// <param name="subPath">The original sub path.</param>
  61. /// <param name="newSubPath">The new sub path.</param>
  62. /// <param name="newPath">The result of the sub path replacement.</param>
  63. /// <returns>The path after replacing the sub path.</returns>
  64. /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramref name="newSubPath" /> is empty.</exception>
  65. public static bool TryReplaceSubPath(
  66. [NotNullWhen(true)] this string? path,
  67. [NotNullWhen(true)] string? subPath,
  68. [NotNullWhen(true)] string? newSubPath,
  69. [NotNullWhen(true)] out string? newPath)
  70. {
  71. newPath = null;
  72. if (string.IsNullOrEmpty(path)
  73. || string.IsNullOrEmpty(subPath)
  74. || string.IsNullOrEmpty(newSubPath)
  75. || subPath.Length > path.Length)
  76. {
  77. return false;
  78. }
  79. char oldDirectorySeparatorChar;
  80. char newDirectorySeparatorChar;
  81. // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
  82. // The reasoning behind this is that a forward slash likely means it's a Linux path and
  83. // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
  84. if (newSubPath.Contains('/', StringComparison.Ordinal))
  85. {
  86. oldDirectorySeparatorChar = '\\';
  87. newDirectorySeparatorChar = '/';
  88. }
  89. else
  90. {
  91. oldDirectorySeparatorChar = '/';
  92. newDirectorySeparatorChar = '\\';
  93. }
  94. path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
  95. subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar);
  96. // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
  97. // when the sub path matches a similar but in-complete subpath
  98. var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
  99. if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
  100. {
  101. return false;
  102. }
  103. if (path.Length > subPath.Length
  104. && !oldSubPathEndsWithSeparator
  105. && path[subPath.Length] != newDirectorySeparatorChar)
  106. {
  107. return false;
  108. }
  109. var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
  110. // Ensure that the path with the old subpath removed starts with a leading dir separator
  111. int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
  112. newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
  113. return true;
  114. }
  115. }
  116. }