2
0

MovieResolver.cs 20 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 partial 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. [GeneratedRegex(@"\bsample\b", RegexOptions.IgnoreCase)]
  54. private static partial Regex IsIgnoredRegex();
  55. /// <inheritdoc />
  56. public MultiItemResolverResult ResolveMultiple(
  57. Folder parent,
  58. List<FileSystemMetadata> files,
  59. string collectionType,
  60. IDirectoryService directoryService)
  61. {
  62. var result = ResolveMultipleInternal(parent, files, collectionType);
  63. if (result is not null)
  64. {
  65. foreach (var item in result.Items)
  66. {
  67. SetInitialItemValues((Video)item, null);
  68. }
  69. }
  70. return result;
  71. }
  72. /// <summary>
  73. /// Resolves the specified args.
  74. /// </summary>
  75. /// <param name="args">The args.</param>
  76. /// <returns>Video.</returns>
  77. protected override Video Resolve(ItemResolveArgs args)
  78. {
  79. var collectionType = args.GetCollectionType();
  80. // Find movies with their own folders
  81. if (args.IsDirectory)
  82. {
  83. if (IsInvalid(args.Parent, collectionType))
  84. {
  85. return null;
  86. }
  87. Video movie = null;
  88. var files = args.GetActualFileSystemChildren().ToList();
  89. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  90. {
  91. movie = FindMovie<MusicVideo>(args, args.Path, args.Parent, files, DirectoryService, collectionType, false);
  92. }
  93. if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase))
  94. {
  95. movie = FindMovie<Video>(args, args.Path, args.Parent, files, DirectoryService, collectionType, false);
  96. }
  97. if (string.IsNullOrEmpty(collectionType))
  98. {
  99. // Owned items will be caught by the video extra resolver
  100. if (args.Parent is null)
  101. {
  102. return null;
  103. }
  104. if (args.HasParent<Series>())
  105. {
  106. return null;
  107. }
  108. movie = FindMovie<Movie>(args, args.Path, args.Parent, files, DirectoryService, collectionType, true);
  109. }
  110. if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  111. {
  112. movie = FindMovie<Movie>(args, args.Path, args.Parent, files, DirectoryService, collectionType, true);
  113. }
  114. // ignore extras
  115. return movie?.ExtraType is null ? movie : null;
  116. }
  117. if (args.Parent is null)
  118. {
  119. return base.Resolve(args);
  120. }
  121. if (IsInvalid(args.Parent, collectionType))
  122. {
  123. return null;
  124. }
  125. Video item = null;
  126. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  127. {
  128. item = ResolveVideo<MusicVideo>(args, false);
  129. }
  130. // To find a movie file, the collection type must be movies or boxsets
  131. else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  132. {
  133. item = ResolveVideo<Movie>(args, true);
  134. }
  135. else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
  136. string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
  137. {
  138. item = ResolveVideo<Video>(args, false);
  139. }
  140. else if (string.IsNullOrEmpty(collectionType))
  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. string collectionType)
  163. {
  164. if (IsInvalid(parent, collectionType))
  165. {
  166. return null;
  167. }
  168. if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase))
  169. {
  170. return ResolveVideos<MusicVideo>(parent, files, true, collectionType, false);
  171. }
  172. if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) ||
  173. string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase))
  174. {
  175. return ResolveVideos<Video>(parent, files, false, collectionType, false);
  176. }
  177. if (string.IsNullOrEmpty(collectionType))
  178. {
  179. // Owned items should just use the plain video type
  180. if (parent is null)
  181. {
  182. return ResolveVideos<Video>(parent, files, false, collectionType, false);
  183. }
  184. if (parent is Series || parent.GetParents().OfType<Series>().Any())
  185. {
  186. return null;
  187. }
  188. return ResolveVideos<Movie>(parent, files, false, collectionType, true);
  189. }
  190. if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase))
  191. {
  192. return ResolveVideos<Movie>(parent, files, true, collectionType, true);
  193. }
  194. if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
  195. {
  196. return ResolveVideos<Episode>(parent, files, false, collectionType, true);
  197. }
  198. return null;
  199. }
  200. private MultiItemResolverResult ResolveVideos<T>(
  201. Folder parent,
  202. IEnumerable<FileSystemMetadata> fileSystemEntries,
  203. bool supportMultiEditions,
  204. string collectionType,
  205. bool parseName)
  206. where T : Video, new()
  207. {
  208. var files = new List<FileSystemMetadata>();
  209. var leftOver = new List<FileSystemMetadata>();
  210. var hasCollectionType = !string.IsNullOrEmpty(collectionType);
  211. // Loop through each child file/folder and see if we find a video
  212. foreach (var child in fileSystemEntries)
  213. {
  214. // This is a hack but currently no better way to resolve a sometimes ambiguous situation
  215. if (!hasCollectionType)
  216. {
  217. if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase)
  218. || string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase))
  219. {
  220. return null;
  221. }
  222. }
  223. if (child.IsDirectory)
  224. {
  225. leftOver.Add(child);
  226. }
  227. else if (!IsIgnoredRegex().IsMatch(child.Name))
  228. {
  229. files.Add(child);
  230. }
  231. }
  232. var videoInfos = files
  233. .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, NamingOptions, parseName))
  234. .Where(f => f is not null)
  235. .ToList();
  236. var resolverResult = VideoListResolver.Resolve(videoInfos, NamingOptions, supportMultiEditions, parseName);
  237. var result = new MultiItemResolverResult
  238. {
  239. ExtraFiles = leftOver
  240. };
  241. var isInMixedFolder = resolverResult.Count > 1 || parent?.IsTopParent == true;
  242. foreach (var video in resolverResult)
  243. {
  244. var firstVideo = video.Files[0];
  245. var path = firstVideo.Path;
  246. if (video.ExtraType is not null)
  247. {
  248. result.ExtraFiles.Add(files.Find(f => string.Equals(f.FullName, path, StringComparison.OrdinalIgnoreCase)));
  249. continue;
  250. }
  251. var additionalParts = video.Files.Count > 1 ? video.Files.Skip(1).Select(i => i.Path).ToArray() : Array.Empty<string>();
  252. var videoItem = new T
  253. {
  254. Path = path,
  255. IsInMixedFolder = isInMixedFolder,
  256. ProductionYear = video.Year,
  257. Name = parseName ? video.Name : firstVideo.Name,
  258. AdditionalParts = additionalParts,
  259. LocalAlternateVersions = video.AlternateVersions.Select(i => i.Path).ToArray()
  260. };
  261. SetVideoType(videoItem, firstVideo);
  262. Set3DFormat(videoItem, firstVideo);
  263. result.Items.Add(videoItem);
  264. }
  265. result.ExtraFiles.AddRange(files.Where(i => !ContainsFile(resolverResult, i)));
  266. return result;
  267. }
  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. }