Series.cs 19 KB

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