VideoListResolver.cs 7.3 KB

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