TVSeriesManager.cs 12 KB

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