Video.cs 18 KB

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