MovieResolver.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #nullable disable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. using Emby.Naming.Common;
  8. using Emby.Naming.Video;
  9. using Jellyfin.Extensions;
  10. using MediaBrowser.Controller.Drawing;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Entities.Movies;
  13. using MediaBrowser.Controller.Entities.TV;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Controller.Resolvers;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using Microsoft.Extensions.Logging;
  20. namespace Emby.Server.Implementations.Library.Resolvers.Movies
  21. {
  22. /// <summary>
  23. /// Class MovieResolver.
  24. /// </summary>
  25. public class MovieResolver : BaseVideoResolver<Video>, IMultiItemResolver
  26. {
  27. private readonly IImageProcessor _imageProcessor;
  28. private string[] _validCollectionTypes = new[]
  29. {
  30. CollectionType.Movies,
  31. CollectionType.HomeVideos,
  32. CollectionType.MusicVideos,
  33. CollectionType.TvShows,
  34. CollectionType.Photos
  35. };
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="MovieResolver"/> class.
  38. /// </summary>
  39. /// <param name="imageProcessor">The image processor.</param>
  40. /// <param name="logger">The logger.</param>
  41. /// <param name="namingOptions">The naming options.</param>
  42. /// <param name="directoryService">The directory service.</param>
  43. public MovieResolver(IImageProcessor imageProcessor, ILogger<MovieResolver> logger, NamingOptions namingOptions, IDirectoryService directoryService)
  44. : base(logger, namingOptions, directoryService)
  45. {
  46. _imageProcessor = imageProcessor;
  47. }
  48. /// <summary>
  49. /// Gets the priority.
  50. /// </summary>
  51. /// <value>The priority.</value>
  52. public override ResolverPriority Priority => ResolverPriority.Fourth;
  53. /// <inheritdoc />
  54. public MultiItemResolverResult ResolveMultiple(
  55. Folder parent,
  56. List<FileSystemMetadata> files,
  57. string collectionType,
  58. IDirectoryService directoryService)
  59. {
  60. var result = ResolveMultipleInternal(parent, files, collectionType);
  61. if (result is not null)
  62. {
  63. foreach (var item in result.Items)
  64. {
  65. SetInitialItemValues((Video)item, null);
  66. }
  67. }
  68. return result;
  69. }
  70. /// <summary>
  71. /// Resolves the specified args.
  72. /// </summary>
  73. /// <param name="args">The args.</param>
  74. /// <returns>Video.</returns>
  75. protected override Video Resolve(ItemResolveArgs args)
  76. {
  77. var collectionType = args.GetCollectionType();
  78. // Find movies with their own folders
  79. if (args.IsDirectory)
  80. {
  81. if (IsInvalid(args.Parent, collectionType))
  82. {
  83. return null;
  84. }
  85. Video movie = null;
  86. var files = args.GetActualFileSystemChildren().ToList();
  87. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  88. {
  89. movie = FindMovie<MusicVideo>(args, args.Path, args.Parent, files, DirectoryService, collectionType, false);
  90. }
  91. if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase))
  92. {
  93. movie = FindMovie<Video>(args, args.Path, args.Parent, files, DirectoryService, collectionType, false);
  94. }
  95. if (string.IsNullOrEmpty(collectionType))
  96. {
  97. // Owned items will be caught by the video extra resolver
  98. if (args.Parent is null)
  99. {
  100. return null;
  101. }
  102. if (args.HasParent<Series>())
  103. {
  104. return null;
  105. }
  106. movie = FindMovie<Movie>(args, args.Path, args.Parent, files, DirectoryService, collectionType, true);
  107. }
  108. if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  109. {
  110. movie = FindMovie<Movie>(args, args.Path, args.Parent, files, DirectoryService, collectionType, true);
  111. }
  112. // ignore extras
  113. return movie?.ExtraType is null ? movie : null;
  114. }
  115. if (args.Parent is null)
  116. {
  117. return base.Resolve(args);
  118. }
  119. if (IsInvalid(args.Parent, collectionType))
  120. {
  121. return null;
  122. }
  123. Video item = null;
  124. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  125. {
  126. item = ResolveVideo<MusicVideo>(args, false);
  127. }
  128. // To find a movie file, the collection type must be movies or boxsets
  129. else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  130. {
  131. item = ResolveVideo<Movie>(args, true);
  132. }
  133. else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
  134. string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
  135. {
  136. item = ResolveVideo<Video>(args, false);
  137. }
  138. else if (string.IsNullOrEmpty(collectionType))
  139. {
  140. if (args.HasParent<Series>())
  141. {
  142. return null;
  143. }
  144. item = ResolveVideo<Video>(args, false);
  145. }
  146. // Ignore extras
  147. if (item?.ExtraType is not null)
  148. {
  149. return null;
  150. }
  151. if (item is not null)
  152. {
  153. item.IsInMixedFolder = true;
  154. }
  155. return item;
  156. }
  157. private MultiItemResolverResult ResolveMultipleInternal(
  158. Folder parent,
  159. List<FileSystemMetadata> files,
  160. string collectionType)
  161. {
  162. if (IsInvalid(parent, collectionType))
  163. {
  164. return null;
  165. }
  166. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  167. {
  168. return ResolveVideos<MusicVideo>(parent, files, true, collectionType, false);
  169. }
  170. if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
  171. string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
  172. {
  173. return ResolveVideos<Video>(parent, files, false, collectionType, false);
  174. }
  175. if (string.IsNullOrEmpty(collectionType))
  176. {
  177. // Owned items should just use the plain video type
  178. if (parent is null)
  179. {
  180. return ResolveVideos<Video>(parent, files, false, collectionType, false);
  181. }
  182. if (parent is Series || parent.GetParents().OfType<Series>().Any())
  183. {
  184. return null;
  185. }
  186. return ResolveVideos<Movie>(parent, files, false, collectionType, true);
  187. }
  188. if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  189. {
  190. return ResolveVideos<Movie>(parent, files, true, collectionType, true);
  191. }
  192. if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
  193. {
  194. return ResolveVideos<Episode>(parent, files, false, collectionType, true);
  195. }
  196. return null;
  197. }
  198. private MultiItemResolverResult ResolveVideos<T>(
  199. Folder parent,
  200. IEnumerable<FileSystemMetadata> fileSystemEntries,
  201. bool supportMultiEditions,
  202. string collectionType,
  203. bool parseName)
  204. where T : Video, new()
  205. {
  206. var files = new List<FileSystemMetadata>();
  207. var leftOver = new List<FileSystemMetadata>();
  208. var hasCollectionType = !string.IsNullOrEmpty(collectionType);
  209. // Loop through each child file/folder and see if we find a video
  210. foreach (var child in fileSystemEntries)
  211. {
  212. // This is a hack but currently no better way to resolve a sometimes ambiguous situation
  213. if (!hasCollectionType)
  214. {
  215. if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase)
  216. || string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase))
  217. {
  218. return null;
  219. }
  220. }
  221. if (child.IsDirectory)
  222. {
  223. leftOver.Add(child);
  224. }
  225. else if (!IsIgnored(child.Name))
  226. {
  227. files.Add(child);
  228. }
  229. }
  230. var videoInfos = files
  231. .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, NamingOptions, parseName))
  232. .Where(f => f is not null)
  233. .ToList();
  234. var resolverResult = VideoListResolver.Resolve(videoInfos, NamingOptions, supportMultiEditions, parseName);
  235. var result = new MultiItemResolverResult
  236. {
  237. ExtraFiles = leftOver
  238. };
  239. var isInMixedFolder = resolverResult.Count > 1 || parent?.IsTopParent == true;
  240. foreach (var video in resolverResult)
  241. {
  242. var firstVideo = video.Files[0];
  243. var path = firstVideo.Path;
  244. if (video.ExtraType is not null)
  245. {
  246. result.ExtraFiles.Add(files.Find(f => string.Equals(f.FullName, path, StringComparison.OrdinalIgnoreCase)));
  247. continue;
  248. }
  249. var additionalParts = video.Files.Count > 1 ? video.Files.Skip(1).Select(i => i.Path).ToArray() : Array.Empty<string>();
  250. var videoItem = new T
  251. {
  252. Path = path,
  253. IsInMixedFolder = isInMixedFolder,
  254. ProductionYear = video.Year,
  255. Name = parseName ? video.Name : firstVideo.Name,
  256. AdditionalParts = additionalParts,
  257. LocalAlternateVersions = video.AlternateVersions.Select(i => i.Path).ToArray()
  258. };
  259. SetVideoType(videoItem, firstVideo);
  260. Set3DFormat(videoItem, firstVideo);
  261. result.Items.Add(videoItem);
  262. }
  263. result.ExtraFiles.AddRange(files.Where(i => !ContainsFile(resolverResult, i)));
  264. return result;
  265. }
  266. private static bool IsIgnored(ReadOnlySpan<char> filename)
  267. => Regex.IsMatch(filename, @"\bsample\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  268. private static bool ContainsFile(IReadOnlyList<VideoInfo> result, FileSystemMetadata file)
  269. {
  270. for (var i = 0; i < result.Count; i++)
  271. {
  272. var current = result[i];
  273. for (var j = 0; j < current.Files.Count; j++)
  274. {
  275. if (ContainsFile(current.Files[j], file))
  276. {
  277. return true;
  278. }
  279. }
  280. for (var j = 0; j < current.AlternateVersions.Count; j++)
  281. {
  282. if (ContainsFile(current.AlternateVersions[j], file))
  283. {
  284. return true;
  285. }
  286. }
  287. }
  288. return false;
  289. }
  290. private static bool ContainsFile(VideoFileInfo result, FileSystemMetadata file)
  291. {
  292. return string.Equals(result.Path, file.FullName, StringComparison.OrdinalIgnoreCase);
  293. }
  294. /// <summary>
  295. /// Sets the initial item values.
  296. /// </summary>
  297. /// <param name="item">The item.</param>
  298. /// <param name="args">The args.</param>
  299. protected override void SetInitialItemValues(Video item, ItemResolveArgs args)
  300. {
  301. base.SetInitialItemValues(item, args);
  302. SetProviderIdsFromPath(item);
  303. }
  304. /// <summary>
  305. /// Sets the provider id from path.
  306. /// </summary>
  307. /// <param name="item">The item.</param>
  308. private static void SetProviderIdsFromPath(Video item)
  309. {
  310. if (item is Movie || item is MusicVideo)
  311. {
  312. // We need to only look at the name of this actual item (not parents)
  313. var justName = item.IsInMixedFolder ? Path.GetFileName(item.Path.AsSpan()) : Path.GetFileName(item.ContainingFolderPath.AsSpan());
  314. if (!justName.IsEmpty)
  315. {
  316. // Check for TMDb id
  317. var tmdbid = justName.GetAttributeValue("tmdbid");
  318. if (!string.IsNullOrWhiteSpace(tmdbid))
  319. {
  320. item.SetProviderId(MetadataProvider.Tmdb, tmdbid);
  321. }
  322. }
  323. if (!string.IsNullOrEmpty(item.Path))
  324. {
  325. // Check for IMDb id - we use full media path, as we can assume that this will match in any use case (whether id in parent dir or in file name)
  326. var imdbid = item.Path.AsSpan().GetAttributeValue("imdbid");
  327. if (!string.IsNullOrWhiteSpace(imdbid))
  328. {
  329. item.SetProviderId(MetadataProvider.Imdb, imdbid);
  330. }
  331. }
  332. }
  333. }
  334. /// <summary>
  335. /// Finds a movie based on a child file system entries.
  336. /// </summary>
  337. /// <returns>Movie.</returns>
  338. private T FindMovie<T>(ItemResolveArgs args, string path, Folder parent, List<FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool parseName)
  339. where T : Video, new()
  340. {
  341. var multiDiscFolders = new List<FileSystemMetadata>();
  342. var libraryOptions = args.LibraryOptions;
  343. var supportPhotos = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && libraryOptions.EnablePhotos;
  344. var photos = new List<FileSystemMetadata>();
  345. // Search for a folder rip
  346. foreach (var child in fileSystemEntries)
  347. {
  348. var filename = child.Name;
  349. if (child.IsDirectory)
  350. {
  351. if (IsDvdDirectory(child.FullName, filename, directoryService))
  352. {
  353. var movie = new T
  354. {
  355. Path = path,
  356. VideoType = VideoType.Dvd
  357. };
  358. Set3DFormat(movie);
  359. return movie;
  360. }
  361. if (IsBluRayDirectory(filename))
  362. {
  363. var movie = new T
  364. {
  365. Path = path,
  366. VideoType = VideoType.BluRay
  367. };
  368. Set3DFormat(movie);
  369. return movie;
  370. }
  371. multiDiscFolders.Add(child);
  372. }
  373. else if (IsDvdFile(filename))
  374. {
  375. var movie = new T
  376. {
  377. Path = path,
  378. VideoType = VideoType.Dvd
  379. };
  380. Set3DFormat(movie);
  381. return movie;
  382. }
  383. else if (supportPhotos && PhotoResolver.IsImageFile(child.FullName, _imageProcessor))
  384. {
  385. photos.Add(child);
  386. }
  387. }
  388. // TODO: Allow GetMultiDiscMovie in here
  389. const bool SupportsMultiVersion = true;
  390. var result = ResolveVideos<T>(parent, fileSystemEntries, SupportsMultiVersion, collectionType, parseName) ??
  391. new MultiItemResolverResult();
  392. var isPhotosCollection = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)
  393. || string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase);
  394. if (!isPhotosCollection && result.Items.Count == 1)
  395. {
  396. var videoPath = result.Items[0].Path;
  397. var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(videoPath, i.Name));
  398. if (!hasPhotos)
  399. {
  400. var movie = (T)result.Items[0];
  401. movie.IsInMixedFolder = false;
  402. movie.Name = Path.GetFileName(movie.ContainingFolderPath);
  403. return movie;
  404. }
  405. }
  406. else if (result.Items.Count == 0 && multiDiscFolders.Count > 0)
  407. {
  408. return GetMultiDiscMovie<T>(multiDiscFolders, directoryService);
  409. }
  410. return null;
  411. }
  412. /// <summary>
  413. /// Gets the multi disc movie.
  414. /// </summary>
  415. /// <param name="multiDiscFolders">The folders.</param>
  416. /// <param name="directoryService">The directory service.</param>
  417. /// <returns>``0.</returns>
  418. private T GetMultiDiscMovie<T>(List<FileSystemMetadata> multiDiscFolders, IDirectoryService directoryService)
  419. where T : Video, new()
  420. {
  421. var videoTypes = new List<VideoType>();
  422. var folderPaths = multiDiscFolders.Select(i => i.FullName).Where(i =>
  423. {
  424. var subFileEntries = directoryService.GetFileSystemEntries(i);
  425. var subfolders = subFileEntries
  426. .Where(e => e.IsDirectory)
  427. .ToList();
  428. if (subfolders.Any(s => IsDvdDirectory(s.FullName, s.Name, directoryService)))
  429. {
  430. videoTypes.Add(VideoType.Dvd);
  431. return true;
  432. }
  433. if (subfolders.Any(s => IsBluRayDirectory(s.Name)))
  434. {
  435. videoTypes.Add(VideoType.BluRay);
  436. return true;
  437. }
  438. var subFiles = subFileEntries
  439. .Where(e => !e.IsDirectory)
  440. .Select(d => d.Name);
  441. if (subFiles.Any(IsDvdFile))
  442. {
  443. videoTypes.Add(VideoType.Dvd);
  444. return true;
  445. }
  446. return false;
  447. }).Order().ToList();
  448. // If different video types were found, don't allow this
  449. if (videoTypes.Distinct().Count() > 1)
  450. {
  451. return null;
  452. }
  453. if (folderPaths.Count == 0)
  454. {
  455. return null;
  456. }
  457. var result = StackResolver.ResolveDirectories(folderPaths, NamingOptions).ToList();
  458. if (result.Count != 1)
  459. {
  460. return null;
  461. }
  462. int additionalPartsLen = folderPaths.Count - 1;
  463. var additionalParts = new string[additionalPartsLen];
  464. folderPaths.CopyTo(1, additionalParts, 0, additionalPartsLen);
  465. var returnVideo = new T
  466. {
  467. Path = folderPaths[0],
  468. AdditionalParts = additionalParts,
  469. VideoType = videoTypes[0],
  470. Name = result[0].Name
  471. };
  472. SetIsoType(returnVideo);
  473. return returnVideo;
  474. }
  475. private bool IsInvalid(Folder parent, ReadOnlySpan<char> collectionType)
  476. {
  477. if (parent is not null)
  478. {
  479. if (parent.IsRoot)
  480. {
  481. return true;
  482. }
  483. }
  484. if (collectionType.IsEmpty)
  485. {
  486. return false;
  487. }
  488. return !_validCollectionTypes.Contains(collectionType, StringComparison.OrdinalIgnoreCase);
  489. }
  490. }
  491. }