MovieResolver.cs 20 KB

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