Video.cs 17 KB

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