MovieResolver.cs 19 KB

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