Video.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using MediaBrowser.Controller.Library;
  2. using MediaBrowser.Controller.Persistence;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Controller.Resolvers;
  5. using MediaBrowser.Model.Entities;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.Serialization;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.Entities
  15. {
  16. /// <summary>
  17. /// Class Video
  18. /// </summary>
  19. public class Video : BaseItem, IHasMediaStreams, IHasAspectRatio, IHasTags, ISupportsPlaceHolders
  20. {
  21. public bool IsMultiPart { get; set; }
  22. public bool HasLocalAlternateVersions { get; set; }
  23. public Guid? PrimaryVersionId { get; set; }
  24. public List<Guid> AdditionalPartIds { get; set; }
  25. public List<Guid> LocalAlternateVersionIds { get; set; }
  26. public Video()
  27. {
  28. PlayableStreamFileNames = new List<string>();
  29. AdditionalPartIds = new List<Guid>();
  30. LocalAlternateVersionIds = new List<Guid>();
  31. Tags = new List<string>();
  32. SubtitleFiles = new List<string>();
  33. LinkedAlternateVersions = new List<LinkedChild>();
  34. }
  35. [IgnoreDataMember]
  36. public int MediaSourceCount
  37. {
  38. get
  39. {
  40. return LinkedAlternateVersions.Count + LocalAlternateVersionIds.Count + 1;
  41. }
  42. }
  43. public List<LinkedChild> LinkedAlternateVersions { get; set; }
  44. /// <summary>
  45. /// Gets the linked children.
  46. /// </summary>
  47. /// <returns>IEnumerable{BaseItem}.</returns>
  48. public IEnumerable<Video> GetAlternateVersions()
  49. {
  50. var filesWithinSameDirectory = LocalAlternateVersionIds
  51. .Select(i => LibraryManager.GetItemById(i))
  52. .Where(i => i != null)
  53. .OfType<Video>();
  54. return filesWithinSameDirectory.Concat(GetLinkedAlternateVersions())
  55. .OrderBy(i => i.SortName);
  56. }
  57. public IEnumerable<Video> GetLinkedAlternateVersions()
  58. {
  59. var linkedVersions = LinkedAlternateVersions
  60. .Select(GetLinkedChild)
  61. .Where(i => i != null)
  62. .OfType<Video>();
  63. return linkedVersions
  64. .OrderBy(i => i.SortName);
  65. }
  66. /// <summary>
  67. /// Gets the additional parts.
  68. /// </summary>
  69. /// <returns>IEnumerable{Video}.</returns>
  70. public IEnumerable<Video> GetAdditionalParts()
  71. {
  72. return AdditionalPartIds
  73. .Select(i => LibraryManager.GetItemById(i))
  74. .Where(i => i != null)
  75. .OfType<Video>()
  76. .OrderBy(i => i.SortName);
  77. }
  78. /// <summary>
  79. /// Gets or sets the subtitle paths.
  80. /// </summary>
  81. /// <value>The subtitle paths.</value>
  82. public List<string> SubtitleFiles { get; set; }
  83. /// <summary>
  84. /// Gets or sets a value indicating whether this instance has subtitles.
  85. /// </summary>
  86. /// <value><c>true</c> if this instance has subtitles; otherwise, <c>false</c>.</value>
  87. public bool HasSubtitles { get; set; }
  88. public bool IsPlaceHolder { get; set; }
  89. /// <summary>
  90. /// Gets or sets the tags.
  91. /// </summary>
  92. /// <value>The tags.</value>
  93. public List<string> Tags { get; set; }
  94. /// <summary>
  95. /// Gets or sets the video bit rate.
  96. /// </summary>
  97. /// <value>The video bit rate.</value>
  98. public int? VideoBitRate { get; set; }
  99. /// <summary>
  100. /// Gets or sets the default index of the video stream.
  101. /// </summary>
  102. /// <value>The default index of the video stream.</value>
  103. public int? DefaultVideoStreamIndex { get; set; }
  104. /// <summary>
  105. /// Gets or sets the type of the video.
  106. /// </summary>
  107. /// <value>The type of the video.</value>
  108. public VideoType VideoType { get; set; }
  109. /// <summary>
  110. /// Gets or sets the type of the iso.
  111. /// </summary>
  112. /// <value>The type of the iso.</value>
  113. public IsoType? IsoType { get; set; }
  114. /// <summary>
  115. /// Gets or sets the video3 D format.
  116. /// </summary>
  117. /// <value>The video3 D format.</value>
  118. public Video3DFormat? Video3DFormat { get; set; }
  119. /// <summary>
  120. /// If the video is a folder-rip, this will hold the file list for the largest playlist
  121. /// </summary>
  122. public List<string> PlayableStreamFileNames { get; set; }
  123. /// <summary>
  124. /// Gets the playable stream files.
  125. /// </summary>
  126. /// <returns>List{System.String}.</returns>
  127. public List<string> GetPlayableStreamFiles()
  128. {
  129. return GetPlayableStreamFiles(Path);
  130. }
  131. /// <summary>
  132. /// Gets or sets the aspect ratio.
  133. /// </summary>
  134. /// <value>The aspect ratio.</value>
  135. public string AspectRatio { get; set; }
  136. [IgnoreDataMember]
  137. public override string ContainingFolderPath
  138. {
  139. get
  140. {
  141. if (IsMultiPart)
  142. {
  143. return System.IO.Path.GetDirectoryName(Path);
  144. }
  145. if (!IsPlaceHolder)
  146. {
  147. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd ||
  148. VideoType == VideoType.HdDvd)
  149. {
  150. return Path;
  151. }
  152. }
  153. return base.ContainingFolderPath;
  154. }
  155. }
  156. public string MainFeaturePlaylistName { get; set; }
  157. /// <summary>
  158. /// Gets the playable stream files.
  159. /// </summary>
  160. /// <param name="rootPath">The root path.</param>
  161. /// <returns>List{System.String}.</returns>
  162. public List<string> GetPlayableStreamFiles(string rootPath)
  163. {
  164. var allFiles = Directory.EnumerateFiles(rootPath, "*", SearchOption.AllDirectories).ToList();
  165. return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  166. .Where(f => !string.IsNullOrEmpty(f))
  167. .ToList();
  168. }
  169. /// <summary>
  170. /// Gets a value indicating whether [is3 D].
  171. /// </summary>
  172. /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
  173. [IgnoreDataMember]
  174. public bool Is3D
  175. {
  176. get { return Video3DFormat.HasValue; }
  177. }
  178. public bool IsHD { get; set; }
  179. /// <summary>
  180. /// Gets the type of the media.
  181. /// </summary>
  182. /// <value>The type of the media.</value>
  183. public override string MediaType
  184. {
  185. get
  186. {
  187. return Model.Entities.MediaType.Video;
  188. }
  189. }
  190. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  191. {
  192. var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  193. // Must have a parent to have additional parts or alternate versions
  194. // In other words, it must be part of the Parent/Child tree
  195. // The additional parts won't have additional parts themselves
  196. if (LocationType == LocationType.FileSystem && Parent != null)
  197. {
  198. if (IsMultiPart)
  199. {
  200. var additionalPartsChanged = await RefreshAdditionalParts(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  201. if (additionalPartsChanged)
  202. {
  203. hasChanges = true;
  204. }
  205. }
  206. else
  207. {
  208. RefreshLinkedAlternateVersions();
  209. var additionalPartsChanged = await RefreshAlternateVersionsWithinSameDirectory(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  210. if (additionalPartsChanged)
  211. {
  212. hasChanges = true;
  213. }
  214. }
  215. }
  216. return hasChanges;
  217. }
  218. private bool RefreshLinkedAlternateVersions()
  219. {
  220. foreach (var child in LinkedAlternateVersions)
  221. {
  222. // Reset the cached value
  223. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  224. {
  225. child.ItemId = null;
  226. }
  227. }
  228. return false;
  229. }
  230. /// <summary>
  231. /// Refreshes the additional parts.
  232. /// </summary>
  233. /// <param name="options">The options.</param>
  234. /// <param name="fileSystemChildren">The file system children.</param>
  235. /// <param name="cancellationToken">The cancellation token.</param>
  236. /// <returns>Task{System.Boolean}.</returns>
  237. private async Task<bool> RefreshAdditionalParts(MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  238. {
  239. var newItems = LoadAdditionalParts(fileSystemChildren, options.DirectoryService).ToList();
  240. var newItemIds = newItems.Select(i => i.Id).ToList();
  241. var itemsChanged = !AdditionalPartIds.SequenceEqual(newItemIds);
  242. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  243. await Task.WhenAll(tasks).ConfigureAwait(false);
  244. AdditionalPartIds = newItemIds;
  245. return itemsChanged;
  246. }
  247. /// <summary>
  248. /// Loads the additional parts.
  249. /// </summary>
  250. /// <returns>IEnumerable{Video}.</returns>
  251. private IEnumerable<Video> LoadAdditionalParts(IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  252. {
  253. IEnumerable<FileSystemInfo> files;
  254. var path = Path;
  255. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
  256. {
  257. files = fileSystemChildren.Where(i =>
  258. {
  259. if ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  260. {
  261. return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsMultiPartFolder(i.FullName) && EntityResolutionHelper.IsMultiPartFile(i.Name);
  262. }
  263. return false;
  264. });
  265. }
  266. else
  267. {
  268. files = fileSystemChildren.Where(i =>
  269. {
  270. if ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  271. {
  272. return false;
  273. }
  274. return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsVideoFile(i.FullName) && EntityResolutionHelper.IsMultiPartFile(i.Name);
  275. });
  276. }
  277. return LibraryManager.ResolvePaths<Video>(files, directoryService, null).Select(video =>
  278. {
  279. // Try to retrieve it from the db. If we don't find it, use the resolved version
  280. var dbItem = LibraryManager.GetItemById(video.Id) as Video;
  281. if (dbItem != null)
  282. {
  283. video = dbItem;
  284. }
  285. return video;
  286. // Sort them so that the list can be easily compared for changes
  287. }).OrderBy(i => i.Path).ToList();
  288. }
  289. private async Task<bool> RefreshAlternateVersionsWithinSameDirectory(MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  290. {
  291. var newItems = HasLocalAlternateVersions ?
  292. LoadAlternateVersionsWithinSameDirectory(fileSystemChildren, options.DirectoryService).ToList() :
  293. new List<Video>();
  294. var newItemIds = newItems.Select(i => i.Id).ToList();
  295. var itemsChanged = !LocalAlternateVersionIds.SequenceEqual(newItemIds);
  296. var tasks = newItems.Select(i => RefreshAlternateVersion(options, i, cancellationToken));
  297. await Task.WhenAll(tasks).ConfigureAwait(false);
  298. LocalAlternateVersionIds = newItemIds;
  299. return itemsChanged;
  300. }
  301. private Task RefreshAlternateVersion(MetadataRefreshOptions options, Video video, CancellationToken cancellationToken)
  302. {
  303. var currentImagePath = video.GetImagePath(ImageType.Primary);
  304. var ownerImagePath = this.GetImagePath(ImageType.Primary);
  305. var newOptions = new MetadataRefreshOptions
  306. {
  307. DirectoryService = options.DirectoryService,
  308. ImageRefreshMode = options.ImageRefreshMode,
  309. MetadataRefreshMode = options.MetadataRefreshMode,
  310. ReplaceAllMetadata = options.ReplaceAllMetadata
  311. };
  312. if (!string.Equals(currentImagePath, ownerImagePath, StringComparison.OrdinalIgnoreCase))
  313. {
  314. newOptions.ForceSave = true;
  315. if (string.IsNullOrWhiteSpace(ownerImagePath))
  316. {
  317. video.ImageInfos.Clear();
  318. }
  319. else
  320. {
  321. video.SetImagePath(ImageType.Primary, ownerImagePath);
  322. }
  323. }
  324. return video.RefreshMetadata(newOptions, cancellationToken);
  325. }
  326. public override async Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  327. {
  328. await base.UpdateToRepository(updateReason, cancellationToken).ConfigureAwait(false);
  329. foreach (var item in LocalAlternateVersionIds.Select(i => LibraryManager.GetItemById(i)))
  330. {
  331. item.ImageInfos = ImageInfos;
  332. item.Overview = Overview;
  333. item.ProductionYear = ProductionYear;
  334. item.PremiereDate = PremiereDate;
  335. item.CommunityRating = CommunityRating;
  336. item.OfficialRating = OfficialRating;
  337. item.Genres = Genres;
  338. item.ProviderIds = ProviderIds;
  339. await item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  340. }
  341. }
  342. /// <summary>
  343. /// Loads the additional parts.
  344. /// </summary>
  345. /// <returns>IEnumerable{Video}.</returns>
  346. private IEnumerable<Video> LoadAlternateVersionsWithinSameDirectory(IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  347. {
  348. IEnumerable<FileSystemInfo> files;
  349. // Only support this for video files. For folder rips, they'll have to use the linking feature
  350. if (VideoType == VideoType.VideoFile || VideoType == VideoType.Iso)
  351. {
  352. var path = Path;
  353. var filenamePrefix = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(path));
  354. files = fileSystemChildren.Where(i =>
  355. {
  356. if ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  357. {
  358. return false;
  359. }
  360. return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) &&
  361. EntityResolutionHelper.IsVideoFile(i.FullName) &&
  362. i.Name.StartsWith(filenamePrefix + " - ", StringComparison.OrdinalIgnoreCase);
  363. });
  364. }
  365. else
  366. {
  367. files = new List<FileSystemInfo>();
  368. }
  369. return LibraryManager.ResolvePaths<Video>(files, directoryService, null).Select(video =>
  370. {
  371. // Try to retrieve it from the db. If we don't find it, use the resolved version
  372. var dbItem = LibraryManager.GetItemById(video.Id) as Video;
  373. if (dbItem != null)
  374. {
  375. video = dbItem;
  376. }
  377. video.PrimaryVersionId = Id;
  378. return video;
  379. // Sort them so that the list can be easily compared for changes
  380. }).OrderBy(i => i.Path).ToList();
  381. }
  382. public override IEnumerable<string> GetDeletePaths()
  383. {
  384. if (!IsInMixedFolder)
  385. {
  386. return new[] { ContainingFolderPath };
  387. }
  388. return base.GetDeletePaths();
  389. }
  390. public virtual IEnumerable<MediaStream> GetMediaStreams()
  391. {
  392. return ItemRepository.GetMediaStreams(new MediaStreamQuery
  393. {
  394. ItemId = Id
  395. });
  396. }
  397. public virtual MediaStream GetDefaultVideoStream()
  398. {
  399. if (!DefaultVideoStreamIndex.HasValue)
  400. {
  401. return null;
  402. }
  403. return ItemRepository.GetMediaStreams(new MediaStreamQuery
  404. {
  405. ItemId = Id,
  406. Index = DefaultVideoStreamIndex.Value
  407. }).FirstOrDefault();
  408. }
  409. }
  410. }