2
0

VideoListResolver.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using Emby.Naming.Common;
  7. using Jellyfin.Extensions;
  8. using MediaBrowser.Model.IO;
  9. namespace Emby.Naming.Video
  10. {
  11. /// <summary>
  12. /// Resolves alternative versions and extras from list of video files.
  13. /// </summary>
  14. public static partial class VideoListResolver
  15. {
  16. [GeneratedRegex("[0-9]{2}[0-9]+[ip]", RegexOptions.IgnoreCase)]
  17. private static partial Regex ResolutionRegex();
  18. [GeneratedRegex(@"^\[([^]]*)\]")]
  19. private static partial Regex CheckMultiVersionRegex();
  20. /// <summary>
  21. /// Resolves alternative versions and extras from list of video files.
  22. /// </summary>
  23. /// <param name="videoInfos">List of related video files.</param>
  24. /// <param name="namingOptions">The naming options.</param>
  25. /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param>
  26. /// <param name="parseName">Whether to parse the name or use the filename.</param>
  27. /// <param name="libraryRoot">Top-level folder for the containing library.</param>
  28. /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns>
  29. public static IReadOnlyList<VideoInfo> Resolve(IReadOnlyList<VideoFileInfo> videoInfos, NamingOptions namingOptions, bool supportMultiVersion = true, bool parseName = true, string? libraryRoot = "")
  30. {
  31. // Filter out all extras, otherwise they could cause stacks to not be resolved
  32. // See the unit test TestStackedWithTrailer
  33. var nonExtras = videoInfos
  34. .Where(i => i.ExtraType is null)
  35. .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });
  36. var stackResult = StackResolver.Resolve(nonExtras, namingOptions).ToList();
  37. var remainingFiles = new List<VideoFileInfo>();
  38. var standaloneMedia = new List<VideoFileInfo>();
  39. for (var i = 0; i < videoInfos.Count; i++)
  40. {
  41. var current = videoInfos[i];
  42. if (stackResult.Any(s => s.ContainsFile(current.Path, current.IsDirectory)))
  43. {
  44. continue;
  45. }
  46. if (current.ExtraType is null)
  47. {
  48. standaloneMedia.Add(current);
  49. }
  50. else
  51. {
  52. remainingFiles.Add(current);
  53. }
  54. }
  55. var list = new List<VideoInfo>();
  56. foreach (var stack in stackResult)
  57. {
  58. var info = new VideoInfo(stack.Name)
  59. {
  60. Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions, parseName, libraryRoot))
  61. .OfType<VideoFileInfo>()
  62. .ToList()
  63. };
  64. info.Year = info.Files[0].Year;
  65. list.Add(info);
  66. }
  67. foreach (var media in standaloneMedia)
  68. {
  69. var info = new VideoInfo(media.Name) { Files = new[] { media } };
  70. info.Year = info.Files[0].Year;
  71. list.Add(info);
  72. }
  73. if (supportMultiVersion)
  74. {
  75. list = GetVideosGroupedByVersion(list, namingOptions);
  76. }
  77. // Whatever files are left, just add them
  78. list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name)
  79. {
  80. Files = new[] { i },
  81. Year = i.Year,
  82. ExtraType = i.ExtraType
  83. }));
  84. return list;
  85. }
  86. private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, NamingOptions namingOptions)
  87. {
  88. if (videos.Count == 0)
  89. {
  90. return videos;
  91. }
  92. var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan()));
  93. if (folderName.Length <= 1 || !HaveSameYear(videos))
  94. {
  95. return videos;
  96. }
  97. // Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if]
  98. VideoInfo? primary = null;
  99. for (var i = 0; i < videos.Count; i++)
  100. {
  101. var video = videos[i];
  102. if (video.ExtraType is not null)
  103. {
  104. continue;
  105. }
  106. if (!IsEligibleForMultiVersion(folderName, video.Files[0].FileNameWithoutExtension, namingOptions))
  107. {
  108. return videos;
  109. }
  110. if (folderName.Equals(video.Files[0].FileNameWithoutExtension, StringComparison.Ordinal))
  111. {
  112. primary = video;
  113. }
  114. }
  115. if (videos.Count > 1)
  116. {
  117. var groups = videos.GroupBy(x => ResolutionRegex().IsMatch(x.Files[0].FileNameWithoutExtension)).ToList();
  118. videos.Clear();
  119. foreach (var group in groups)
  120. {
  121. if (group.Key)
  122. {
  123. videos.InsertRange(0, group
  124. .OrderByDescending(x => ResolutionRegex().Match(x.Files[0].FileNameWithoutExtension.ToString()).Value, new AlphanumericComparator())
  125. .ThenBy(x => x.Files[0].FileNameWithoutExtension.ToString(), new AlphanumericComparator()));
  126. }
  127. else
  128. {
  129. videos.AddRange(group.OrderBy(x => x.Files[0].FileNameWithoutExtension.ToString(), new AlphanumericComparator()));
  130. }
  131. }
  132. }
  133. primary ??= videos[0];
  134. videos.Remove(primary);
  135. var list = new List<VideoInfo>
  136. {
  137. primary
  138. };
  139. list[0].AlternateVersions = videos.Select(x => x.Files[0]).ToArray();
  140. list[0].Name = folderName.ToString();
  141. return list;
  142. }
  143. private static bool HaveSameYear(IReadOnlyList<VideoInfo> videos)
  144. {
  145. if (videos.Count == 1)
  146. {
  147. return true;
  148. }
  149. var firstYear = videos[0].Year ?? -1;
  150. for (var i = 1; i < videos.Count; i++)
  151. {
  152. if ((videos[i].Year ?? -1) != firstYear)
  153. {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. private static bool IsEligibleForMultiVersion(ReadOnlySpan<char> folderName, ReadOnlySpan<char> testFilename, NamingOptions namingOptions)
  160. {
  161. if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
  162. {
  163. return false;
  164. }
  165. // Remove the folder name before cleaning as we don't care about cleaning that part
  166. if (folderName.Length <= testFilename.Length)
  167. {
  168. testFilename = testFilename[folderName.Length..].Trim();
  169. }
  170. // There are no span overloads for regex unfortunately
  171. if (CleanStringParser.TryClean(testFilename.ToString(), namingOptions.CleanStringRegexes, out var cleanName))
  172. {
  173. testFilename = cleanName.AsSpan().Trim();
  174. }
  175. // The CleanStringParser should have removed common keywords etc.
  176. return testFilename.IsEmpty
  177. || testFilename[0] == '-'
  178. || CheckMultiVersionRegex().IsMatch(testFilename);
  179. }
  180. }
  181. }