VideoListResolver.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 MediaBrowser.Model.Entities;
  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. /// <summary>
  17. /// Resolves alternative versions and extras from list of video files.
  18. /// </summary>
  19. /// <param name="files">List of related video files.</param>
  20. /// <param name="namingOptions">The naming options.</param>
  21. /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param>
  22. /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns>
  23. public static IEnumerable<VideoInfo> Resolve(List<FileSystemMetadata> files, NamingOptions namingOptions, bool supportMultiVersion = true)
  24. {
  25. var videoInfos = files
  26. .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, namingOptions))
  27. .OfType<VideoFileInfo>()
  28. .ToList();
  29. // Filter out all extras, otherwise they could cause stacks to not be resolved
  30. // See the unit test TestStackedWithTrailer
  31. var nonExtras = videoInfos
  32. .Where(i => i.ExtraType == null)
  33. .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });
  34. var stackResult = new StackResolver(namingOptions)
  35. .Resolve(nonExtras).ToList();
  36. var remainingFiles = videoInfos
  37. .Where(i => !stackResult.Any(s => i.Path != null && s.ContainsFile(i.Path, i.IsDirectory)))
  38. .ToList();
  39. var list = new List<VideoInfo>();
  40. foreach (var stack in stackResult)
  41. {
  42. var info = new VideoInfo(stack.Name)
  43. {
  44. Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions))
  45. .OfType<VideoFileInfo>()
  46. .ToList()
  47. };
  48. info.Year = info.Files[0].Year;
  49. var extras = ExtractExtras(remainingFiles, stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0].AsSpan()), namingOptions.VideoFlagDelimiters);
  50. if (extras.Count > 0)
  51. {
  52. info.Extras = extras;
  53. }
  54. list.Add(info);
  55. }
  56. var standaloneMedia = remainingFiles
  57. .Where(i => i.ExtraType == null)
  58. .ToList();
  59. foreach (var media in standaloneMedia)
  60. {
  61. var info = new VideoInfo(media.Name) { Files = new[] { media } };
  62. info.Year = info.Files[0].Year;
  63. remainingFiles.Remove(media);
  64. var extras = ExtractExtras(remainingFiles, media.FileNameWithoutExtension, namingOptions.VideoFlagDelimiters);
  65. info.Extras = extras;
  66. list.Add(info);
  67. }
  68. if (supportMultiVersion)
  69. {
  70. list = GetVideosGroupedByVersion(list, namingOptions);
  71. }
  72. // If there's only one resolved video, use the folder name as well to find extras
  73. if (list.Count == 1)
  74. {
  75. var info = list[0];
  76. var videoPath = list[0].Files[0].Path;
  77. var parentPath = Path.GetDirectoryName(videoPath.AsSpan());
  78. if (!parentPath.IsEmpty)
  79. {
  80. var folderName = Path.GetFileName(parentPath);
  81. if (!folderName.IsEmpty)
  82. {
  83. var extras = ExtractExtras(remainingFiles, folderName, namingOptions.VideoFlagDelimiters);
  84. extras.AddRange(info.Extras);
  85. info.Extras = extras;
  86. }
  87. }
  88. // Add the extras that are just based on file name as well
  89. var extrasByFileName = remainingFiles
  90. .Where(i => i.ExtraRule != null && i.ExtraRule.RuleType == ExtraRuleType.Filename)
  91. .ToList();
  92. remainingFiles = remainingFiles
  93. .Except(extrasByFileName)
  94. .ToList();
  95. extrasByFileName.AddRange(info.Extras);
  96. info.Extras = extrasByFileName;
  97. }
  98. // If there's only one video, accept all trailers
  99. // Be lenient because people use all kinds of mishmash conventions with trailers.
  100. if (list.Count == 1)
  101. {
  102. var trailers = remainingFiles
  103. .Where(i => i.ExtraType == ExtraType.Trailer)
  104. .ToList();
  105. trailers.AddRange(list[0].Extras);
  106. list[0].Extras = trailers;
  107. remainingFiles = remainingFiles
  108. .Except(trailers)
  109. .ToList();
  110. }
  111. // Whatever files are left, just add them
  112. list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name)
  113. {
  114. Files = new[] { i },
  115. Year = i.Year
  116. }));
  117. return list;
  118. }
  119. private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, NamingOptions namingOptions)
  120. {
  121. if (videos.Count == 0)
  122. {
  123. return videos;
  124. }
  125. var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan()));
  126. if (folderName.Length <= 1 || !HaveSameYear(videos))
  127. {
  128. return videos;
  129. }
  130. // Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if]
  131. for (var i = 0; i < videos.Count; i++)
  132. {
  133. var video = videos[i];
  134. if (!IsEligibleForMultiVersion(folderName, video.Files[0].Path, namingOptions))
  135. {
  136. return videos;
  137. }
  138. }
  139. // The list is created and overwritten in the caller, so we are allowed to do in-place sorting
  140. videos.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));
  141. var list = new List<VideoInfo>
  142. {
  143. videos[0]
  144. };
  145. var alternateVersionsLen = videos.Count - 1;
  146. var alternateVersions = new VideoFileInfo[alternateVersionsLen];
  147. var extras = new List<VideoFileInfo>(list[0].Extras);
  148. for (int i = 0; i < alternateVersionsLen; i++)
  149. {
  150. var video = videos[i + 1];
  151. alternateVersions[i] = video.Files[0];
  152. extras.AddRange(video.Extras);
  153. }
  154. list[0].AlternateVersions = alternateVersions;
  155. list[0].Name = folderName.ToString();
  156. list[0].Extras = extras;
  157. return list;
  158. }
  159. private static bool HaveSameYear(IReadOnlyList<VideoInfo> videos)
  160. {
  161. if (videos.Count == 1)
  162. {
  163. return true;
  164. }
  165. var firstYear = videos[0].Year ?? -1;
  166. for (var i = 1; i < videos.Count; i++)
  167. {
  168. if ((videos[i].Year ?? -1) != firstYear)
  169. {
  170. return false;
  171. }
  172. }
  173. return true;
  174. }
  175. private static bool IsEligibleForMultiVersion(ReadOnlySpan<char> folderName, string testFilePath, NamingOptions namingOptions)
  176. {
  177. var testFilename = Path.GetFileNameWithoutExtension(testFilePath.AsSpan());
  178. if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
  179. {
  180. return false;
  181. }
  182. // Remove the folder name before cleaning as we don't care about cleaning that part
  183. if (folderName.Length <= testFilename.Length)
  184. {
  185. testFilename = testFilename[folderName.Length..].Trim();
  186. }
  187. // There are no span overloads for regex unfortunately
  188. var tmpTestFilename = testFilename.ToString();
  189. if (CleanStringParser.TryClean(tmpTestFilename, namingOptions.CleanStringRegexes, out var cleanName))
  190. {
  191. tmpTestFilename = cleanName.Trim().ToString();
  192. }
  193. // The CleanStringParser should have removed common keywords etc.
  194. return string.IsNullOrEmpty(tmpTestFilename)
  195. || testFilename[0] == '-'
  196. || Regex.IsMatch(tmpTestFilename, @"^\[([^]]*)\]", RegexOptions.Compiled);
  197. }
  198. private static ReadOnlySpan<char> TrimFilenameDelimiters(ReadOnlySpan<char> name, ReadOnlySpan<char> videoFlagDelimiters)
  199. {
  200. return name.IsEmpty ? name : name.TrimEnd().TrimEnd(videoFlagDelimiters).TrimEnd();
  201. }
  202. private static bool StartsWith(ReadOnlySpan<char> fileName, ReadOnlySpan<char> baseName, ReadOnlySpan<char> trimmedBaseName)
  203. {
  204. if (baseName.IsEmpty)
  205. {
  206. return false;
  207. }
  208. return fileName.StartsWith(baseName, StringComparison.OrdinalIgnoreCase)
  209. || (!trimmedBaseName.IsEmpty && fileName.StartsWith(trimmedBaseName, StringComparison.OrdinalIgnoreCase));
  210. }
  211. /// <summary>
  212. /// Finds similar filenames to that of [baseName] and removes any matches from [remainingFiles].
  213. /// </summary>
  214. /// <param name="remainingFiles">The list of remaining filenames.</param>
  215. /// <param name="baseName">The base name to use for the comparison.</param>
  216. /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
  217. /// <returns>A list of video extras for [baseName].</returns>
  218. private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> baseName, ReadOnlySpan<char> videoFlagDelimiters)
  219. {
  220. return ExtractExtras(remainingFiles, baseName, ReadOnlySpan<char>.Empty, videoFlagDelimiters);
  221. }
  222. /// <summary>
  223. /// Finds similar filenames to that of [firstBaseName] and [secondBaseName] and removes any matches from [remainingFiles].
  224. /// </summary>
  225. /// <param name="remainingFiles">The list of remaining filenames.</param>
  226. /// <param name="firstBaseName">The first base name to use for the comparison.</param>
  227. /// <param name="secondBaseName">The second base name to use for the comparison.</param>
  228. /// <param name="videoFlagDelimiters">The video flag delimiters.</param>
  229. /// <returns>A list of video extras for [firstBaseName] and [secondBaseName].</returns>
  230. private static List<VideoFileInfo> ExtractExtras(IList<VideoFileInfo> remainingFiles, ReadOnlySpan<char> firstBaseName, ReadOnlySpan<char> secondBaseName, ReadOnlySpan<char> videoFlagDelimiters)
  231. {
  232. var trimmedFirstBaseName = TrimFilenameDelimiters(firstBaseName, videoFlagDelimiters);
  233. var trimmedSecondBaseName = TrimFilenameDelimiters(secondBaseName, videoFlagDelimiters);
  234. var result = new List<VideoFileInfo>();
  235. for (var pos = remainingFiles.Count - 1; pos >= 0; pos--)
  236. {
  237. var file = remainingFiles[pos];
  238. if (file.ExtraType == null)
  239. {
  240. continue;
  241. }
  242. var filename = file.FileNameWithoutExtension;
  243. if (StartsWith(filename, firstBaseName, trimmedFirstBaseName)
  244. || StartsWith(filename, secondBaseName, trimmedSecondBaseName))
  245. {
  246. result.Add(file);
  247. remainingFiles.RemoveAt(pos);
  248. }
  249. }
  250. return result;
  251. }
  252. }
  253. }