MovieResolver.cs 20 KB

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