Series.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text.Json.Serialization;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Providers;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Providers;
  13. using MediaBrowser.Model.Querying;
  14. using MediaBrowser.Model.Users;
  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. RemoteTrailers = Array.Empty<MediaUrl>();
  25. LocalTrailerIds = Array.Empty<Guid>();
  26. RemoteTrailerIds = Array.Empty<Guid>();
  27. AirDays = Array.Empty<DayOfWeek>();
  28. }
  29. public DayOfWeek[] AirDays { get; set; }
  30. public string AirTime { get; set; }
  31. [JsonIgnore]
  32. public override bool SupportsAddingToPlaylist => true;
  33. [JsonIgnore]
  34. public override bool IsPreSorted => true;
  35. [JsonIgnore]
  36. public override bool SupportsDateLastMediaAdded => true;
  37. [JsonIgnore]
  38. public override bool SupportsInheritedParentImages => false;
  39. [JsonIgnore]
  40. public override bool SupportsPeople => true;
  41. /// <inheritdoc />
  42. public IReadOnlyList<Guid> LocalTrailerIds { get; set; }
  43. /// <inheritdoc />
  44. public IReadOnlyList<Guid> RemoteTrailerIds { get; set; }
  45. /// <summary>
  46. /// airdate, dvd or absolute
  47. /// </summary>
  48. public string DisplayOrder { get; set; }
  49. /// <summary>
  50. /// Gets or sets the status.
  51. /// </summary>
  52. /// <value>The status.</value>
  53. public SeriesStatus? Status { get; set; }
  54. public override double GetDefaultPrimaryImageAspectRatio()
  55. {
  56. double value = 2;
  57. value /= 3;
  58. return value;
  59. }
  60. public override string CreatePresentationUniqueKey()
  61. {
  62. if (LibraryManager.GetLibraryOptions(this).EnableAutomaticSeriesGrouping)
  63. {
  64. var userdatakeys = GetUserDataKeys();
  65. if (userdatakeys.Count > 1)
  66. {
  67. return AddLibrariesToPresentationUniqueKey(userdatakeys[0]);
  68. }
  69. }
  70. return base.CreatePresentationUniqueKey();
  71. }
  72. private string AddLibrariesToPresentationUniqueKey(string key)
  73. {
  74. var lang = GetPreferredMetadataLanguage();
  75. if (!string.IsNullOrEmpty(lang))
  76. {
  77. key += "-" + lang;
  78. }
  79. var folders = LibraryManager.GetCollectionFolders(this)
  80. .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
  81. .ToArray();
  82. if (folders.Length == 0)
  83. {
  84. return key;
  85. }
  86. return key + "-" + string.Join("-", folders);
  87. }
  88. private static string GetUniqueSeriesKey(BaseItem series)
  89. {
  90. return series.GetPresentationUniqueKey();
  91. }
  92. public override int GetChildCount(User user)
  93. {
  94. var seriesKey = GetUniqueSeriesKey(this);
  95. var result = LibraryManager.GetCount(new InternalItemsQuery(user)
  96. {
  97. AncestorWithPresentationUniqueKey = null,
  98. SeriesPresentationUniqueKey = seriesKey,
  99. IncludeItemTypes = new[] { typeof(Season).Name },
  100. IsVirtualItem = false,
  101. Limit = 0,
  102. DtoOptions = new DtoOptions(false)
  103. {
  104. EnableImages = false
  105. }
  106. });
  107. return result;
  108. }
  109. public override int GetRecursiveChildCount(User user)
  110. {
  111. var seriesKey = GetUniqueSeriesKey(this);
  112. var query = new InternalItemsQuery(user)
  113. {
  114. AncestorWithPresentationUniqueKey = null,
  115. SeriesPresentationUniqueKey = seriesKey,
  116. DtoOptions = new DtoOptions(false)
  117. {
  118. EnableImages = false
  119. }
  120. };
  121. if (query.IncludeItemTypes.Length == 0)
  122. {
  123. query.IncludeItemTypes = new[] { typeof(Episode).Name };
  124. }
  125. query.IsVirtualItem = false;
  126. query.Limit = 0;
  127. var totalRecordCount = LibraryManager.GetCount(query);
  128. return totalRecordCount;
  129. }
  130. /// <summary>
  131. /// Gets the user data key.
  132. /// </summary>
  133. /// <returns>System.String.</returns>
  134. public override List<string> GetUserDataKeys()
  135. {
  136. var list = base.GetUserDataKeys();
  137. var key = this.GetProviderId(MetadataProvider.Imdb);
  138. if (!string.IsNullOrEmpty(key))
  139. {
  140. list.Insert(0, key);
  141. }
  142. key = this.GetProviderId(MetadataProvider.Tvdb);
  143. if (!string.IsNullOrEmpty(key))
  144. {
  145. list.Insert(0, key);
  146. }
  147. return list;
  148. }
  149. public override List<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
  150. {
  151. return GetSeasons(user, new DtoOptions(true));
  152. }
  153. public List<BaseItem> GetSeasons(User user, DtoOptions options)
  154. {
  155. var query = new InternalItemsQuery(user)
  156. {
  157. DtoOptions = options
  158. };
  159. SetSeasonQueryOptions(query, user);
  160. return LibraryManager.GetItemList(query);
  161. }
  162. private void SetSeasonQueryOptions(InternalItemsQuery query, User user)
  163. {
  164. var seriesKey = GetUniqueSeriesKey(this);
  165. query.AncestorWithPresentationUniqueKey = null;
  166. query.SeriesPresentationUniqueKey = seriesKey;
  167. query.IncludeItemTypes = new[] { typeof(Season).Name };
  168. query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray();
  169. if (user != null)
  170. {
  171. var config = user.Configuration;
  172. if (!config.DisplayMissingEpisodes)
  173. {
  174. query.IsMissing = false;
  175. }
  176. }
  177. }
  178. protected override QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  179. {
  180. var user = query.User;
  181. if (query.Recursive)
  182. {
  183. var seriesKey = GetUniqueSeriesKey(this);
  184. query.AncestorWithPresentationUniqueKey = null;
  185. query.SeriesPresentationUniqueKey = seriesKey;
  186. if (query.OrderBy.Count == 0)
  187. {
  188. query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray();
  189. }
  190. if (query.IncludeItemTypes.Length == 0)
  191. {
  192. query.IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name };
  193. }
  194. query.IsVirtualItem = false;
  195. return LibraryManager.GetItemsResult(query);
  196. }
  197. SetSeasonQueryOptions(query, user);
  198. return LibraryManager.GetItemsResult(query);
  199. }
  200. public IEnumerable<BaseItem> GetEpisodes(User user, DtoOptions options)
  201. {
  202. var seriesKey = GetUniqueSeriesKey(this);
  203. var query = new InternalItemsQuery(user)
  204. {
  205. AncestorWithPresentationUniqueKey = null,
  206. SeriesPresentationUniqueKey = seriesKey,
  207. IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name },
  208. OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
  209. DtoOptions = options
  210. };
  211. var config = user.Configuration;
  212. if (!config.DisplayMissingEpisodes)
  213. {
  214. query.IsMissing = false;
  215. }
  216. var allItems = LibraryManager.GetItemList(query);
  217. var allSeriesEpisodes = allItems.OfType<Episode>().ToList();
  218. var allEpisodes = allItems.OfType<Season>()
  219. .SelectMany(i => i.GetEpisodes(this, user, allSeriesEpisodes, options))
  220. .Reverse();
  221. // Specials could appear twice based on above - once in season 0, once in the aired season
  222. // This depends on settings for that series
  223. // When this happens, remove the duplicate from season 0
  224. return allEpisodes.GroupBy(i => i.Id).Select(x => x.First()).Reverse();
  225. }
  226. public async Task RefreshAllMetadata(MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
  227. {
  228. // Refresh bottom up, children first, then the boxset
  229. // By then hopefully the movies within will have Tmdb collection values
  230. var items = GetRecursiveChildren();
  231. var totalItems = items.Count;
  232. var numComplete = 0;
  233. // Refresh seasons
  234. foreach (var item in items)
  235. {
  236. if (!(item is Season))
  237. {
  238. continue;
  239. }
  240. cancellationToken.ThrowIfCancellationRequested();
  241. if (refreshOptions.RefreshItem(item))
  242. {
  243. await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  244. }
  245. numComplete++;
  246. double percent = numComplete;
  247. percent /= totalItems;
  248. progress.Report(percent * 100);
  249. }
  250. // Refresh episodes and other children
  251. foreach (var item in items)
  252. {
  253. if ((item is Season))
  254. {
  255. continue;
  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. if (refreshOptions.RefreshItem(item))
  273. {
  274. await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  275. }
  276. }
  277. numComplete++;
  278. double percent = numComplete;
  279. percent /= totalItems;
  280. progress.Report(percent * 100);
  281. }
  282. refreshOptions = new MetadataRefreshOptions(refreshOptions);
  283. await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  284. }
  285. public List<BaseItem> GetSeasonEpisodes(Season parentSeason, User user, DtoOptions options)
  286. {
  287. var queryFromSeries = ConfigurationManager.Configuration.DisplaySpecialsWithinSeasons;
  288. // add optimization when this setting is not enabled
  289. var seriesKey = queryFromSeries ?
  290. GetUniqueSeriesKey(this) :
  291. GetUniqueSeriesKey(parentSeason);
  292. var query = new InternalItemsQuery(user)
  293. {
  294. AncestorWithPresentationUniqueKey = queryFromSeries ? null : seriesKey,
  295. SeriesPresentationUniqueKey = queryFromSeries ? seriesKey : null,
  296. IncludeItemTypes = new[] { typeof(Episode).Name },
  297. OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Ascending)).ToArray(),
  298. DtoOptions = options
  299. };
  300. if (user != null)
  301. {
  302. var config = user.Configuration;
  303. if (!config.DisplayMissingEpisodes)
  304. {
  305. query.IsMissing = false;
  306. }
  307. }
  308. var allItems = LibraryManager.GetItemList(query);
  309. return GetSeasonEpisodes(parentSeason, user, allItems, options);
  310. }
  311. public List<BaseItem> GetSeasonEpisodes(Season parentSeason, User user, IEnumerable<BaseItem> allSeriesEpisodes, DtoOptions options)
  312. {
  313. if (allSeriesEpisodes == null)
  314. {
  315. return GetSeasonEpisodes(parentSeason, user, options);
  316. }
  317. var episodes = FilterEpisodesBySeason(allSeriesEpisodes, parentSeason, ConfigurationManager.Configuration.DisplaySpecialsWithinSeasons);
  318. var sortBy = (parentSeason.IndexNumber ?? -1) == 0 ? ItemSortBy.SortName : ItemSortBy.AiredEpisodeOrder;
  319. return LibraryManager.Sort(episodes, user, new[] { sortBy }, SortOrder.Ascending).ToList();
  320. }
  321. /// <summary>
  322. /// Filters the episodes by season.
  323. /// </summary>
  324. public static IEnumerable<BaseItem> FilterEpisodesBySeason(IEnumerable<BaseItem> episodes, Season parentSeason, bool includeSpecials)
  325. {
  326. var seasonNumber = parentSeason.IndexNumber;
  327. var seasonPresentationKey = GetUniqueSeriesKey(parentSeason);
  328. var supportSpecialsInSeason = includeSpecials && seasonNumber.HasValue && seasonNumber.Value != 0;
  329. return episodes.Where(episode =>
  330. {
  331. var episodeItem = (Episode)episode;
  332. var currentSeasonNumber = supportSpecialsInSeason ? episodeItem.AiredSeasonNumber : episode.ParentIndexNumber;
  333. if (currentSeasonNumber.HasValue && seasonNumber.HasValue && currentSeasonNumber.Value == seasonNumber.Value)
  334. {
  335. return true;
  336. }
  337. if (!currentSeasonNumber.HasValue && !seasonNumber.HasValue && parentSeason.LocationType == LocationType.Virtual)
  338. {
  339. return true;
  340. }
  341. var season = episodeItem.Season;
  342. return season != null && string.Equals(GetUniqueSeriesKey(season), seasonPresentationKey, StringComparison.OrdinalIgnoreCase);
  343. });
  344. }
  345. /// <summary>
  346. /// Filters the episodes by season.
  347. /// </summary>
  348. public static IEnumerable<Episode> FilterEpisodesBySeason(IEnumerable<Episode> episodes, int seasonNumber, bool includeSpecials)
  349. {
  350. if (!includeSpecials || seasonNumber < 1)
  351. {
  352. return episodes.Where(i => (i.ParentIndexNumber ?? -1) == seasonNumber);
  353. }
  354. return episodes.Where(i =>
  355. {
  356. var episode = i;
  357. if (episode != null)
  358. {
  359. var currentSeasonNumber = episode.AiredSeasonNumber;
  360. return currentSeasonNumber.HasValue && currentSeasonNumber.Value == seasonNumber;
  361. }
  362. return false;
  363. });
  364. }
  365. protected override bool GetBlockUnratedValue(UserPolicy config)
  366. {
  367. return config.BlockUnratedItems.Contains(UnratedItem.Series);
  368. }
  369. public override UnratedItem GetBlockUnratedType()
  370. {
  371. return UnratedItem.Series;
  372. }
  373. public SeriesInfo GetLookupInfo()
  374. {
  375. var info = GetItemLookupInfo<SeriesInfo>();
  376. return info;
  377. }
  378. public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
  379. {
  380. var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata);
  381. if (!ProductionYear.HasValue)
  382. {
  383. var info = LibraryManager.ParseName(Name);
  384. var yearInName = info.Year;
  385. if (yearInName.HasValue)
  386. {
  387. ProductionYear = yearInName;
  388. hasChanges = true;
  389. }
  390. }
  391. return hasChanges;
  392. }
  393. public override List<ExternalUrl> GetRelatedUrls()
  394. {
  395. var list = base.GetRelatedUrls();
  396. var imdbId = this.GetProviderId(MetadataProvider.Imdb);
  397. if (!string.IsNullOrEmpty(imdbId))
  398. {
  399. list.Add(new ExternalUrl
  400. {
  401. Name = "Trakt",
  402. Url = string.Format("https://trakt.tv/shows/{0}", imdbId)
  403. });
  404. }
  405. return list;
  406. }
  407. [JsonIgnore]
  408. public override bool StopRefreshIfLocalMetadataFound => false;
  409. }
  410. }