Video.cs 18 KB

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