TVSeriesManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 == null)
  35. {
  36. throw new ArgumentException("User not found");
  37. }
  38. string presentationUniqueKey = null;
  39. if (!string.IsNullOrEmpty(query.SeriesId))
  40. {
  41. if (_libraryManager.GetItemById(query.SeriesId) 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 != 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 == null)
  76. {
  77. throw new ArgumentException("User not found");
  78. }
  79. string presentationUniqueKey = null;
  80. int? limit = null;
  81. if (!string.IsNullOrEmpty(request.SeriesId))
  82. {
  83. if (_libraryManager.GetItemById(request.SeriesId) 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. public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IReadOnlyList<string> seriesKeys, DtoOptions dtoOptions)
  118. {
  119. // Avoid implicitly captured closure
  120. var currentUser = user;
  121. var allNextUp = seriesKeys
  122. .Select(i => GetNextUp(i, currentUser, dtoOptions, false));
  123. if (request.EnableRewatching)
  124. {
  125. allNextUp = allNextUp.Concat(
  126. seriesKeys.Select(i => GetNextUp(i, currentUser, dtoOptions, true))
  127. )
  128. .OrderByDescending(i => i.Item1);
  129. }
  130. // If viewing all next up for all series, remove first episodes
  131. // But if that returns empty, keep those first episodes (avoid completely empty view)
  132. var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId);
  133. var anyFound = false;
  134. return allNextUp
  135. .Where(i =>
  136. {
  137. if (request.DisableFirstEpisode)
  138. {
  139. return i.Item1 != DateTime.MinValue;
  140. }
  141. if (alwaysEnableFirstEpisode || (i.Item1 != DateTime.MinValue && i.Item1.Date >= request.NextUpDateCutoff))
  142. {
  143. anyFound = true;
  144. return true;
  145. }
  146. if (!anyFound && i.Item1 == DateTime.MinValue)
  147. {
  148. return true;
  149. }
  150. return false;
  151. })
  152. .Select(i => i.Item2())
  153. .Where(i => i != null);
  154. }
  155. private static string GetUniqueSeriesKey(Episode episode)
  156. {
  157. return episode.SeriesPresentationUniqueKey;
  158. }
  159. private static string GetUniqueSeriesKey(Series series)
  160. {
  161. return series.GetPresentationUniqueKey();
  162. }
  163. /// <summary>
  164. /// Gets the next up.
  165. /// </summary>
  166. /// <returns>Task{Episode}.</returns>
  167. private Tuple<DateTime, Func<Episode>> GetNextUp(string seriesKey, User user, DtoOptions dtoOptions, bool rewatching)
  168. {
  169. var lastQuery = new InternalItemsQuery(user)
  170. {
  171. AncestorWithPresentationUniqueKey = null,
  172. SeriesPresentationUniqueKey = seriesKey,
  173. IncludeItemTypes = new[] { BaseItemKind.Episode },
  174. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Descending) },
  175. IsPlayed = true,
  176. Limit = 1,
  177. ParentIndexNumberNotEquals = 0,
  178. DtoOptions = new DtoOptions
  179. {
  180. Fields = new[] { ItemFields.SortName },
  181. EnableImages = false
  182. }
  183. };
  184. if (rewatching)
  185. {
  186. // find last watched by date played, not by newest episode watched
  187. lastQuery.OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) };
  188. }
  189. var lastWatchedEpisode = _libraryManager.GetItemList(lastQuery).Cast<Episode>().FirstOrDefault();
  190. Func<Episode> getEpisode = () =>
  191. {
  192. var nextQuery = new InternalItemsQuery(user)
  193. {
  194. AncestorWithPresentationUniqueKey = null,
  195. SeriesPresentationUniqueKey = seriesKey,
  196. IncludeItemTypes = new[] { BaseItemKind.Episode },
  197. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
  198. Limit = 1,
  199. IsPlayed = rewatching,
  200. IsVirtualItem = false,
  201. ParentIndexNumberNotEquals = 0,
  202. MinSortName = lastWatchedEpisode?.SortName,
  203. DtoOptions = dtoOptions
  204. };
  205. Episode nextEpisode;
  206. if (rewatching)
  207. {
  208. nextQuery.Limit = 2;
  209. // get watched episode after most recently watched
  210. nextEpisode = _libraryManager.GetItemList(nextQuery).Cast<Episode>().ElementAtOrDefault(1);
  211. }
  212. else
  213. {
  214. nextEpisode = _libraryManager.GetItemList(nextQuery).Cast<Episode>().FirstOrDefault();
  215. }
  216. if (_configurationManager.Configuration.DisplaySpecialsWithinSeasons)
  217. {
  218. var consideredEpisodes = _libraryManager.GetItemList(new InternalItemsQuery(user)
  219. {
  220. AncestorWithPresentationUniqueKey = null,
  221. SeriesPresentationUniqueKey = seriesKey,
  222. ParentIndexNumber = 0,
  223. IncludeItemTypes = new[] { BaseItemKind.Episode },
  224. IsPlayed = rewatching,
  225. IsVirtualItem = false,
  226. DtoOptions = dtoOptions
  227. })
  228. .Cast<Episode>()
  229. .Where(episode => episode.AirsBeforeSeasonNumber != null || episode.AirsAfterSeasonNumber != null)
  230. .ToList();
  231. if (lastWatchedEpisode != null)
  232. {
  233. // Last watched episode is added, because there could be specials that aired before the last watched episode
  234. consideredEpisodes.Add(lastWatchedEpisode);
  235. }
  236. if (nextEpisode != null)
  237. {
  238. consideredEpisodes.Add(nextEpisode);
  239. }
  240. var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) })
  241. .Cast<Episode>();
  242. if (lastWatchedEpisode != null)
  243. {
  244. sortedConsideredEpisodes = sortedConsideredEpisodes.SkipWhile(episode => !episode.Id.Equals(lastWatchedEpisode.Id)).Skip(1);
  245. }
  246. nextEpisode = sortedConsideredEpisodes.FirstOrDefault();
  247. }
  248. if (nextEpisode != null)
  249. {
  250. var userData = _userDataManager.GetUserData(user, nextEpisode);
  251. if (userData.PlaybackPositionTicks > 0)
  252. {
  253. return null;
  254. }
  255. }
  256. return nextEpisode;
  257. };
  258. if (lastWatchedEpisode != null)
  259. {
  260. var userData = _userDataManager.GetUserData(user, lastWatchedEpisode);
  261. var lastWatchedDate = userData.LastPlayedDate ?? DateTime.MinValue.AddDays(1);
  262. return new Tuple<DateTime, Func<Episode>>(lastWatchedDate, getEpisode);
  263. }
  264. // Return the first episode
  265. return new Tuple<DateTime, Func<Episode>>(DateTime.MinValue, getEpisode);
  266. }
  267. private static QueryResult<BaseItem> GetResult(IEnumerable<BaseItem> items, NextUpQuery query)
  268. {
  269. int totalCount = 0;
  270. if (query.EnableTotalRecordCount)
  271. {
  272. var list = items.ToList();
  273. totalCount = list.Count;
  274. items = list;
  275. }
  276. if (query.StartIndex.HasValue)
  277. {
  278. items = items.Skip(query.StartIndex.Value);
  279. }
  280. if (query.Limit.HasValue)
  281. {
  282. items = items.Take(query.Limit.Value);
  283. }
  284. return new QueryResult<BaseItem>(
  285. query.StartIndex,
  286. totalCount,
  287. items.ToArray());
  288. }
  289. }
  290. }