Video.cs 17 KB

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