ItemsController.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Globalization;
  4. using System.Linq;
  5. using Jellyfin.Api.Constants;
  6. using Jellyfin.Api.Extensions;
  7. using Jellyfin.Api.Helpers;
  8. using Jellyfin.Api.ModelBinders;
  9. using Jellyfin.Data.Enums;
  10. using MediaBrowser.Controller.Dto;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Entities.Audio;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Globalization;
  17. using MediaBrowser.Model.Querying;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Microsoft.AspNetCore.Http;
  20. using Microsoft.AspNetCore.Mvc;
  21. using Microsoft.Extensions.Logging;
  22. namespace Jellyfin.Api.Controllers
  23. {
  24. /// <summary>
  25. /// The items controller.
  26. /// </summary>
  27. [Route("")]
  28. [Authorize(Policy = Policies.DefaultAuthorization)]
  29. public class ItemsController : BaseJellyfinApiController
  30. {
  31. private readonly IUserManager _userManager;
  32. private readonly ILibraryManager _libraryManager;
  33. private readonly ILocalizationManager _localization;
  34. private readonly IDtoService _dtoService;
  35. private readonly ILogger<ItemsController> _logger;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="ItemsController"/> class.
  38. /// </summary>
  39. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  40. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  41. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  42. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  43. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  44. public ItemsController(
  45. IUserManager userManager,
  46. ILibraryManager libraryManager,
  47. ILocalizationManager localization,
  48. IDtoService dtoService,
  49. ILogger<ItemsController> logger)
  50. {
  51. _userManager = userManager;
  52. _libraryManager = libraryManager;
  53. _localization = localization;
  54. _dtoService = dtoService;
  55. _logger = logger;
  56. }
  57. /// <summary>
  58. /// Gets items based on a query.
  59. /// </summary>
  60. /// <param name="uId">The user id supplied in the /Users/{uid}/Items.</param>
  61. /// <param name="userId">The user id supplied as query parameter.</param>
  62. /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
  63. /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
  64. /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
  65. /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
  66. /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
  67. /// <param name="hasTrailer">Optional filter by items with trailers.</param>
  68. /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
  69. /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
  70. /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
  71. /// <param name="isHd">Optional filter by items that are HD or not.</param>
  72. /// <param name="is4K">Optional filter by items that are 4K or not.</param>
  73. /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
  74. /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
  75. /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
  76. /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
  77. /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
  78. /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
  79. /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
  80. /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
  81. /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
  82. /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
  83. /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
  84. /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
  85. /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
  86. /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
  87. /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
  88. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  89. /// <param name="limit">Optional. The maximum number of records to return.</param>
  90. /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
  91. /// <param name="searchTerm">Optional. Filter based on a search term.</param>
  92. /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
  93. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  94. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  95. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  96. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  97. /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
  98. /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
  99. /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
  100. /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
  101. /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
  102. /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
  103. /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
  104. /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
  105. /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
  106. /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
  107. /// <param name="enableUserData">Optional, include user data.</param>
  108. /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
  109. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  110. /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
  111. /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
  112. /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
  113. /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
  114. /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
  115. /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
  116. /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
  117. /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
  118. /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
  119. /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
  120. /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
  121. /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
  122. /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
  123. /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
  124. /// <param name="isLocked">Optional filter by items that are locked.</param>
  125. /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
  126. /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
  127. /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
  128. /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
  129. /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
  130. /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
  131. /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
  132. /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
  133. /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
  134. /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
  135. /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
  136. /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
  137. /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
  138. /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
  139. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  140. /// <param name="enableImages">Optional, include image information in output.</param>
  141. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
  142. [HttpGet("Items")]
  143. [HttpGet("Users/{uId}/Items", Name = "GetItems_2")]
  144. [ProducesResponseType(StatusCodes.Status200OK)]
  145. public ActionResult<QueryResult<BaseItemDto>> GetItems(
  146. [FromRoute] Guid? uId,
  147. [FromQuery] Guid? userId,
  148. [FromQuery] string? maxOfficialRating,
  149. [FromQuery] bool? hasThemeSong,
  150. [FromQuery] bool? hasThemeVideo,
  151. [FromQuery] bool? hasSubtitles,
  152. [FromQuery] bool? hasSpecialFeature,
  153. [FromQuery] bool? hasTrailer,
  154. [FromQuery] string? adjacentTo,
  155. [FromQuery] int? parentIndexNumber,
  156. [FromQuery] bool? hasParentalRating,
  157. [FromQuery] bool? isHd,
  158. [FromQuery] bool? is4K,
  159. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
  160. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
  161. [FromQuery] bool? isMissing,
  162. [FromQuery] bool? isUnaired,
  163. [FromQuery] double? minCommunityRating,
  164. [FromQuery] double? minCriticRating,
  165. [FromQuery] DateTime? minPremiereDate,
  166. [FromQuery] DateTime? minDateLastSaved,
  167. [FromQuery] DateTime? minDateLastSavedForUser,
  168. [FromQuery] DateTime? maxPremiereDate,
  169. [FromQuery] bool? hasOverview,
  170. [FromQuery] bool? hasImdbId,
  171. [FromQuery] bool? hasTmdbId,
  172. [FromQuery] bool? hasTvdbId,
  173. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
  174. [FromQuery] int? startIndex,
  175. [FromQuery] int? limit,
  176. [FromQuery] bool? recursive,
  177. [FromQuery] string? searchTerm,
  178. [FromQuery] string? sortOrder,
  179. [FromQuery] string? parentId,
  180. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  181. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes,
  182. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes,
  183. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
  184. [FromQuery] bool? isFavorite,
  185. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
  186. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
  187. [FromQuery] string? sortBy,
  188. [FromQuery] bool? isPlayed,
  189. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
  190. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
  191. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
  192. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
  193. [FromQuery] bool? enableUserData,
  194. [FromQuery] int? imageTypeLimit,
  195. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  196. [FromQuery] string? person,
  197. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
  198. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
  199. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
  200. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
  201. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
  202. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
  203. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
  204. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
  205. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
  206. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
  207. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  208. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
  209. [FromQuery] string? minOfficialRating,
  210. [FromQuery] bool? isLocked,
  211. [FromQuery] bool? isPlaceHolder,
  212. [FromQuery] bool? hasOfficialRating,
  213. [FromQuery] bool? collapseBoxSetItems,
  214. [FromQuery] int? minWidth,
  215. [FromQuery] int? minHeight,
  216. [FromQuery] int? maxWidth,
  217. [FromQuery] int? maxHeight,
  218. [FromQuery] bool? is3D,
  219. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
  220. [FromQuery] string? nameStartsWithOrGreater,
  221. [FromQuery] string? nameStartsWith,
  222. [FromQuery] string? nameLessThan,
  223. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
  224. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
  225. [FromQuery] bool enableTotalRecordCount = true,
  226. [FromQuery] bool? enableImages = true)
  227. {
  228. // use user id route parameter over query parameter
  229. userId = uId ?? userId;
  230. var user = userId.HasValue && !userId.Equals(Guid.Empty)
  231. ? _userManager.GetUserById(userId.Value)
  232. : null;
  233. var dtoOptions = new DtoOptions { Fields = fields }
  234. .AddClientFields(Request)
  235. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  236. if (includeItemTypes.Length == 1
  237. && (includeItemTypes[0].Equals("Playlist", StringComparison.OrdinalIgnoreCase)
  238. || includeItemTypes[0].Equals("BoxSet", StringComparison.OrdinalIgnoreCase)))
  239. {
  240. parentId = null;
  241. }
  242. BaseItem? item = null;
  243. QueryResult<BaseItem> result;
  244. if (!string.IsNullOrEmpty(parentId))
  245. {
  246. item = _libraryManager.GetItemById(parentId);
  247. }
  248. item ??= _libraryManager.GetUserRootFolder();
  249. if (!(item is Folder folder))
  250. {
  251. folder = _libraryManager.GetUserRootFolder();
  252. }
  253. if (folder is IHasCollectionType hasCollectionType
  254. && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
  255. {
  256. recursive = true;
  257. includeItemTypes = new[] { "Playlist" };
  258. }
  259. bool isInEnabledFolder = user!.GetPreference(PreferenceKind.EnabledFolders).Any(i => new Guid(i) == item.Id)
  260. // Assume all folders inside an EnabledChannel are enabled
  261. || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.Id)
  262. // Assume all items inside an EnabledChannel are enabled
  263. || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.ChannelId);
  264. var collectionFolders = _libraryManager.GetCollectionFolders(item);
  265. foreach (var collectionFolder in collectionFolders)
  266. {
  267. if (user.GetPreference(PreferenceKind.EnabledFolders).Contains(
  268. collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture),
  269. StringComparer.OrdinalIgnoreCase))
  270. {
  271. isInEnabledFolder = true;
  272. }
  273. }
  274. if (!(item is UserRootFolder)
  275. && !isInEnabledFolder
  276. && !user.HasPermission(PermissionKind.EnableAllFolders)
  277. && !user.HasPermission(PermissionKind.EnableAllChannels))
  278. {
  279. _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}.", user.Username, item.Name);
  280. return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}.");
  281. }
  282. if ((recursive.HasValue && recursive.Value) || ids.Length != 0 || !(item is UserRootFolder))
  283. {
  284. var query = new InternalItemsQuery(user!)
  285. {
  286. IsPlayed = isPlayed,
  287. MediaTypes = mediaTypes,
  288. IncludeItemTypes = includeItemTypes,
  289. ExcludeItemTypes = excludeItemTypes,
  290. Recursive = recursive ?? false,
  291. OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
  292. IsFavorite = isFavorite,
  293. Limit = limit,
  294. StartIndex = startIndex,
  295. IsMissing = isMissing,
  296. IsUnaired = isUnaired,
  297. CollapseBoxSetItems = collapseBoxSetItems,
  298. NameLessThan = nameLessThan,
  299. NameStartsWith = nameStartsWith,
  300. NameStartsWithOrGreater = nameStartsWithOrGreater,
  301. HasImdbId = hasImdbId,
  302. IsPlaceHolder = isPlaceHolder,
  303. IsLocked = isLocked,
  304. MinWidth = minWidth,
  305. MinHeight = minHeight,
  306. MaxWidth = maxWidth,
  307. MaxHeight = maxHeight,
  308. Is3D = is3D,
  309. HasTvdbId = hasTvdbId,
  310. HasTmdbId = hasTmdbId,
  311. HasOverview = hasOverview,
  312. HasOfficialRating = hasOfficialRating,
  313. HasParentalRating = hasParentalRating,
  314. HasSpecialFeature = hasSpecialFeature,
  315. HasSubtitles = hasSubtitles,
  316. HasThemeSong = hasThemeSong,
  317. HasThemeVideo = hasThemeVideo,
  318. HasTrailer = hasTrailer,
  319. IsHD = isHd,
  320. Is4K = is4K,
  321. Tags = tags,
  322. OfficialRatings = officialRatings,
  323. Genres = genres,
  324. ArtistIds = artistIds,
  325. AlbumArtistIds = albumArtistIds,
  326. ContributingArtistIds = contributingArtistIds,
  327. GenreIds = genreIds,
  328. StudioIds = studioIds,
  329. Person = person,
  330. PersonIds = personIds,
  331. PersonTypes = personTypes,
  332. Years = years,
  333. ImageTypes = imageTypes,
  334. VideoTypes = videoTypes,
  335. AdjacentTo = adjacentTo,
  336. ItemIds = ids,
  337. MinCommunityRating = minCommunityRating,
  338. MinCriticRating = minCriticRating,
  339. ParentId = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId),
  340. ParentIndexNumber = parentIndexNumber,
  341. EnableTotalRecordCount = enableTotalRecordCount,
  342. ExcludeItemIds = excludeItemIds,
  343. DtoOptions = dtoOptions,
  344. SearchTerm = searchTerm,
  345. MinDateLastSaved = minDateLastSaved?.ToUniversalTime(),
  346. MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
  347. MinPremiereDate = minPremiereDate?.ToUniversalTime(),
  348. MaxPremiereDate = maxPremiereDate?.ToUniversalTime(),
  349. };
  350. if (ids.Length != 0 || !string.IsNullOrWhiteSpace(searchTerm))
  351. {
  352. query.CollapseBoxSetItems = false;
  353. }
  354. foreach (var filter in filters)
  355. {
  356. switch (filter)
  357. {
  358. case ItemFilter.Dislikes:
  359. query.IsLiked = false;
  360. break;
  361. case ItemFilter.IsFavorite:
  362. query.IsFavorite = true;
  363. break;
  364. case ItemFilter.IsFavoriteOrLikes:
  365. query.IsFavoriteOrLiked = true;
  366. break;
  367. case ItemFilter.IsFolder:
  368. query.IsFolder = true;
  369. break;
  370. case ItemFilter.IsNotFolder:
  371. query.IsFolder = false;
  372. break;
  373. case ItemFilter.IsPlayed:
  374. query.IsPlayed = true;
  375. break;
  376. case ItemFilter.IsResumable:
  377. query.IsResumable = true;
  378. break;
  379. case ItemFilter.IsUnplayed:
  380. query.IsPlayed = false;
  381. break;
  382. case ItemFilter.Likes:
  383. query.IsLiked = true;
  384. break;
  385. }
  386. }
  387. // Filter by Series Status
  388. if (seriesStatus.Length != 0)
  389. {
  390. query.SeriesStatuses = seriesStatus;
  391. }
  392. // ExcludeLocationTypes
  393. if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
  394. {
  395. query.IsVirtualItem = false;
  396. }
  397. if (locationTypes.Length > 0 && locationTypes.Length < 4)
  398. {
  399. query.IsVirtualItem = locationTypes.Contains(LocationType.Virtual);
  400. }
  401. // Min official rating
  402. if (!string.IsNullOrWhiteSpace(minOfficialRating))
  403. {
  404. query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
  405. }
  406. // Max official rating
  407. if (!string.IsNullOrWhiteSpace(maxOfficialRating))
  408. {
  409. query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
  410. }
  411. // Artists
  412. if (artists.Length != 0)
  413. {
  414. query.ArtistIds = artists.Select(i =>
  415. {
  416. try
  417. {
  418. return _libraryManager.GetArtist(i, new DtoOptions(false));
  419. }
  420. catch
  421. {
  422. return null;
  423. }
  424. }).Where(i => i != null).Select(i => i!.Id).ToArray();
  425. }
  426. // ExcludeArtistIds
  427. if (excludeArtistIds.Length != 0)
  428. {
  429. query.ExcludeArtistIds = excludeArtistIds;
  430. }
  431. if (albumIds.Length != 0)
  432. {
  433. query.AlbumIds = albumIds;
  434. }
  435. // Albums
  436. if (albums.Length != 0)
  437. {
  438. query.AlbumIds = albums.SelectMany(i =>
  439. {
  440. return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = i, Limit = 1 });
  441. }).ToArray();
  442. }
  443. // Studios
  444. if (studios.Length != 0)
  445. {
  446. query.StudioIds = studios.Select(i =>
  447. {
  448. try
  449. {
  450. return _libraryManager.GetStudio(i);
  451. }
  452. catch
  453. {
  454. return null;
  455. }
  456. }).Where(i => i != null).Select(i => i!.Id).ToArray();
  457. }
  458. // Apply default sorting if none requested
  459. if (query.OrderBy.Count == 0)
  460. {
  461. // Albums by artist
  462. if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase))
  463. {
  464. query.OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending), new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) };
  465. }
  466. }
  467. result = folder.GetItems(query);
  468. }
  469. else
  470. {
  471. var itemsArray = folder.GetChildren(user, true);
  472. result = new QueryResult<BaseItem> { Items = itemsArray, TotalRecordCount = itemsArray.Count, StartIndex = 0 };
  473. }
  474. return new QueryResult<BaseItemDto> { StartIndex = startIndex.GetValueOrDefault(), TotalRecordCount = result.TotalRecordCount, Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user) };
  475. }
  476. /// <summary>
  477. /// Gets items based on a query.
  478. /// </summary>
  479. /// <param name="userId">The user id.</param>
  480. /// <param name="startIndex">The start index.</param>
  481. /// <param name="limit">The item limit.</param>
  482. /// <param name="searchTerm">The search term.</param>
  483. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  484. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  485. /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
  486. /// <param name="enableUserData">Optional. Include user data.</param>
  487. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  488. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  489. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  490. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  491. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  492. /// <param name="enableImages">Optional. Include image information in output.</param>
  493. /// <response code="200">Items returned.</response>
  494. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
  495. [HttpGet("Users/{userId}/Items/Resume")]
  496. [ProducesResponseType(StatusCodes.Status200OK)]
  497. public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
  498. [FromRoute, Required] Guid userId,
  499. [FromQuery] int? startIndex,
  500. [FromQuery] int? limit,
  501. [FromQuery] string? searchTerm,
  502. [FromQuery] string? parentId,
  503. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  504. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
  505. [FromQuery] bool? enableUserData,
  506. [FromQuery] int? imageTypeLimit,
  507. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  508. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes,
  509. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes,
  510. [FromQuery] bool enableTotalRecordCount = true,
  511. [FromQuery] bool? enableImages = true)
  512. {
  513. var user = _userManager.GetUserById(userId);
  514. var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId);
  515. var dtoOptions = new DtoOptions { Fields = fields }
  516. .AddClientFields(Request)
  517. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  518. var ancestorIds = Array.Empty<Guid>();
  519. var excludeFolderIds = user.GetPreference(PreferenceKind.LatestItemExcludes);
  520. if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0)
  521. {
  522. ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
  523. .Where(i => i is Folder)
  524. .Where(i => !excludeFolderIds.Contains(i.Id.ToString("N", CultureInfo.InvariantCulture)))
  525. .Select(i => i.Id)
  526. .ToArray();
  527. }
  528. var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  529. {
  530. OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
  531. IsResumable = true,
  532. StartIndex = startIndex,
  533. Limit = limit,
  534. ParentId = parentIdGuid,
  535. Recursive = true,
  536. DtoOptions = dtoOptions,
  537. MediaTypes = mediaTypes,
  538. IsVirtualItem = false,
  539. CollapseBoxSetItems = false,
  540. EnableTotalRecordCount = enableTotalRecordCount,
  541. AncestorIds = ancestorIds,
  542. IncludeItemTypes = includeItemTypes,
  543. ExcludeItemTypes = excludeItemTypes,
  544. SearchTerm = searchTerm
  545. });
  546. var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user);
  547. return new QueryResult<BaseItemDto>
  548. {
  549. StartIndex = startIndex.GetValueOrDefault(),
  550. TotalRecordCount = itemsResult.TotalRecordCount,
  551. Items = returnItems
  552. };
  553. }
  554. }
  555. }