MovieResolver.cs 20 KB

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