VideoListResolver.cs 7.4 KB

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