TVSeriesManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using Jellyfin.Data.Entities;
  7. using Jellyfin.Data.Enums;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Dto;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.TV;
  13. using MediaBrowser.Model.Querying;
  14. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  15. using Series = MediaBrowser.Controller.Entities.TV.Series;
  16. namespace Emby.Server.Implementations.TV
  17. {
  18. public class TVSeriesManager : ITVSeriesManager
  19. {
  20. private readonly IUserManager _userManager;
  21. private readonly IUserDataManager _userDataManager;
  22. private readonly ILibraryManager _libraryManager;
  23. private readonly IServerConfigurationManager _configurationManager;
  24. public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager)
  25. {
  26. _userManager = userManager;
  27. _userDataManager = userDataManager;
  28. _libraryManager = libraryManager;
  29. _configurationManager = configurationManager;
  30. }
  31. public QueryResult<BaseItem> GetNextUp(NextUpQuery query, DtoOptions options)
  32. {
  33. var user = _userManager.GetUserById(query.UserId);
  34. if (user is null)
  35. {
  36. throw new ArgumentException("User not found");
  37. }
  38. string presentationUniqueKey = null;
  39. if (query.SeriesId.HasValue && !query.SeriesId.Value.Equals(default))
  40. {
  41. if (_libraryManager.GetItemById(query.SeriesId.Value) is Series series)
  42. {
  43. presentationUniqueKey = GetUniqueSeriesKey(series);
  44. }
  45. }
  46. if (!string.IsNullOrEmpty(presentationUniqueKey))
  47. {
  48. return GetResult(GetNextUpEpisodes(query, user, new[] { presentationUniqueKey }, options), query);
  49. }
  50. BaseItem[] parents;
  51. if (query.ParentId.HasValue)
  52. {
  53. var parent = _libraryManager.GetItemById(query.ParentId.Value);
  54. if (parent is not null)
  55. {
  56. parents = new[] { parent };
  57. }
  58. else
  59. {
  60. parents = Array.Empty<BaseItem>();
  61. }
  62. }
  63. else
  64. {
  65. parents = _libraryManager.GetUserRootFolder().GetChildren(user, true)
  66. .Where(i => i is Folder)
  67. .Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes).Contains(i.Id))
  68. .ToArray();
  69. }
  70. return GetNextUp(query, parents, options);
  71. }
  72. public QueryResult<BaseItem> GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions options)
  73. {
  74. var user = _userManager.GetUserById(request.UserId);
  75. if (user is null)
  76. {
  77. throw new ArgumentException("User not found");
  78. }
  79. string presentationUniqueKey = null;
  80. int? limit = null;
  81. if (request.SeriesId.HasValue && !request.SeriesId.Value.Equals(default))
  82. {
  83. if (_libraryManager.GetItemById(request.SeriesId.Value) is Series series)
  84. {
  85. presentationUniqueKey = GetUniqueSeriesKey(series);
  86. limit = 1;
  87. }
  88. }
  89. if (!string.IsNullOrEmpty(presentationUniqueKey))
  90. {
  91. return GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, options), request);
  92. }
  93. if (limit.HasValue)
  94. {
  95. limit = limit.Value + 10;
  96. }
  97. var items = _libraryManager
  98. .GetItemList(
  99. new InternalItemsQuery(user)
  100. {
  101. IncludeItemTypes = new[] { BaseItemKind.Episode },
  102. OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
  103. SeriesPresentationUniqueKey = presentationUniqueKey,
  104. Limit = limit,
  105. DtoOptions = new DtoOptions { Fields = new[] { ItemFields.SeriesPresentationUniqueKey }, EnableImages = false },
  106. GroupBySeriesPresentationUniqueKey = true
  107. },
  108. parentsFolders.ToList())
  109. .Cast<Episode>()
  110. .Where(episode => !string.IsNullOrEmpty(episode.SeriesPresentationUniqueKey))
  111. .Select(GetUniqueSeriesKey)
  112. .ToList();
  113. // Avoid implicitly captured closure
  114. var episodes = GetNextUpEpisodes(request, user, items, options);
  115. return GetResult(episodes, request);
  116. }
  117. private IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IReadOnlyList<string> seriesKeys, DtoOptions dtoOptions)
  118. {
  119. var allNextUp = seriesKeys.Select(i => GetNextUp(i, user, dtoOptions, false));
  120. if (request.EnableRewatching)
  121. {
  122. allNextUp = allNextUp.Concat(
  123. seriesKeys.Select(i => GetNextUp(i, user, dtoOptions, true)))
  124. .OrderByDescending(i => i.LastWatchedDate);
  125. }
  126. // If viewing all next up for all series, remove first episodes
  127. // But if that returns empty, keep those first episodes (avoid completely empty view)
  128. var alwaysEnableFirstEpisode = request.SeriesId.HasValue && !request.SeriesId.Value.Equals(default);
  129. var anyFound = false;
  130. return allNextUp
  131. .Where(i =>
  132. {
  133. if (request.DisableFirstEpisode)
  134. {
  135. return i.LastWatchedDate != DateTime.MinValue;
  136. }
  137. if (alwaysEnableFirstEpisode || (i.LastWatchedDate != DateTime.MinValue && i.LastWatchedDate.Date >= request.NextUpDateCutoff))
  138. {
  139. anyFound = true;
  140. return true;
  141. }
  142. return !anyFound && i.LastWatchedDate == DateTime.MinValue;
  143. })
  144. .Select(i => i.GetEpisodeFunction())
  145. .Where(i => i is not null);
  146. }
  147. private static string GetUniqueSeriesKey(Episode episode)
  148. {
  149. return episode.SeriesPresentationUniqueKey;
  150. }
  151. private static string GetUniqueSeriesKey(Series series)
  152. {
  153. return series.GetPresentationUniqueKey();
  154. }
  155. /// <summary>
  156. /// Gets the next up.
  157. /// </summary>
  158. /// <returns>Task{Episode}.</returns>
  159. private (DateTime LastWatchedDate, Func<Episode> GetEpisodeFunction) GetNextUp(string seriesKey, User user, DtoOptions dtoOptions, bool rewatching)
  160. {
  161. var lastQuery = new InternalItemsQuery(user)
  162. {
  163. AncestorWithPresentationUniqueKey = null,
  164. SeriesPresentationUniqueKey = seriesKey,
  165. IncludeItemTypes = new[] { BaseItemKind.Episode },
  166. IsPlayed = true,
  167. Limit = 1,
  168. ParentIndexNumberNotEquals = 0,
  169. DtoOptions = new DtoOptions
  170. {
  171. Fields = new[] { ItemFields.SortName },
  172. EnableImages = false
  173. }
  174. };
  175. // If rewatching is enabled, sort first by date played and then by season and episode numbers
  176. lastQuery.OrderBy = rewatching
  177. ? new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.ParentIndexNumber, SortOrder.Descending), (ItemSortBy.IndexNumber, SortOrder.Descending) }
  178. : new[] { (ItemSortBy.ParentIndexNumber, SortOrder.Descending), (ItemSortBy.IndexNumber, SortOrder.Descending) };
  179. var lastWatchedEpisode = _libraryManager.GetItemList(lastQuery).Cast<Episode>().FirstOrDefault();
  180. Episode GetEpisode()
  181. {
  182. var nextQuery = new InternalItemsQuery(user)
  183. {
  184. AncestorWithPresentationUniqueKey = null,
  185. SeriesPresentationUniqueKey = seriesKey,
  186. IncludeItemTypes = new[] { BaseItemKind.Episode },
  187. OrderBy = new[] { (ItemSortBy.ParentIndexNumber, SortOrder.Ascending), (ItemSortBy.IndexNumber, SortOrder.Ascending) },
  188. Limit = 1,
  189. IsPlayed = rewatching,
  190. IsVirtualItem = false,
  191. ParentIndexNumberNotEquals = 0,
  192. DtoOptions = dtoOptions
  193. };
  194. // Locate the next up episode based on the last watched episode's season and episode number
  195. var lastWatchedParentIndexNumber = lastWatchedEpisode?.ParentIndexNumber;
  196. var lastWatchedIndexNumber = lastWatchedEpisode?.IndexNumberEnd ?? lastWatchedEpisode?.IndexNumber;
  197. if (lastWatchedParentIndexNumber.HasValue && lastWatchedIndexNumber.HasValue)
  198. {
  199. nextQuery.MinParentAndIndexNumber = (lastWatchedParentIndexNumber.Value, lastWatchedIndexNumber.Value + 1);
  200. }
  201. var nextEpisode = _libraryManager.GetItemList(nextQuery).Cast<Episode>().FirstOrDefault();
  202. if (_configurationManager.Configuration.DisplaySpecialsWithinSeasons)
  203. {
  204. var consideredEpisodes = _libraryManager.GetItemList(new InternalItemsQuery(user)
  205. {
  206. AncestorWithPresentationUniqueKey = null,
  207. SeriesPresentationUniqueKey = seriesKey,
  208. ParentIndexNumber = 0,
  209. IncludeItemTypes = new[] { BaseItemKind.Episode },
  210. IsPlayed = rewatching,
  211. IsVirtualItem = false,
  212. DtoOptions = dtoOptions
  213. })
  214. .Cast<Episode>()
  215. .Where(episode => episode.AirsBeforeSeasonNumber is not null || episode.AirsAfterSeasonNumber is not null)
  216. .ToList();
  217. if (lastWatchedEpisode is not null)
  218. {
  219. // Last watched episode is added, because there could be specials that aired before the last watched episode
  220. consideredEpisodes.Add(lastWatchedEpisode);
  221. }
  222. if (nextEpisode is not null)
  223. {
  224. consideredEpisodes.Add(nextEpisode);
  225. }
  226. var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) })
  227. .Cast<Episode>();
  228. if (lastWatchedEpisode is not null)
  229. {
  230. sortedConsideredEpisodes = sortedConsideredEpisodes.SkipWhile(episode => !episode.Id.Equals(lastWatchedEpisode.Id)).Skip(1);
  231. }
  232. nextEpisode = sortedConsideredEpisodes.FirstOrDefault();
  233. }
  234. if (nextEpisode is not null)
  235. {
  236. var userData = _userDataManager.GetUserData(user, nextEpisode);
  237. if (userData.PlaybackPositionTicks > 0)
  238. {
  239. return null;
  240. }
  241. }
  242. return nextEpisode;
  243. }
  244. if (lastWatchedEpisode is not null)
  245. {
  246. var userData = _userDataManager.GetUserData(user, lastWatchedEpisode);
  247. var lastWatchedDate = userData.LastPlayedDate ?? DateTime.MinValue.AddDays(1);
  248. return (lastWatchedDate, GetEpisode);
  249. }
  250. // Return the first episode
  251. return (DateTime.MinValue, GetEpisode);
  252. }
  253. private static QueryResult<BaseItem> GetResult(IEnumerable<BaseItem> items, NextUpQuery query)
  254. {
  255. int totalCount = 0;
  256. if (query.EnableTotalRecordCount)
  257. {
  258. var list = items.ToList();
  259. totalCount = list.Count;
  260. items = list;
  261. }
  262. if (query.StartIndex.HasValue)
  263. {
  264. items = items.Skip(query.StartIndex.Value);
  265. }
  266. if (query.Limit.HasValue)
  267. {
  268. items = items.Take(query.Limit.Value);
  269. }
  270. return new QueryResult<BaseItem>(
  271. query.StartIndex,
  272. totalCount,
  273. items.ToArray());
  274. }
  275. }
  276. }