MovieResolver.cs 20 KB

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