Series.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. using MediaBrowser.Controller.Providers;
  2. using MediaBrowser.Model.Configuration;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Querying;
  5. using MediaBrowser.Model.Users;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Runtime.Serialization;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Model.Providers;
  13. using MoreLinq;
  14. namespace MediaBrowser.Controller.Entities.TV
  15. {
  16. /// <summary>
  17. /// Class Series
  18. /// </summary>
  19. public class Series : Folder, IHasTrailers, IHasDisplayOrder, IHasLookupInfo<SeriesInfo>, IHasSpecialFeatures, IMetadataContainer, IHasOriginalTitle
  20. {
  21. public List<Guid> SpecialFeatureIds { get; set; }
  22. public int? AnimeSeriesIndex { get; set; }
  23. public Series()
  24. {
  25. AirDays = new List<DayOfWeek>();
  26. SpecialFeatureIds = new List<Guid>();
  27. RemoteTrailers = new List<MediaUrl>();
  28. LocalTrailerIds = new List<Guid>();
  29. RemoteTrailerIds = new List<Guid>();
  30. DisplaySpecialsWithSeasons = true;
  31. }
  32. [IgnoreDataMember]
  33. public override bool SupportsAddingToPlaylist
  34. {
  35. get { return true; }
  36. }
  37. [IgnoreDataMember]
  38. public override bool IsPreSorted
  39. {
  40. get
  41. {
  42. return true;
  43. }
  44. }
  45. [IgnoreDataMember]
  46. public override bool SupportsDateLastMediaAdded
  47. {
  48. get
  49. {
  50. return true;
  51. }
  52. }
  53. public bool DisplaySpecialsWithSeasons { get; set; }
  54. public List<Guid> LocalTrailerIds { get; set; }
  55. public List<Guid> RemoteTrailerIds { get; set; }
  56. public List<MediaUrl> RemoteTrailers { get; set; }
  57. /// <summary>
  58. /// airdate, dvd or absolute
  59. /// </summary>
  60. public string DisplayOrder { get; set; }
  61. /// <summary>
  62. /// Gets or sets the status.
  63. /// </summary>
  64. /// <value>The status.</value>
  65. public SeriesStatus? Status { get; set; }
  66. /// <summary>
  67. /// Gets or sets the air days.
  68. /// </summary>
  69. /// <value>The air days.</value>
  70. public List<DayOfWeek> AirDays { get; set; }
  71. /// <summary>
  72. /// Gets or sets the air time.
  73. /// </summary>
  74. /// <value>The air time.</value>
  75. public string AirTime { get; set; }
  76. /// <summary>
  77. /// Gets or sets the date last episode added.
  78. /// </summary>
  79. /// <value>The date last episode added.</value>
  80. [IgnoreDataMember]
  81. public DateTime DateLastEpisodeAdded
  82. {
  83. get
  84. {
  85. return GetRecursiveChildren(i => i is Episode)
  86. .Select(i => i.DateCreated)
  87. .OrderByDescending(i => i)
  88. .FirstOrDefault();
  89. }
  90. }
  91. [IgnoreDataMember]
  92. public override string PresentationUniqueKey
  93. {
  94. get
  95. {
  96. if (EnablePooling())
  97. {
  98. return GetUserDataKeys().First();
  99. }
  100. return base.PresentationUniqueKey;
  101. }
  102. }
  103. /// <summary>
  104. /// Gets the user data key.
  105. /// </summary>
  106. /// <returns>System.String.</returns>
  107. public override List<string> GetUserDataKeys()
  108. {
  109. var list = base.GetUserDataKeys();
  110. var key = this.GetProviderId(MetadataProviders.Imdb);
  111. if (!string.IsNullOrWhiteSpace(key))
  112. {
  113. list.Insert(0, key);
  114. }
  115. key = this.GetProviderId(MetadataProviders.Tvdb);
  116. if (!string.IsNullOrWhiteSpace(key))
  117. {
  118. list.Insert(0, key);
  119. }
  120. return list;
  121. }
  122. /// <summary>
  123. /// Gets the trailer ids.
  124. /// </summary>
  125. /// <returns>List&lt;Guid&gt;.</returns>
  126. public List<Guid> GetTrailerIds()
  127. {
  128. var list = LocalTrailerIds.ToList();
  129. list.AddRange(RemoteTrailerIds);
  130. return list;
  131. }
  132. // Studio, Genre and Rating will all be the same so makes no sense to index by these
  133. protected override IEnumerable<string> GetIndexByOptions()
  134. {
  135. return new List<string> {
  136. {"None"},
  137. {"Performer"},
  138. {"Director"},
  139. {"Year"},
  140. };
  141. }
  142. [IgnoreDataMember]
  143. public bool ContainsEpisodesWithoutSeasonFolders
  144. {
  145. get
  146. {
  147. return Children.OfType<Video>().Any();
  148. }
  149. }
  150. public override IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  151. {
  152. return GetSeasons(user);
  153. }
  154. public IEnumerable<Season> GetSeasons(User user)
  155. {
  156. var config = user.Configuration;
  157. return GetSeasons(user, config.DisplayMissingEpisodes, config.DisplayUnairedEpisodes);
  158. }
  159. protected override Task<QueryResult<BaseItem>> GetItemsInternal(InternalItemsQuery query)
  160. {
  161. var user = query.User;
  162. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  163. IEnumerable<BaseItem> items;
  164. if (query.User == null)
  165. {
  166. items = query.Recursive
  167. ? GetRecursiveChildren(filter)
  168. : Children.Where(filter);
  169. }
  170. else
  171. {
  172. items = query.Recursive
  173. ? GetSeasons(user).Cast<BaseItem>().Concat(GetEpisodes(user)).Where(filter)
  174. : GetSeasons(user).Where(filter);
  175. }
  176. var result = PostFilterAndSort(items, query);
  177. return Task.FromResult(result);
  178. }
  179. public IEnumerable<Season> GetSeasons(User user, bool includeMissingSeasons, bool includeVirtualUnaired)
  180. {
  181. IEnumerable<Season> seasons;
  182. if (EnablePooling())
  183. {
  184. var seriesIds = LibraryManager.GetItemIds(new InternalItemsQuery(user)
  185. {
  186. PresentationUniqueKey = PresentationUniqueKey,
  187. IncludeItemTypes = new[] { typeof(Series).Name }
  188. });
  189. if (seriesIds.Count > 1)
  190. {
  191. seasons = LibraryManager.GetItemList(new InternalItemsQuery(user)
  192. {
  193. AncestorIds = seriesIds.Select(i => i.ToString("N")).ToArray(),
  194. IncludeItemTypes = new[] { typeof(Season).Name },
  195. SortBy = new[] { ItemSortBy.SortName }
  196. }).Cast<Season>();
  197. }
  198. else
  199. {
  200. seasons = LibraryManager.Sort(base.GetChildren(user, true), user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).OfType<Season>();
  201. }
  202. }
  203. else
  204. {
  205. seasons = LibraryManager.Sort(base.GetChildren(user, true), user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).OfType<Season>();
  206. }
  207. if (!includeMissingSeasons)
  208. {
  209. seasons = seasons.Where(i => !(i.IsMissingSeason));
  210. }
  211. if (!includeVirtualUnaired)
  212. {
  213. seasons = seasons.Where(i => !i.IsVirtualUnaired);
  214. }
  215. return seasons;
  216. }
  217. public IEnumerable<Episode> GetEpisodes(User user)
  218. {
  219. var config = user.Configuration;
  220. return GetEpisodes(user, config.DisplayMissingEpisodes, config.DisplayUnairedEpisodes);
  221. }
  222. public IEnumerable<Episode> GetEpisodes(User user, bool includeMissing, bool includeVirtualUnaired)
  223. {
  224. var allEpisodes = GetSeasons(user, true, true)
  225. .SelectMany(i => i.GetEpisodes(user, includeMissing, includeVirtualUnaired))
  226. .Reverse()
  227. .ToList();
  228. // Specials could appear twice based on above - once in season 0, once in the aired season
  229. // This depends on settings for that series
  230. // When this happens, remove the duplicate from season 0
  231. return allEpisodes.DistinctBy(i => i.Id).Reverse();
  232. }
  233. public async Task RefreshAllMetadata(MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
  234. {
  235. // Refresh bottom up, children first, then the boxset
  236. // By then hopefully the movies within will have Tmdb collection values
  237. var items = GetRecursiveChildren().ToList();
  238. var seasons = items.OfType<Season>().ToList();
  239. var otherItems = items.Except(seasons).ToList();
  240. var totalItems = seasons.Count + otherItems.Count;
  241. var numComplete = 0;
  242. // Refresh current item
  243. await RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  244. // Refresh seasons
  245. foreach (var item in seasons)
  246. {
  247. cancellationToken.ThrowIfCancellationRequested();
  248. await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  249. numComplete++;
  250. double percent = numComplete;
  251. percent /= totalItems;
  252. progress.Report(percent * 100);
  253. }
  254. // Refresh episodes and other children
  255. foreach (var item in otherItems)
  256. {
  257. cancellationToken.ThrowIfCancellationRequested();
  258. var skipItem = false;
  259. var episode = item as Episode;
  260. if (episode != null
  261. && refreshOptions.MetadataRefreshMode != MetadataRefreshMode.FullRefresh
  262. && !refreshOptions.ReplaceAllMetadata
  263. && episode.IsMissingEpisode
  264. && episode.LocationType == LocationType.Virtual
  265. && episode.PremiereDate.HasValue
  266. && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30)
  267. {
  268. skipItem = true;
  269. }
  270. if (!skipItem)
  271. {
  272. await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  273. }
  274. numComplete++;
  275. double percent = numComplete;
  276. percent /= totalItems;
  277. progress.Report(percent * 100);
  278. }
  279. refreshOptions = new MetadataRefreshOptions(refreshOptions);
  280. refreshOptions.IsPostRecursiveRefresh = true;
  281. await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  282. progress.Report(100);
  283. }
  284. public IEnumerable<Episode> GetEpisodes(User user, Season season)
  285. {
  286. var config = user.Configuration;
  287. return GetEpisodes(user, season, config.DisplayMissingEpisodes, config.DisplayUnairedEpisodes);
  288. }
  289. private bool EnablePooling()
  290. {
  291. return false;
  292. }
  293. public IEnumerable<Episode> GetEpisodes(User user, Season parentSeason, bool includeMissingEpisodes, bool includeVirtualUnairedEpisodes)
  294. {
  295. IEnumerable<Episode> episodes;
  296. if (EnablePooling())
  297. {
  298. var seriesIds = LibraryManager.GetItemIds(new InternalItemsQuery(user)
  299. {
  300. PresentationUniqueKey = PresentationUniqueKey,
  301. IncludeItemTypes = new[] { typeof(Series).Name }
  302. });
  303. if (seriesIds.Count > 1)
  304. {
  305. episodes = LibraryManager.GetItemList(new InternalItemsQuery(user)
  306. {
  307. AncestorIds = seriesIds.Select(i => i.ToString("N")).ToArray(),
  308. IncludeItemTypes = new[] { typeof(Episode).Name },
  309. SortBy = new[] { ItemSortBy.SortName }
  310. }).Cast<Episode>();
  311. }
  312. else
  313. {
  314. episodes = GetRecursiveChildren(user, new InternalItemsQuery(user)
  315. {
  316. IncludeItemTypes = new[] { typeof(Episode).Name }
  317. }).Cast<Episode>();
  318. }
  319. }
  320. else
  321. {
  322. episodes = GetRecursiveChildren(user, new InternalItemsQuery(user)
  323. {
  324. IncludeItemTypes = new[] { typeof(Episode).Name }
  325. }).Cast<Episode>();
  326. }
  327. episodes = FilterEpisodesBySeason(episodes, parentSeason, DisplaySpecialsWithSeasons);
  328. if (!includeMissingEpisodes)
  329. {
  330. episodes = episodes.Where(i => !i.IsMissingEpisode);
  331. }
  332. if (!includeVirtualUnairedEpisodes)
  333. {
  334. episodes = episodes.Where(i => !i.IsVirtualUnaired);
  335. }
  336. var sortBy = (parentSeason.IndexNumber ?? -1) == 0 ? ItemSortBy.SortName : ItemSortBy.AiredEpisodeOrder;
  337. return LibraryManager.Sort(episodes, user, new[] { sortBy }, SortOrder.Ascending)
  338. .Cast<Episode>();
  339. }
  340. /// <summary>
  341. /// Filters the episodes by season.
  342. /// </summary>
  343. public static IEnumerable<Episode> FilterEpisodesBySeason(IEnumerable<Episode> episodes, int seasonNumber, bool includeSpecials)
  344. {
  345. if (!includeSpecials || seasonNumber < 1)
  346. {
  347. return episodes.Where(i => (i.ParentIndexNumber ?? -1) == seasonNumber);
  348. }
  349. return episodes.Where(i =>
  350. {
  351. var episode = i;
  352. if (episode != null)
  353. {
  354. var currentSeasonNumber = episode.AiredSeasonNumber;
  355. return currentSeasonNumber.HasValue && currentSeasonNumber.Value == seasonNumber;
  356. }
  357. return false;
  358. });
  359. }
  360. /// <summary>
  361. /// Filters the episodes by season.
  362. /// </summary>
  363. public static IEnumerable<Episode> FilterEpisodesBySeason(IEnumerable<Episode> episodes, Season parentSeason, bool includeSpecials)
  364. {
  365. var seasonNumber = parentSeason.IndexNumber;
  366. if (!includeSpecials || (seasonNumber.HasValue && seasonNumber.Value == 0))
  367. {
  368. var seasonPresentationKey = parentSeason.PresentationUniqueKey;
  369. return episodes.Where(i =>
  370. {
  371. if ((i.ParentIndexNumber ?? -1) == seasonNumber)
  372. {
  373. return true;
  374. }
  375. if (!i.ParentIndexNumber.HasValue)
  376. {
  377. var season = i.Season;
  378. return season != null && string.Equals(season.PresentationUniqueKey, seasonPresentationKey, StringComparison.OrdinalIgnoreCase);
  379. }
  380. return false;
  381. });
  382. }
  383. else
  384. {
  385. var seasonPresentationKey = parentSeason.PresentationUniqueKey;
  386. return episodes.Where(episode =>
  387. {
  388. var currentSeasonNumber = episode.AiredSeasonNumber;
  389. if (currentSeasonNumber.HasValue && seasonNumber.HasValue && currentSeasonNumber.Value == seasonNumber.Value)
  390. {
  391. return true;
  392. }
  393. if (!episode.ParentIndexNumber.HasValue)
  394. {
  395. var season = episode.Season;
  396. return season != null && string.Equals(season.PresentationUniqueKey, seasonPresentationKey, StringComparison.OrdinalIgnoreCase);
  397. }
  398. return false;
  399. });
  400. }
  401. }
  402. protected override bool GetBlockUnratedValue(UserPolicy config)
  403. {
  404. return config.BlockUnratedItems.Contains(UnratedItem.Series);
  405. }
  406. public override UnratedItem GetBlockUnratedType()
  407. {
  408. return UnratedItem.Series;
  409. }
  410. public SeriesInfo GetLookupInfo()
  411. {
  412. var info = GetItemLookupInfo<SeriesInfo>();
  413. info.AnimeSeriesIndex = AnimeSeriesIndex;
  414. return info;
  415. }
  416. public override bool BeforeMetadataRefresh()
  417. {
  418. var hasChanges = base.BeforeMetadataRefresh();
  419. if (!ProductionYear.HasValue)
  420. {
  421. var info = LibraryManager.ParseName(Name);
  422. var yearInName = info.Year;
  423. if (yearInName.HasValue)
  424. {
  425. ProductionYear = yearInName;
  426. hasChanges = true;
  427. }
  428. }
  429. return hasChanges;
  430. }
  431. public override List<ExternalUrl> GetRelatedUrls()
  432. {
  433. var list = base.GetRelatedUrls();
  434. var imdbId = this.GetProviderId(MetadataProviders.Imdb);
  435. if (!string.IsNullOrWhiteSpace(imdbId))
  436. {
  437. list.Add(new ExternalUrl
  438. {
  439. Name = "Trakt",
  440. Url = string.Format("https://trakt.tv/shows/{0}", imdbId)
  441. });
  442. }
  443. return list;
  444. }
  445. }
  446. }