UserViewBuilder.cs 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. using MediaBrowser.Controller.Channels;
  2. using MediaBrowser.Controller.Collections;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.Playlists;
  9. using MediaBrowser.Controller.TV;
  10. using MediaBrowser.Model.Channels;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.LiveTv;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.Querying;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Controller.Entities
  22. {
  23. public class UserViewBuilder
  24. {
  25. private readonly IChannelManager _channelManager;
  26. private readonly ILiveTvManager _liveTvManager;
  27. private readonly IUserViewManager _userViewManager;
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly ILogger _logger;
  30. private readonly IUserDataManager _userDataManager;
  31. private readonly ITVSeriesManager _tvSeriesManager;
  32. private readonly ICollectionManager _collectionManager;
  33. private readonly IPlaylistManager _playlistManager;
  34. public UserViewBuilder(IUserViewManager userViewManager, ILiveTvManager liveTvManager, IChannelManager channelManager, ILibraryManager libraryManager, ILogger logger, IUserDataManager userDataManager, ITVSeriesManager tvSeriesManager, ICollectionManager collectionManager, IPlaylistManager playlistManager)
  35. {
  36. _userViewManager = userViewManager;
  37. _liveTvManager = liveTvManager;
  38. _channelManager = channelManager;
  39. _libraryManager = libraryManager;
  40. _logger = logger;
  41. _userDataManager = userDataManager;
  42. _tvSeriesManager = tvSeriesManager;
  43. _collectionManager = collectionManager;
  44. _playlistManager = playlistManager;
  45. }
  46. public async Task<QueryResult<BaseItem>> GetUserItems(Folder queryParent, Folder displayParent, string viewType, InternalItemsQuery query)
  47. {
  48. var user = query.User;
  49. if (query.IncludeItemTypes != null &&
  50. query.IncludeItemTypes.Length == 1 &&
  51. string.Equals(query.IncludeItemTypes[0], "Playlist", StringComparison.OrdinalIgnoreCase))
  52. {
  53. if (!string.Equals(viewType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
  54. {
  55. return await FindPlaylists(queryParent, user, query).ConfigureAwait(false);
  56. }
  57. }
  58. switch (viewType)
  59. {
  60. case CollectionType.Channels:
  61. {
  62. var result = await _channelManager.GetChannelsInternal(new ChannelQuery
  63. {
  64. UserId = user.Id.ToString("N"),
  65. Limit = query.Limit,
  66. StartIndex = query.StartIndex
  67. }, CancellationToken.None).ConfigureAwait(false);
  68. return GetResult(result);
  69. }
  70. case SpecialFolder.LiveTvChannels:
  71. {
  72. var result = await _liveTvManager.GetInternalChannels(new LiveTvChannelQuery
  73. {
  74. UserId = query.User.Id.ToString("N"),
  75. Limit = query.Limit,
  76. StartIndex = query.StartIndex
  77. }, CancellationToken.None).ConfigureAwait(false);
  78. return GetResult(result);
  79. }
  80. case SpecialFolder.LiveTvNowPlaying:
  81. {
  82. var result = await _liveTvManager.GetRecommendedProgramsInternal(new RecommendedProgramQuery
  83. {
  84. UserId = query.User.Id.ToString("N"),
  85. Limit = query.Limit,
  86. IsAiring = true
  87. }, CancellationToken.None).ConfigureAwait(false);
  88. return GetResult(result);
  89. }
  90. case SpecialFolder.LiveTvRecordingGroups:
  91. {
  92. var result = await _liveTvManager.GetInternalRecordings(new RecordingQuery
  93. {
  94. UserId = query.User.Id.ToString("N"),
  95. Status = RecordingStatus.Completed,
  96. Limit = query.Limit,
  97. StartIndex = query.StartIndex
  98. }, CancellationToken.None).ConfigureAwait(false);
  99. return GetResult(result);
  100. }
  101. case CollectionType.LiveTv:
  102. {
  103. return await GetLiveTvView(queryParent, user, query).ConfigureAwait(false);
  104. }
  105. case CollectionType.Books:
  106. case CollectionType.Photos:
  107. case CollectionType.HomeVideos:
  108. case CollectionType.MusicVideos:
  109. return GetResult(queryParent.GetChildren(user, true), queryParent, query);
  110. case CollectionType.Folders:
  111. return GetResult(user.RootFolder.GetChildren(user, true), queryParent, query);
  112. case CollectionType.Games:
  113. return await GetGameView(user, queryParent, query).ConfigureAwait(false);
  114. case CollectionType.Playlists:
  115. return await GetPlaylistsView(queryParent, user, query).ConfigureAwait(false);
  116. case CollectionType.BoxSets:
  117. return await GetBoxsetView(queryParent, user, query).ConfigureAwait(false);
  118. case CollectionType.TvShows:
  119. return await GetTvView(queryParent, user, query).ConfigureAwait(false);
  120. case CollectionType.Music:
  121. return await GetMusicFolders(queryParent, user, query).ConfigureAwait(false);
  122. case CollectionType.Movies:
  123. return await GetMovieFolders(queryParent, user, query).ConfigureAwait(false);
  124. case SpecialFolder.MusicGenres:
  125. return await GetMusicGenres(queryParent, user, query).ConfigureAwait(false);
  126. case SpecialFolder.MusicGenre:
  127. return await GetMusicGenreItems(queryParent, displayParent, user, query).ConfigureAwait(false);
  128. case SpecialFolder.GameGenres:
  129. return await GetGameGenres(queryParent, user, query).ConfigureAwait(false);
  130. case SpecialFolder.GameGenre:
  131. return await GetGameGenreItems(queryParent, displayParent, user, query).ConfigureAwait(false);
  132. case SpecialFolder.GameSystems:
  133. return GetGameSystems(queryParent, user, query);
  134. case SpecialFolder.LatestGames:
  135. return GetLatestGames(queryParent, user, query);
  136. case SpecialFolder.RecentlyPlayedGames:
  137. return GetRecentlyPlayedGames(queryParent, user, query);
  138. case SpecialFolder.GameFavorites:
  139. return GetFavoriteGames(queryParent, user, query);
  140. case SpecialFolder.TvShowSeries:
  141. return GetTvSeries(queryParent, user, query);
  142. case SpecialFolder.TvGenres:
  143. return await GetTvGenres(queryParent, user, query).ConfigureAwait(false);
  144. case SpecialFolder.TvGenre:
  145. return await GetTvGenreItems(queryParent, displayParent, user, query).ConfigureAwait(false);
  146. case SpecialFolder.TvResume:
  147. return GetTvResume(queryParent, user, query);
  148. case SpecialFolder.TvNextUp:
  149. return GetTvNextUp(queryParent, query);
  150. case SpecialFolder.TvLatest:
  151. return GetTvLatest(queryParent, user, query);
  152. case SpecialFolder.MovieFavorites:
  153. return GetFavoriteMovies(queryParent, user, query);
  154. case SpecialFolder.MovieLatest:
  155. return GetMovieLatest(queryParent, user, query);
  156. case SpecialFolder.MovieGenres:
  157. return await GetMovieGenres(queryParent, user, query).ConfigureAwait(false);
  158. case SpecialFolder.MovieGenre:
  159. return await GetMovieGenreItems(queryParent, displayParent, user, query).ConfigureAwait(false);
  160. case SpecialFolder.MovieResume:
  161. return GetMovieResume(queryParent, user, query);
  162. case SpecialFolder.MovieMovies:
  163. return GetMovieMovies(queryParent, user, query);
  164. case SpecialFolder.MovieCollections:
  165. return GetMovieCollections(queryParent, user, query);
  166. case SpecialFolder.MusicLatest:
  167. return GetMusicLatest(queryParent, user, query);
  168. case SpecialFolder.MusicPlaylists:
  169. return await GetMusicPlaylists(queryParent, user, query).ConfigureAwait(false);
  170. case SpecialFolder.MusicAlbums:
  171. return GetMusicAlbums(queryParent, user, query);
  172. case SpecialFolder.MusicAlbumArtists:
  173. return GetMusicAlbumArtists(queryParent, user, query);
  174. case SpecialFolder.MusicArtists:
  175. return GetMusicArtists(queryParent, user, query);
  176. case SpecialFolder.MusicSongs:
  177. return GetMusicSongs(queryParent, user, query);
  178. case SpecialFolder.TvFavoriteEpisodes:
  179. return GetFavoriteEpisodes(queryParent, user, query);
  180. case SpecialFolder.TvFavoriteSeries:
  181. return GetFavoriteSeries(queryParent, user, query);
  182. case SpecialFolder.MusicFavorites:
  183. return await GetMusicFavorites(queryParent, user, query).ConfigureAwait(false);
  184. case SpecialFolder.MusicFavoriteAlbums:
  185. return GetFavoriteAlbums(queryParent, user, query);
  186. case SpecialFolder.MusicFavoriteArtists:
  187. return GetFavoriteArtists(queryParent, user, query);
  188. case SpecialFolder.MusicFavoriteSongs:
  189. return GetFavoriteSongs(queryParent, user, query);
  190. default:
  191. return GetResult(GetMediaFolders(user).SelectMany(i => i.GetChildren(user, true)), queryParent, query);
  192. }
  193. }
  194. private async Task<QueryResult<BaseItem>> FindPlaylists(Folder parent, User user, InternalItemsQuery query)
  195. {
  196. var collectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  197. var list = _playlistManager.GetPlaylists(user.Id.ToString("N"))
  198. .Where(i => i.GetChildren(user, true).Any(media => _libraryManager.GetCollectionFolders(media).Select(c => c.Id).Any(collectionFolders.Contains)));
  199. return GetResult(list, parent, query);
  200. }
  201. private int GetSpecialItemsLimit()
  202. {
  203. return 50;
  204. }
  205. private async Task<QueryResult<BaseItem>> GetMusicFolders(Folder parent, User user, InternalItemsQuery query)
  206. {
  207. if (query.Recursive)
  208. {
  209. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }, i => FilterItem(i, query));
  210. return PostFilterAndSort(items, parent, null, query);
  211. }
  212. var list = new List<BaseItem>();
  213. list.Add(await GetUserView(SpecialFolder.MusicLatest, user, "0", parent).ConfigureAwait(false));
  214. list.Add(await GetUserView(SpecialFolder.MusicPlaylists, user, "1", parent).ConfigureAwait(false));
  215. list.Add(await GetUserView(SpecialFolder.MusicAlbums, user, "2", parent).ConfigureAwait(false));
  216. list.Add(await GetUserView(SpecialFolder.MusicAlbumArtists, user, "3", parent).ConfigureAwait(false));
  217. //list.Add(await GetUserView(SpecialFolder.MusicArtists, user, "4", parent).ConfigureAwait(false));
  218. list.Add(await GetUserView(SpecialFolder.MusicSongs, user, "5", parent).ConfigureAwait(false));
  219. list.Add(await GetUserView(SpecialFolder.MusicGenres, user, "6", parent).ConfigureAwait(false));
  220. list.Add(await GetUserView(SpecialFolder.MusicFavorites, user, "7", parent).ConfigureAwait(false));
  221. return GetResult(list, parent, query);
  222. }
  223. private async Task<QueryResult<BaseItem>> GetMusicFavorites(Folder parent, User user, InternalItemsQuery query)
  224. {
  225. var list = new List<BaseItem>();
  226. list.Add(await GetUserView(SpecialFolder.MusicFavoriteAlbums, user, "0", parent).ConfigureAwait(false));
  227. list.Add(await GetUserView(SpecialFolder.MusicFavoriteArtists, user, "1", parent).ConfigureAwait(false));
  228. list.Add(await GetUserView(SpecialFolder.MusicFavoriteSongs, user, "2", parent).ConfigureAwait(false));
  229. return GetResult(list, parent, query);
  230. }
  231. private async Task<QueryResult<BaseItem>> GetMusicGenres(Folder parent, User user, InternalItemsQuery query)
  232. {
  233. var tasks = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos })
  234. .Where(i => !i.IsFolder)
  235. .SelectMany(i => i.Genres)
  236. .DistinctNames()
  237. .Select(i =>
  238. {
  239. try
  240. {
  241. return _libraryManager.GetMusicGenre(i);
  242. }
  243. catch
  244. {
  245. // Full exception logged at lower levels
  246. _logger.Error("Error getting genre");
  247. return null;
  248. }
  249. })
  250. .Where(i => i != null)
  251. .Select(i => GetUserView(i.Name, SpecialFolder.MusicGenre, user, i.SortName, parent));
  252. var genres = await Task.WhenAll(tasks).ConfigureAwait(false);
  253. return GetResult(genres, parent, query);
  254. }
  255. private async Task<QueryResult<BaseItem>> GetMusicGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
  256. {
  257. var items = GetRecursiveChildren(queryParent, user, new[] { CollectionType.Music, CollectionType.MusicVideos })
  258. .Where(i => !i.IsFolder)
  259. .Where(i => i.Genres.Contains(displayParent.Name, StringComparer.OrdinalIgnoreCase))
  260. .OfType<IHasAlbumArtist>()
  261. .SelectMany(i => i.AlbumArtists)
  262. .DistinctNames()
  263. .Select(i =>
  264. {
  265. try
  266. {
  267. return _libraryManager.GetArtist(i);
  268. }
  269. catch
  270. {
  271. // Already logged at lower levels
  272. return null;
  273. }
  274. })
  275. .Where(i => i != null);
  276. return GetResult(items, queryParent, query);
  277. }
  278. private QueryResult<BaseItem> GetMusicAlbumArtists(Folder parent, User user, InternalItemsQuery query)
  279. {
  280. var artists = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos })
  281. .Where(i => !i.IsFolder)
  282. .OfType<IHasAlbumArtist>()
  283. .SelectMany(i => i.AlbumArtists)
  284. .DistinctNames()
  285. .Select(i =>
  286. {
  287. try
  288. {
  289. return _libraryManager.GetArtist(i);
  290. }
  291. catch
  292. {
  293. // Already logged at lower levels
  294. return null;
  295. }
  296. })
  297. .Where(i => i != null);
  298. return GetResult(artists, parent, query);
  299. }
  300. private QueryResult<BaseItem> GetMusicArtists(Folder parent, User user, InternalItemsQuery query)
  301. {
  302. var artists = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos })
  303. .Where(i => !i.IsFolder)
  304. .OfType<IHasArtist>()
  305. .SelectMany(i => i.Artists)
  306. .DistinctNames()
  307. .Select(i =>
  308. {
  309. try
  310. {
  311. return _libraryManager.GetArtist(i);
  312. }
  313. catch
  314. {
  315. // Already logged at lower levels
  316. return null;
  317. }
  318. })
  319. .Where(i => i != null);
  320. return GetResult(artists, parent, query);
  321. }
  322. private QueryResult<BaseItem> GetFavoriteArtists(Folder parent, User user, InternalItemsQuery query)
  323. {
  324. var artists = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos })
  325. .Where(i => !i.IsFolder)
  326. .OfType<IHasAlbumArtist>()
  327. .SelectMany(i => i.AlbumArtists)
  328. .DistinctNames()
  329. .Select(i =>
  330. {
  331. try
  332. {
  333. return _libraryManager.GetArtist(i);
  334. }
  335. catch
  336. {
  337. // Already logged at lower levels
  338. return null;
  339. }
  340. })
  341. .Where(i => i != null && _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite);
  342. return GetResult(artists, parent, query);
  343. }
  344. private Task<QueryResult<BaseItem>> GetMusicPlaylists(Folder parent, User user, InternalItemsQuery query)
  345. {
  346. query.IncludeItemTypes = new[] { "Playlist" };
  347. query.Recursive = true;
  348. return parent.GetItems(query);
  349. }
  350. private QueryResult<BaseItem> GetMusicAlbums(Folder parent, User user, InternalItemsQuery query)
  351. {
  352. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }, i => (i is MusicAlbum) && FilterItem(i, query));
  353. return PostFilterAndSort(items, parent, null, query);
  354. }
  355. private QueryResult<BaseItem> GetMusicSongs(Folder parent, User user, InternalItemsQuery query)
  356. {
  357. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }, i => (i is Audio.Audio) && FilterItem(i, query));
  358. return PostFilterAndSort(items, parent, null, query);
  359. }
  360. private QueryResult<BaseItem> GetMusicLatest(Folder parent, User user, InternalItemsQuery query)
  361. {
  362. var items = _userViewManager.GetLatestItems(new LatestItemsQuery
  363. {
  364. UserId = user.Id.ToString("N"),
  365. Limit = GetSpecialItemsLimit(),
  366. IncludeItemTypes = new[] { typeof(Audio.Audio).Name },
  367. ParentId = (parent == null ? null : parent.Id.ToString("N")),
  368. GroupItems = true
  369. }).Select(i => i.Item1 ?? i.Item2.FirstOrDefault()).Where(i => i != null);
  370. query.SortBy = new string[] { };
  371. //var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }, i => i is MusicVideo || i is Audio.Audio && FilterItem(i, query));
  372. return PostFilterAndSort(items, parent, null, query);
  373. }
  374. private async Task<QueryResult<BaseItem>> GetMovieFolders(Folder parent, User user, InternalItemsQuery query)
  375. {
  376. if (query.Recursive)
  377. {
  378. var recursiveItems = GetRecursiveChildren(parent, user,
  379. new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty })
  380. .Where(i => i is Movie || i is BoxSet);
  381. //var collections = _collectionManager.CollapseItemsWithinBoxSets(recursiveItems, user).ToList();
  382. //if (collections.Count > 0)
  383. //{
  384. // recursiveItems.AddRange(_collectionManager.CollapseItemsWithinBoxSets(recursiveItems, user));
  385. // recursiveItems = recursiveItems.DistinctBy(i => i.Id).ToList();
  386. //}
  387. return GetResult(recursiveItems, parent, query);
  388. }
  389. var list = new List<BaseItem>();
  390. list.Add(await GetUserView(SpecialFolder.MovieResume, user, "0", parent).ConfigureAwait(false));
  391. list.Add(await GetUserView(SpecialFolder.MovieLatest, user, "1", parent).ConfigureAwait(false));
  392. list.Add(await GetUserView(SpecialFolder.MovieMovies, user, "2", parent).ConfigureAwait(false));
  393. list.Add(await GetUserView(SpecialFolder.MovieCollections, user, "3", parent).ConfigureAwait(false));
  394. list.Add(await GetUserView(SpecialFolder.MovieFavorites, user, "4", parent).ConfigureAwait(false));
  395. list.Add(await GetUserView(SpecialFolder.MovieGenres, user, "5", parent).ConfigureAwait(false));
  396. return GetResult(list, parent, query);
  397. }
  398. private QueryResult<BaseItem> GetFavoriteMovies(Folder parent, User user, InternalItemsQuery query)
  399. {
  400. query.IsFavorite = true;
  401. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty }, i => (i is Movie) && FilterItem(i, query));
  402. return PostFilterAndSort(items, parent, null, query);
  403. }
  404. private QueryResult<BaseItem> GetFavoriteSeries(Folder parent, User user, InternalItemsQuery query)
  405. {
  406. query.IsFavorite = true;
  407. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => (i is Series) && FilterItem(i, query));
  408. return PostFilterAndSort(items, parent, null, query);
  409. }
  410. private QueryResult<BaseItem> GetFavoriteEpisodes(Folder parent, User user, InternalItemsQuery query)
  411. {
  412. query.IsFavorite = true;
  413. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => (i is Episode) && FilterItem(i, query));
  414. return PostFilterAndSort(items, parent, null, query);
  415. }
  416. private QueryResult<BaseItem> GetFavoriteSongs(Folder parent, User user, InternalItemsQuery query)
  417. {
  418. query.IsFavorite = true;
  419. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music }, i => (i is Audio.Audio) && FilterItem(i, query));
  420. return PostFilterAndSort(items, parent, null, query);
  421. }
  422. private QueryResult<BaseItem> GetFavoriteAlbums(Folder parent, User user, InternalItemsQuery query)
  423. {
  424. query.IsFavorite = true;
  425. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music }, i => (i is MusicAlbum) && FilterItem(i, query));
  426. return PostFilterAndSort(items, parent, null, query);
  427. }
  428. private QueryResult<BaseItem> GetMovieMovies(Folder parent, User user, InternalItemsQuery query)
  429. {
  430. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty }, i => (i is Movie) && FilterItem(i, query));
  431. return PostFilterAndSort(items, parent, null, query);
  432. }
  433. private QueryResult<BaseItem> GetMovieCollections(Folder parent, User user, InternalItemsQuery query)
  434. {
  435. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty }, i => (i is BoxSet) && FilterItem(i, query));
  436. return PostFilterAndSort(items, parent, null, query);
  437. }
  438. private QueryResult<BaseItem> GetMovieLatest(Folder parent, User user, InternalItemsQuery query)
  439. {
  440. query.SortBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName };
  441. query.SortOrder = SortOrder.Descending;
  442. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty }, i => i is Movie && FilterItem(i, query));
  443. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  444. }
  445. private QueryResult<BaseItem> GetMovieResume(Folder parent, User user, InternalItemsQuery query)
  446. {
  447. query.SortBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName };
  448. query.SortOrder = SortOrder.Descending;
  449. query.IsResumable = true;
  450. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty }, i => i is Movie && FilterItem(i, query));
  451. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  452. }
  453. private async Task<QueryResult<BaseItem>> GetMovieGenres(Folder parent, User user, InternalItemsQuery query)
  454. {
  455. var tasks = GetRecursiveChildren(parent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty })
  456. .Where(i => i is Movie)
  457. .SelectMany(i => i.Genres)
  458. .DistinctNames()
  459. .Select(i =>
  460. {
  461. try
  462. {
  463. return _libraryManager.GetGenre(i);
  464. }
  465. catch
  466. {
  467. // Full exception logged at lower levels
  468. _logger.Error("Error getting genre");
  469. return null;
  470. }
  471. })
  472. .Where(i => i != null)
  473. .Select(i => GetUserView(i.Name, SpecialFolder.MovieGenre, user, i.SortName, parent));
  474. var genres = await Task.WhenAll(tasks).ConfigureAwait(false);
  475. return GetResult(genres, parent, query);
  476. }
  477. private async Task<QueryResult<BaseItem>> GetMovieGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
  478. {
  479. var items = GetRecursiveChildren(queryParent, user, new[] { CollectionType.Movies, CollectionType.BoxSets, string.Empty })
  480. .Where(i => i is Movie)
  481. .Where(i => i.Genres.Contains(displayParent.Name, StringComparer.OrdinalIgnoreCase));
  482. return GetResult(items, queryParent, query);
  483. }
  484. private async Task<QueryResult<BaseItem>> GetPlaylistsView(Folder parent, User user, InternalItemsQuery query)
  485. {
  486. return GetResult(_playlistManager.GetPlaylists(user.Id.ToString("N")), parent, query);
  487. }
  488. private async Task<QueryResult<BaseItem>> GetBoxsetView(Folder parent, User user, InternalItemsQuery query)
  489. {
  490. return GetResult(GetMediaFolders(user).SelectMany(i =>
  491. {
  492. var hasCollectionType = i as ICollectionFolder;
  493. Func<BaseItem, bool> filter = b => b is BoxSet;
  494. if (hasCollectionType != null && string.Equals(hasCollectionType.CollectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase))
  495. {
  496. return i.GetChildren(user, true).Where(filter);
  497. }
  498. return i.GetRecursiveChildren(user, filter);
  499. }), parent, query);
  500. }
  501. private async Task<QueryResult<BaseItem>> GetTvView(Folder parent, User user, InternalItemsQuery query)
  502. {
  503. if (query.Recursive)
  504. {
  505. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => (i is Series || i is Season || i is Episode) && FilterItem(i, query));
  506. return PostFilterAndSort(items, parent, null, query);
  507. }
  508. var list = new List<BaseItem>();
  509. list.Add(await GetUserView(SpecialFolder.TvResume, user, "0", parent).ConfigureAwait(false));
  510. list.Add(await GetUserView(SpecialFolder.TvNextUp, user, "1", parent).ConfigureAwait(false));
  511. list.Add(await GetUserView(SpecialFolder.TvLatest, user, "2", parent).ConfigureAwait(false));
  512. list.Add(await GetUserView(SpecialFolder.TvShowSeries, user, "3", parent).ConfigureAwait(false));
  513. list.Add(await GetUserView(SpecialFolder.TvFavoriteSeries, user, "4", parent).ConfigureAwait(false));
  514. list.Add(await GetUserView(SpecialFolder.TvFavoriteEpisodes, user, "5", parent).ConfigureAwait(false));
  515. list.Add(await GetUserView(SpecialFolder.TvGenres, user, "6", parent).ConfigureAwait(false));
  516. return GetResult(list, parent, query);
  517. }
  518. private async Task<QueryResult<BaseItem>> GetGameView(User user, Folder parent, InternalItemsQuery query)
  519. {
  520. if (query.Recursive)
  521. {
  522. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Games }, i => FilterItem(i, query));
  523. return PostFilterAndSort(items, parent, null, query);
  524. }
  525. var list = new List<BaseItem>();
  526. list.Add(await GetUserView(SpecialFolder.LatestGames, user, "0", parent).ConfigureAwait(false));
  527. list.Add(await GetUserView(SpecialFolder.RecentlyPlayedGames, user, "1", parent).ConfigureAwait(false));
  528. list.Add(await GetUserView(SpecialFolder.GameFavorites, user, "2", parent).ConfigureAwait(false));
  529. list.Add(await GetUserView(SpecialFolder.GameSystems, user, "3", parent).ConfigureAwait(false));
  530. list.Add(await GetUserView(SpecialFolder.GameGenres, user, "4", parent).ConfigureAwait(false));
  531. return GetResult(list, parent, query);
  532. }
  533. private QueryResult<BaseItem> GetLatestGames(Folder parent, User user, InternalItemsQuery query)
  534. {
  535. query.SortBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName };
  536. query.SortOrder = SortOrder.Descending;
  537. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Games }, i => i is Game && FilterItem(i, query));
  538. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  539. }
  540. private QueryResult<BaseItem> GetRecentlyPlayedGames(Folder parent, User user, InternalItemsQuery query)
  541. {
  542. query.IsPlayed = true;
  543. query.SortBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName };
  544. query.SortOrder = SortOrder.Descending;
  545. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Games }, i => i is Game && FilterItem(i, query));
  546. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  547. }
  548. private QueryResult<BaseItem> GetFavoriteGames(Folder parent, User user, InternalItemsQuery query)
  549. {
  550. query.IsFavorite = true;
  551. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Games }, i => i is Game && FilterItem(i, query));
  552. return PostFilterAndSort(items, parent, null, query);
  553. }
  554. private QueryResult<BaseItem> GetTvLatest(Folder parent, User user, InternalItemsQuery query)
  555. {
  556. query.SortBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName };
  557. query.SortOrder = SortOrder.Descending;
  558. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => i is Episode && FilterItem(i, query));
  559. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  560. }
  561. private QueryResult<BaseItem> GetTvNextUp(Folder parent, InternalItemsQuery query)
  562. {
  563. var parentFolders = GetMediaFolders(parent, query.User, new[] { CollectionType.TvShows, string.Empty });
  564. var result = _tvSeriesManager.GetNextUp(new NextUpQuery
  565. {
  566. Limit = query.Limit,
  567. StartIndex = query.StartIndex,
  568. UserId = query.User.Id.ToString("N")
  569. }, parentFolders);
  570. return result;
  571. }
  572. private QueryResult<BaseItem> GetTvResume(Folder parent, User user, InternalItemsQuery query)
  573. {
  574. query.SortBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName };
  575. query.SortOrder = SortOrder.Descending;
  576. query.IsResumable = true;
  577. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => i is Episode && FilterItem(i, query));
  578. return PostFilterAndSort(items, parent, GetSpecialItemsLimit(), query);
  579. }
  580. private QueryResult<BaseItem> GetTvSeries(Folder parent, User user, InternalItemsQuery query)
  581. {
  582. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty }, i => i is Series && FilterItem(i, query));
  583. return PostFilterAndSort(items, parent, null, query);
  584. }
  585. private async Task<QueryResult<BaseItem>> GetTvGenres(Folder parent, User user, InternalItemsQuery query)
  586. {
  587. var tasks = GetRecursiveChildren(parent, user, new[] { CollectionType.TvShows, string.Empty })
  588. .OfType<Series>()
  589. .SelectMany(i => i.Genres)
  590. .DistinctNames()
  591. .Select(i =>
  592. {
  593. try
  594. {
  595. return _libraryManager.GetGenre(i);
  596. }
  597. catch
  598. {
  599. // Full exception logged at lower levels
  600. _logger.Error("Error getting genre");
  601. return null;
  602. }
  603. })
  604. .Where(i => i != null)
  605. .Select(i => GetUserView(i.Name, SpecialFolder.TvGenre, user, i.SortName, parent));
  606. var genres = await Task.WhenAll(tasks).ConfigureAwait(false);
  607. return GetResult(genres, parent, query);
  608. }
  609. private async Task<QueryResult<BaseItem>> GetTvGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
  610. {
  611. var items = GetRecursiveChildren(queryParent, user, new[] { CollectionType.TvShows, string.Empty })
  612. .Where(i => i is Series)
  613. .Where(i => i.Genres.Contains(displayParent.Name, StringComparer.OrdinalIgnoreCase));
  614. return GetResult(items, queryParent, query);
  615. }
  616. private QueryResult<BaseItem> GetGameSystems(Folder parent, User user, InternalItemsQuery query)
  617. {
  618. var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Games }, i => i is GameSystem && FilterItem(i, query));
  619. return PostFilterAndSort(items, parent, null, query);
  620. }
  621. private async Task<QueryResult<BaseItem>> GetGameGenreItems(Folder queryParent, Folder displayParent, User user, InternalItemsQuery query)
  622. {
  623. var items = GetRecursiveChildren(queryParent, user, new[] { CollectionType.Games },
  624. i => i is Game && i.Genres.Contains(displayParent.Name, StringComparer.OrdinalIgnoreCase));
  625. return GetResult(items, queryParent, query);
  626. }
  627. private async Task<QueryResult<BaseItem>> GetGameGenres(Folder parent, User user, InternalItemsQuery query)
  628. {
  629. var tasks = GetRecursiveChildren(parent, user, new[] { CollectionType.Games })
  630. .OfType<Game>()
  631. .SelectMany(i => i.Genres)
  632. .DistinctNames()
  633. .Select(i =>
  634. {
  635. try
  636. {
  637. return _libraryManager.GetGameGenre(i);
  638. }
  639. catch
  640. {
  641. // Full exception logged at lower levels
  642. _logger.Error("Error getting game genre");
  643. return null;
  644. }
  645. })
  646. .Where(i => i != null)
  647. .Select(i => GetUserView(i.Name, SpecialFolder.GameGenre, user, i.SortName, parent));
  648. var genres = await Task.WhenAll(tasks).ConfigureAwait(false);
  649. return GetResult(genres, parent, query);
  650. }
  651. private QueryResult<BaseItem> GetResult<T>(QueryResult<T> result)
  652. where T : BaseItem
  653. {
  654. return new QueryResult<BaseItem>
  655. {
  656. Items = result.Items,
  657. TotalRecordCount = result.TotalRecordCount
  658. };
  659. }
  660. private QueryResult<BaseItem> GetResult<T>(IEnumerable<T> items,
  661. BaseItem queryParent,
  662. InternalItemsQuery query)
  663. where T : BaseItem
  664. {
  665. items = items.Where(i => Filter(i, query.User, query, _userDataManager, _libraryManager));
  666. return PostFilterAndSort(items, queryParent, null, query, _libraryManager);
  667. }
  668. public bool FilterItem(BaseItem item, InternalItemsQuery query)
  669. {
  670. return Filter(item, query.User, query, _userDataManager, _libraryManager);
  671. }
  672. private QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items,
  673. BaseItem queryParent,
  674. int? totalRecordLimit,
  675. InternalItemsQuery query)
  676. {
  677. return PostFilterAndSort(items, queryParent, totalRecordLimit, query, _libraryManager);
  678. }
  679. public static QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items,
  680. BaseItem queryParent,
  681. int? totalRecordLimit,
  682. InternalItemsQuery query,
  683. ILibraryManager libraryManager)
  684. {
  685. var user = query.User;
  686. items = FilterVirtualEpisodes(items,
  687. query.IsMissing,
  688. query.IsVirtualUnaired,
  689. query.IsUnaired);
  690. items = CollapseBoxSetItemsIfNeeded(items, query, queryParent, user);
  691. // This must be the last filter
  692. if (!string.IsNullOrEmpty(query.AdjacentTo))
  693. {
  694. items = FilterForAdjacency(items, query.AdjacentTo);
  695. }
  696. return Sort(items, totalRecordLimit, query, libraryManager);
  697. }
  698. public static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(IEnumerable<BaseItem> items,
  699. InternalItemsQuery query,
  700. BaseItem queryParent,
  701. User user)
  702. {
  703. if (items == null)
  704. {
  705. throw new ArgumentNullException("items");
  706. }
  707. if (CollapseBoxSetItems(query, queryParent, user))
  708. {
  709. items = BaseItem.CollectionManager.CollapseItemsWithinBoxSets(items, user);
  710. }
  711. items = ApplyPostCollectionCollapseFilters(query, items, user);
  712. return items;
  713. }
  714. private static IEnumerable<BaseItem> ApplyPostCollectionCollapseFilters(InternalItemsQuery request,
  715. IEnumerable<BaseItem> items,
  716. User user)
  717. {
  718. if (!string.IsNullOrEmpty(request.NameStartsWithOrGreater))
  719. {
  720. items = items.Where(i => string.Compare(request.NameStartsWithOrGreater, i.SortName, StringComparison.CurrentCultureIgnoreCase) < 1);
  721. }
  722. if (!string.IsNullOrEmpty(request.NameStartsWith))
  723. {
  724. items = items.Where(i => string.Compare(request.NameStartsWith, i.SortName.Substring(0, 1), StringComparison.CurrentCultureIgnoreCase) == 0);
  725. }
  726. if (!string.IsNullOrEmpty(request.NameLessThan))
  727. {
  728. items = items.Where(i => string.Compare(request.NameLessThan, i.SortName, StringComparison.CurrentCultureIgnoreCase) == 1);
  729. }
  730. return items;
  731. }
  732. private static bool CollapseBoxSetItems(InternalItemsQuery query,
  733. BaseItem queryParent,
  734. User user)
  735. {
  736. // Could end up stuck in a loop like this
  737. if (queryParent is BoxSet)
  738. {
  739. return false;
  740. }
  741. var param = query.CollapseBoxSetItems;
  742. if (!param.HasValue)
  743. {
  744. if (user != null && !user.Configuration.GroupMoviesIntoBoxSets)
  745. {
  746. return false;
  747. }
  748. if (query.IncludeItemTypes.Contains("Movie", StringComparer.OrdinalIgnoreCase))
  749. {
  750. param = true;
  751. }
  752. }
  753. return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
  754. }
  755. private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
  756. {
  757. if (request.IsFavorite.HasValue)
  758. {
  759. return false;
  760. }
  761. if (request.IsFavoriteOrLiked.HasValue)
  762. {
  763. return false;
  764. }
  765. if (request.IsLiked.HasValue)
  766. {
  767. return false;
  768. }
  769. if (request.IsPlayed.HasValue)
  770. {
  771. return false;
  772. }
  773. if (request.IsResumable.HasValue)
  774. {
  775. return false;
  776. }
  777. if (request.IsFolder.HasValue)
  778. {
  779. return false;
  780. }
  781. if (request.Genres.Length > 0)
  782. {
  783. return false;
  784. }
  785. if (request.HasImdbId.HasValue)
  786. {
  787. return false;
  788. }
  789. if (request.HasOfficialRating.HasValue)
  790. {
  791. return false;
  792. }
  793. if (request.HasOverview.HasValue)
  794. {
  795. return false;
  796. }
  797. if (request.HasParentalRating.HasValue)
  798. {
  799. return false;
  800. }
  801. if (request.HasSpecialFeature.HasValue)
  802. {
  803. return false;
  804. }
  805. if (request.HasSubtitles.HasValue)
  806. {
  807. return false;
  808. }
  809. if (request.HasThemeSong.HasValue)
  810. {
  811. return false;
  812. }
  813. if (request.HasThemeVideo.HasValue)
  814. {
  815. return false;
  816. }
  817. if (request.HasTmdbId.HasValue)
  818. {
  819. return false;
  820. }
  821. if (request.HasTrailer.HasValue)
  822. {
  823. return false;
  824. }
  825. if (request.ImageTypes.Length > 0)
  826. {
  827. return false;
  828. }
  829. if (request.Is3D.HasValue)
  830. {
  831. return false;
  832. }
  833. if (request.IsHD.HasValue)
  834. {
  835. return false;
  836. }
  837. if (request.IsInBoxSet.HasValue)
  838. {
  839. return false;
  840. }
  841. if (request.IsLocked.HasValue)
  842. {
  843. return false;
  844. }
  845. if (request.IsPlaceHolder.HasValue)
  846. {
  847. return false;
  848. }
  849. if (request.IsPlayed.HasValue)
  850. {
  851. return false;
  852. }
  853. if (request.IsUnidentified.HasValue)
  854. {
  855. return false;
  856. }
  857. if (request.IsYearMismatched.HasValue)
  858. {
  859. return false;
  860. }
  861. if (!string.IsNullOrWhiteSpace(request.Person))
  862. {
  863. return false;
  864. }
  865. if (request.PersonIds.Length > 0)
  866. {
  867. return false;
  868. }
  869. if (request.Studios.Length > 0)
  870. {
  871. return false;
  872. }
  873. if (request.StudioIds.Length > 0)
  874. {
  875. return false;
  876. }
  877. if (request.VideoTypes.Length > 0)
  878. {
  879. return false;
  880. }
  881. if (request.Years.Length > 0)
  882. {
  883. return false;
  884. }
  885. if (request.Tags.Length > 0)
  886. {
  887. return false;
  888. }
  889. if (request.OfficialRatings.Length > 0)
  890. {
  891. return false;
  892. }
  893. return true;
  894. }
  895. public static IEnumerable<BaseItem> FilterVirtualEpisodes(
  896. IEnumerable<BaseItem> items,
  897. bool? isMissing,
  898. bool? isVirtualUnaired,
  899. bool? isUnaired)
  900. {
  901. items = FilterVirtualSeasons(items, isMissing, isVirtualUnaired, isUnaired);
  902. if (isMissing.HasValue)
  903. {
  904. var val = isMissing.Value;
  905. items = items.Where(i =>
  906. {
  907. var e = i as Episode;
  908. if (e != null)
  909. {
  910. return e.IsMissingEpisode == val;
  911. }
  912. return true;
  913. });
  914. }
  915. if (isUnaired.HasValue)
  916. {
  917. var val = isUnaired.Value;
  918. items = items.Where(i =>
  919. {
  920. var e = i as Episode;
  921. if (e != null)
  922. {
  923. return e.IsUnaired == val;
  924. }
  925. return true;
  926. });
  927. }
  928. if (isVirtualUnaired.HasValue)
  929. {
  930. var val = isVirtualUnaired.Value;
  931. items = items.Where(i =>
  932. {
  933. var e = i as Episode;
  934. if (e != null)
  935. {
  936. return e.IsVirtualUnaired == val;
  937. }
  938. return true;
  939. });
  940. }
  941. return items;
  942. }
  943. private static IEnumerable<BaseItem> FilterVirtualSeasons(
  944. IEnumerable<BaseItem> items,
  945. bool? isMissing,
  946. bool? isVirtualUnaired,
  947. bool? isUnaired)
  948. {
  949. if (isMissing.HasValue && isVirtualUnaired.HasValue)
  950. {
  951. if (!isMissing.Value && !isVirtualUnaired.Value)
  952. {
  953. return items.Where(i =>
  954. {
  955. var e = i as Season;
  956. if (e != null)
  957. {
  958. return !e.IsMissingOrVirtualUnaired;
  959. }
  960. return true;
  961. });
  962. }
  963. }
  964. if (isMissing.HasValue)
  965. {
  966. var val = isMissing.Value;
  967. items = items.Where(i =>
  968. {
  969. var e = i as Season;
  970. if (e != null)
  971. {
  972. return e.IsMissingSeason == val;
  973. }
  974. return true;
  975. });
  976. }
  977. if (isUnaired.HasValue)
  978. {
  979. var val = isUnaired.Value;
  980. items = items.Where(i =>
  981. {
  982. var e = i as Season;
  983. if (e != null)
  984. {
  985. return e.IsUnaired == val;
  986. }
  987. return true;
  988. });
  989. }
  990. if (isVirtualUnaired.HasValue)
  991. {
  992. var val = isVirtualUnaired.Value;
  993. items = items.Where(i =>
  994. {
  995. var e = i as Season;
  996. if (e != null)
  997. {
  998. return e.IsVirtualUnaired == val;
  999. }
  1000. return true;
  1001. });
  1002. }
  1003. return items;
  1004. }
  1005. public static QueryResult<BaseItem> Sort(IEnumerable<BaseItem> items,
  1006. int? totalRecordLimit,
  1007. InternalItemsQuery query,
  1008. ILibraryManager libraryManager)
  1009. {
  1010. var user = query.User;
  1011. items = libraryManager.ReplaceVideosWithPrimaryVersions(items);
  1012. if (query.SortBy.Length > 0)
  1013. {
  1014. items = libraryManager.Sort(items, user, query.SortBy, query.SortOrder);
  1015. }
  1016. var itemsArray = totalRecordLimit.HasValue ? items.Take(totalRecordLimit.Value).ToArray() : items.ToArray();
  1017. var totalCount = itemsArray.Length;
  1018. if (query.Limit.HasValue)
  1019. {
  1020. itemsArray = itemsArray.Skip(query.StartIndex ?? 0).Take(query.Limit.Value).ToArray();
  1021. }
  1022. else if (query.StartIndex.HasValue)
  1023. {
  1024. itemsArray = itemsArray.Skip(query.StartIndex.Value).ToArray();
  1025. }
  1026. return new QueryResult<BaseItem>
  1027. {
  1028. TotalRecordCount = totalCount,
  1029. Items = itemsArray
  1030. };
  1031. }
  1032. public static bool Filter(BaseItem item, User user, InternalItemsQuery query, IUserDataManager userDataManager, ILibraryManager libraryManager)
  1033. {
  1034. if (query.MediaTypes.Length > 0 && !query.MediaTypes.Contains(item.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  1035. {
  1036. return false;
  1037. }
  1038. if (query.IncludeItemTypes.Length > 0 && !query.IncludeItemTypes.Contains(item.GetClientTypeName(), StringComparer.OrdinalIgnoreCase))
  1039. {
  1040. return false;
  1041. }
  1042. if (query.ExcludeItemTypes.Length > 0 && query.ExcludeItemTypes.Contains(item.GetClientTypeName(), StringComparer.OrdinalIgnoreCase))
  1043. {
  1044. return false;
  1045. }
  1046. if (query.IsFolder.HasValue && query.IsFolder.Value != item.IsFolder)
  1047. {
  1048. return false;
  1049. }
  1050. if (query.Filter != null && !query.Filter(item))
  1051. {
  1052. return false;
  1053. }
  1054. UserItemData userData = null;
  1055. if (query.IsLiked.HasValue)
  1056. {
  1057. userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1058. if (!userData.Likes.HasValue || userData.Likes != query.IsLiked.Value)
  1059. {
  1060. return false;
  1061. }
  1062. }
  1063. if (query.IsFavoriteOrLiked.HasValue)
  1064. {
  1065. userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1066. var isFavoriteOrLiked = userData.IsFavorite || (userData.Likes ?? false);
  1067. if (isFavoriteOrLiked != query.IsFavoriteOrLiked.Value)
  1068. {
  1069. return false;
  1070. }
  1071. }
  1072. if (query.IsFavorite.HasValue)
  1073. {
  1074. userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1075. if (userData.IsFavorite != query.IsFavorite.Value)
  1076. {
  1077. return false;
  1078. }
  1079. }
  1080. if (query.IsResumable.HasValue)
  1081. {
  1082. userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1083. var isResumable = userData.PlaybackPositionTicks > 0;
  1084. if (isResumable != query.IsResumable.Value)
  1085. {
  1086. return false;
  1087. }
  1088. }
  1089. if (query.IsPlayed.HasValue)
  1090. {
  1091. if (item.IsPlayed(user) != query.IsPlayed.Value)
  1092. {
  1093. return false;
  1094. }
  1095. }
  1096. if (query.IsInBoxSet.HasValue)
  1097. {
  1098. var val = query.IsInBoxSet.Value;
  1099. if (item.Parents.OfType<BoxSet>().Any() != val)
  1100. {
  1101. return false;
  1102. }
  1103. }
  1104. // Filter by Video3DFormat
  1105. if (query.Is3D.HasValue)
  1106. {
  1107. var val = query.Is3D.Value;
  1108. var video = item as Video;
  1109. if (video == null || val != video.Video3DFormat.HasValue)
  1110. {
  1111. return false;
  1112. }
  1113. }
  1114. if (query.IsHD.HasValue)
  1115. {
  1116. var val = query.IsHD.Value;
  1117. var video = item as Video;
  1118. if (video == null || val != video.IsHD)
  1119. {
  1120. return false;
  1121. }
  1122. }
  1123. if (query.IsUnidentified.HasValue)
  1124. {
  1125. var val = query.IsUnidentified.Value;
  1126. if (item.IsUnidentified != val)
  1127. {
  1128. return false;
  1129. }
  1130. }
  1131. if (query.IsLocked.HasValue)
  1132. {
  1133. var val = query.IsLocked.Value;
  1134. if (item.IsLocked != val)
  1135. {
  1136. return false;
  1137. }
  1138. }
  1139. if (query.HasOverview.HasValue)
  1140. {
  1141. var filterValue = query.HasOverview.Value;
  1142. var hasValue = !string.IsNullOrEmpty(item.Overview);
  1143. if (hasValue != filterValue)
  1144. {
  1145. return false;
  1146. }
  1147. }
  1148. if (query.HasImdbId.HasValue)
  1149. {
  1150. var filterValue = query.HasImdbId.Value;
  1151. var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Imdb));
  1152. if (hasValue != filterValue)
  1153. {
  1154. return false;
  1155. }
  1156. }
  1157. if (query.HasTmdbId.HasValue)
  1158. {
  1159. var filterValue = query.HasTmdbId.Value;
  1160. var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb));
  1161. if (hasValue != filterValue)
  1162. {
  1163. return false;
  1164. }
  1165. }
  1166. if (query.HasTvdbId.HasValue)
  1167. {
  1168. var filterValue = query.HasTvdbId.Value;
  1169. var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tvdb));
  1170. if (hasValue != filterValue)
  1171. {
  1172. return false;
  1173. }
  1174. }
  1175. if (query.IsYearMismatched.HasValue)
  1176. {
  1177. var filterValue = query.IsYearMismatched.Value;
  1178. if (IsYearMismatched(item, libraryManager) != filterValue)
  1179. {
  1180. return false;
  1181. }
  1182. }
  1183. if (query.HasOfficialRating.HasValue)
  1184. {
  1185. var filterValue = query.HasOfficialRating.Value;
  1186. var hasValue = !string.IsNullOrEmpty(item.OfficialRating);
  1187. if (hasValue != filterValue)
  1188. {
  1189. return false;
  1190. }
  1191. }
  1192. if (query.IsPlaceHolder.HasValue)
  1193. {
  1194. var filterValue = query.IsPlaceHolder.Value;
  1195. var isPlaceHolder = false;
  1196. var hasPlaceHolder = item as ISupportsPlaceHolders;
  1197. if (hasPlaceHolder != null)
  1198. {
  1199. isPlaceHolder = hasPlaceHolder.IsPlaceHolder;
  1200. }
  1201. if (isPlaceHolder != filterValue)
  1202. {
  1203. return false;
  1204. }
  1205. }
  1206. if (query.HasSpecialFeature.HasValue)
  1207. {
  1208. var filterValue = query.HasSpecialFeature.Value;
  1209. var movie = item as IHasSpecialFeatures;
  1210. if (movie != null)
  1211. {
  1212. var ok = filterValue
  1213. ? movie.SpecialFeatureIds.Count > 0
  1214. : movie.SpecialFeatureIds.Count == 0;
  1215. if (!ok)
  1216. {
  1217. return false;
  1218. }
  1219. }
  1220. else
  1221. {
  1222. return false;
  1223. }
  1224. }
  1225. if (query.HasSubtitles.HasValue)
  1226. {
  1227. var val = query.HasSubtitles.Value;
  1228. var video = item as Video;
  1229. if (video == null || val != video.HasSubtitles)
  1230. {
  1231. return false;
  1232. }
  1233. }
  1234. if (query.HasParentalRating.HasValue)
  1235. {
  1236. var val = query.HasParentalRating.Value;
  1237. var rating = item.CustomRating;
  1238. if (string.IsNullOrEmpty(rating))
  1239. {
  1240. rating = item.OfficialRating;
  1241. }
  1242. if (val)
  1243. {
  1244. if (string.IsNullOrEmpty(rating))
  1245. {
  1246. return false;
  1247. }
  1248. }
  1249. else
  1250. {
  1251. if (!string.IsNullOrEmpty(rating))
  1252. {
  1253. return false;
  1254. }
  1255. }
  1256. }
  1257. if (query.HasTrailer.HasValue)
  1258. {
  1259. var val = query.HasTrailer.Value;
  1260. var trailerCount = 0;
  1261. var hasTrailers = item as IHasTrailers;
  1262. if (hasTrailers != null)
  1263. {
  1264. trailerCount = hasTrailers.GetTrailerIds().Count;
  1265. }
  1266. var ok = val ? trailerCount > 0 : trailerCount == 0;
  1267. if (!ok)
  1268. {
  1269. return false;
  1270. }
  1271. }
  1272. if (query.HasThemeSong.HasValue)
  1273. {
  1274. var filterValue = query.HasThemeSong.Value;
  1275. var themeCount = 0;
  1276. var iHasThemeMedia = item as IHasThemeMedia;
  1277. if (iHasThemeMedia != null)
  1278. {
  1279. themeCount = iHasThemeMedia.ThemeSongIds.Count;
  1280. }
  1281. var ok = filterValue ? themeCount > 0 : themeCount == 0;
  1282. if (!ok)
  1283. {
  1284. return false;
  1285. }
  1286. }
  1287. if (query.HasThemeVideo.HasValue)
  1288. {
  1289. var filterValue = query.HasThemeVideo.Value;
  1290. var themeCount = 0;
  1291. var iHasThemeMedia = item as IHasThemeMedia;
  1292. if (iHasThemeMedia != null)
  1293. {
  1294. themeCount = iHasThemeMedia.ThemeVideoIds.Count;
  1295. }
  1296. var ok = filterValue ? themeCount > 0 : themeCount == 0;
  1297. if (!ok)
  1298. {
  1299. return false;
  1300. }
  1301. }
  1302. // Apply genre filter
  1303. if (query.Genres.Length > 0 && !(query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase))))
  1304. {
  1305. return false;
  1306. }
  1307. // Filter by VideoType
  1308. if (query.VideoTypes.Length > 0)
  1309. {
  1310. var video = item as Video;
  1311. if (video == null || !query.VideoTypes.Contains(video.VideoType))
  1312. {
  1313. return false;
  1314. }
  1315. }
  1316. if (query.ImageTypes.Length > 0 && !query.ImageTypes.Any(item.HasImage))
  1317. {
  1318. return false;
  1319. }
  1320. // Apply studio filter
  1321. if (query.Studios.Length > 0 && !query.Studios.Any(v => item.Studios.Contains(v, StringComparer.OrdinalIgnoreCase)))
  1322. {
  1323. return false;
  1324. }
  1325. // Apply studio filter
  1326. if (query.StudioIds.Length > 0 && !query.StudioIds.Any(id =>
  1327. {
  1328. var studioItem = libraryManager.GetItemById(id);
  1329. return studioItem != null && item.Studios.Contains(studioItem.Name, StringComparer.OrdinalIgnoreCase);
  1330. }))
  1331. {
  1332. return false;
  1333. }
  1334. // Apply year filter
  1335. if (query.Years.Length > 0)
  1336. {
  1337. if (!(item.ProductionYear.HasValue && query.Years.Contains(item.ProductionYear.Value)))
  1338. {
  1339. return false;
  1340. }
  1341. }
  1342. // Apply official rating filter
  1343. if (query.OfficialRatings.Length > 0 && !query.OfficialRatings.Contains(item.OfficialRating ?? string.Empty))
  1344. {
  1345. return false;
  1346. }
  1347. // Apply person filter
  1348. if (query.PersonIds.Length > 0)
  1349. {
  1350. var names = query.PersonIds
  1351. .Select(libraryManager.GetItemById)
  1352. .Select(i => i == null ? "-1" : i.Name)
  1353. .ToList();
  1354. if (!(names.Any(
  1355. v => item.People.Select(i => i.Name).Contains(v, StringComparer.OrdinalIgnoreCase))))
  1356. {
  1357. return false;
  1358. }
  1359. }
  1360. // Apply person filter
  1361. if (!string.IsNullOrWhiteSpace(query.Person))
  1362. {
  1363. var personTypes = query.PersonTypes;
  1364. if (personTypes.Length == 0)
  1365. {
  1366. if (!(item.People.Any(p => string.Equals(p.Name, query.Person, StringComparison.OrdinalIgnoreCase))))
  1367. {
  1368. return false;
  1369. }
  1370. }
  1371. else
  1372. {
  1373. var types = personTypes;
  1374. var ok = new[] { item }.Any(i =>
  1375. i.People != null &&
  1376. i.People.Any(p =>
  1377. string.Equals(p.Name, query.Person, StringComparison.OrdinalIgnoreCase) && (types.Contains(p.Type ?? string.Empty, StringComparer.OrdinalIgnoreCase) || types.Contains(p.Role ?? string.Empty, StringComparer.OrdinalIgnoreCase))));
  1378. if (!ok)
  1379. {
  1380. return false;
  1381. }
  1382. }
  1383. }
  1384. // Apply tag filter
  1385. var tags = query.Tags;
  1386. if (tags.Length > 0)
  1387. {
  1388. var hasTags = item as IHasTags;
  1389. if (hasTags == null)
  1390. {
  1391. return false;
  1392. }
  1393. if (!(tags.Any(v => hasTags.Tags.Contains(v, StringComparer.OrdinalIgnoreCase))))
  1394. {
  1395. return false;
  1396. }
  1397. }
  1398. return true;
  1399. }
  1400. private IEnumerable<Folder> GetMediaFolders(User user)
  1401. {
  1402. var excludeFolderIds = user.Configuration.ExcludeFoldersFromGrouping.Select(i => new Guid(i)).ToList();
  1403. return user.RootFolder
  1404. .GetChildren(user, true, true)
  1405. .OfType<Folder>()
  1406. .Where(i => !excludeFolderIds.Contains(i.Id) && !UserView.IsExcludedFromGrouping(i));
  1407. }
  1408. private IEnumerable<Folder> GetMediaFolders(User user, IEnumerable<string> viewTypes)
  1409. {
  1410. return GetMediaFolders(user)
  1411. .Where(i =>
  1412. {
  1413. var folder = i as ICollectionFolder;
  1414. return folder != null && viewTypes.Contains(folder.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
  1415. });
  1416. }
  1417. private IEnumerable<Folder> GetMediaFolders(Folder parent, User user, IEnumerable<string> viewTypes)
  1418. {
  1419. if (parent == null || parent is UserView)
  1420. {
  1421. return GetMediaFolders(user, viewTypes);
  1422. }
  1423. return new[] { parent };
  1424. }
  1425. private IEnumerable<BaseItem> GetRecursiveChildren(Folder parent, User user, IEnumerable<string> viewTypes)
  1426. {
  1427. if (parent == null || parent is UserView)
  1428. {
  1429. return GetMediaFolders(user, viewTypes).SelectMany(i => i.GetRecursiveChildren(user));
  1430. }
  1431. return parent.GetRecursiveChildren(user);
  1432. }
  1433. private IEnumerable<BaseItem> GetRecursiveChildren(Folder parent, User user, IEnumerable<string> viewTypes, Func<BaseItem, bool> filter)
  1434. {
  1435. if (parent == null || parent is UserView)
  1436. {
  1437. return GetMediaFolders(user, viewTypes).SelectMany(i => i.GetRecursiveChildren(user, filter));
  1438. }
  1439. return parent.GetRecursiveChildren(user, filter);
  1440. }
  1441. private async Task<QueryResult<BaseItem>> GetLiveTvView(Folder queryParent, User user, InternalItemsQuery query)
  1442. {
  1443. if (query.Recursive)
  1444. {
  1445. return await _liveTvManager.GetInternalRecordings(new RecordingQuery
  1446. {
  1447. IsInProgress = false,
  1448. Status = RecordingStatus.Completed,
  1449. UserId = user.Id.ToString("N")
  1450. }, CancellationToken.None).ConfigureAwait(false);
  1451. }
  1452. var list = new List<BaseItem>();
  1453. //list.Add(await GetUserSubView(SpecialFolder.LiveTvNowPlaying, user, "0", parent).ConfigureAwait(false));
  1454. list.Add(await GetUserView(SpecialFolder.LiveTvChannels, user, string.Empty, user.RootFolder).ConfigureAwait(false));
  1455. list.Add(await GetUserView(SpecialFolder.LiveTvRecordingGroups, user, string.Empty, user.RootFolder).ConfigureAwait(false));
  1456. return GetResult(list, queryParent, query);
  1457. }
  1458. private async Task<UserView> GetUserView(string name, string type, User user, string sortName, BaseItem parent)
  1459. {
  1460. var view = await _userViewManager.GetUserSubView(name, parent.Id.ToString("N"), type, user, sortName, CancellationToken.None)
  1461. .ConfigureAwait(false);
  1462. return view;
  1463. }
  1464. private async Task<UserView> GetUserView(string type, User user, string sortName, BaseItem parent)
  1465. {
  1466. var view = await _userViewManager.GetUserSubView(parent.Id.ToString("N"), type, user, sortName, CancellationToken.None)
  1467. .ConfigureAwait(false);
  1468. return view;
  1469. }
  1470. public static bool IsYearMismatched(BaseItem item, ILibraryManager libraryManager)
  1471. {
  1472. if (item.ProductionYear.HasValue)
  1473. {
  1474. var path = item.Path;
  1475. if (!string.IsNullOrEmpty(path))
  1476. {
  1477. var info = libraryManager.ParseName(Path.GetFileName(path));
  1478. var yearInName = info.Year;
  1479. // Go up a level if we didn't get a year
  1480. if (!yearInName.HasValue)
  1481. {
  1482. info = libraryManager.ParseName(Path.GetFileName(Path.GetDirectoryName(path)));
  1483. yearInName = info.Year;
  1484. }
  1485. if (yearInName.HasValue)
  1486. {
  1487. return yearInName.Value != item.ProductionYear.Value;
  1488. }
  1489. }
  1490. }
  1491. return false;
  1492. }
  1493. public static IEnumerable<BaseItem> FilterForAdjacency(IEnumerable<BaseItem> items, string adjacentToId)
  1494. {
  1495. var list = items.ToList();
  1496. var adjacentToIdGuid = new Guid(adjacentToId);
  1497. var adjacentToItem = list.FirstOrDefault(i => i.Id == adjacentToIdGuid);
  1498. var index = list.IndexOf(adjacentToItem);
  1499. var previousId = Guid.Empty;
  1500. var nextId = Guid.Empty;
  1501. if (index > 0)
  1502. {
  1503. previousId = list[index - 1].Id;
  1504. }
  1505. if (index < list.Count - 1)
  1506. {
  1507. nextId = list[index + 1].Id;
  1508. }
  1509. return list.Where(i => i.Id == previousId || i.Id == nextId || i.Id == adjacentToIdGuid);
  1510. }
  1511. }
  1512. }