ItemsController.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 delimeted.</param>
  74. /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimeted.</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 exxcluding item ids. This allows multiple, comma delimeted.</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 delimeted. 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 delimeted.</param>
  96. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param>
  97. /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimeted. 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 delimeted. 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 delimeted.</param>
  104. /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.</param>
  105. /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.</param>
  106. /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.</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 delimeted.</param>
  114. /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimeted.</param>
  115. /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimeted.</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 delimeted.</param>
  120. /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimeted.</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 delimeted.</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 delimeted.</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 delimeted.</param>
  138. /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimeted.</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] string? 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] string? 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] string? excludeItemTypes,
  182. [FromQuery] string? includeItemTypes,
  183. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
  184. [FromQuery] bool? isFavorite,
  185. [FromQuery] string? mediaTypes,
  186. [FromQuery] ImageType[] imageTypes,
  187. [FromQuery] string? sortBy,
  188. [FromQuery] bool? isPlayed,
  189. [FromQuery] string? genres,
  190. [FromQuery] string? officialRatings,
  191. [FromQuery] string? tags,
  192. [FromQuery] string? years,
  193. [FromQuery] bool? enableUserData,
  194. [FromQuery] int? imageTypeLimit,
  195. [FromQuery] ImageType[] enableImageTypes,
  196. [FromQuery] string? person,
  197. [FromQuery] string? personIds,
  198. [FromQuery] string? personTypes,
  199. [FromQuery] string? studios,
  200. [FromQuery] string? artists,
  201. [FromQuery] string? excludeArtistIds,
  202. [FromQuery] string? artistIds,
  203. [FromQuery] string? albumArtistIds,
  204. [FromQuery] string? contributingArtistIds,
  205. [FromQuery] string? albums,
  206. [FromQuery] string? albumIds,
  207. [FromQuery] string? ids,
  208. [FromQuery] string? 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] string? seriesStatus,
  220. [FromQuery] string? nameStartsWithOrGreater,
  221. [FromQuery] string? nameStartsWith,
  222. [FromQuery] string? nameLessThan,
  223. [FromQuery] string? studioIds,
  224. [FromQuery] string? 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 (string.Equals(includeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase)
  237. || string.Equals(includeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
  238. {
  239. parentId = null;
  240. }
  241. BaseItem? item = null;
  242. QueryResult<BaseItem> result;
  243. if (!string.IsNullOrEmpty(parentId))
  244. {
  245. item = _libraryManager.GetItemById(parentId);
  246. }
  247. item ??= _libraryManager.GetUserRootFolder();
  248. if (!(item is Folder folder))
  249. {
  250. folder = _libraryManager.GetUserRootFolder();
  251. }
  252. if (folder is IHasCollectionType hasCollectionType
  253. && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
  254. {
  255. recursive = true;
  256. includeItemTypes = "Playlist";
  257. }
  258. bool isInEnabledFolder = user!.GetPreference(PreferenceKind.EnabledFolders).Any(i => new Guid(i) == item.Id)
  259. // Assume all folders inside an EnabledChannel are enabled
  260. || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.Id)
  261. // Assume all items inside an EnabledChannel are enabled
  262. || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.ChannelId);
  263. var collectionFolders = _libraryManager.GetCollectionFolders(item);
  264. foreach (var collectionFolder in collectionFolders)
  265. {
  266. if (user.GetPreference(PreferenceKind.EnabledFolders).Contains(
  267. collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture),
  268. StringComparer.OrdinalIgnoreCase))
  269. {
  270. isInEnabledFolder = true;
  271. }
  272. }
  273. if (!(item is UserRootFolder)
  274. && !isInEnabledFolder
  275. && !user.HasPermission(PermissionKind.EnableAllFolders)
  276. && !user.HasPermission(PermissionKind.EnableAllChannels))
  277. {
  278. _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}.", user.Username, item.Name);
  279. return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}.");
  280. }
  281. if ((recursive.HasValue && recursive.Value) || !string.IsNullOrEmpty(ids) || !(item is UserRootFolder))
  282. {
  283. var query = new InternalItemsQuery(user!)
  284. {
  285. IsPlayed = isPlayed,
  286. MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
  287. IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
  288. ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
  289. Recursive = recursive ?? false,
  290. OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
  291. IsFavorite = isFavorite,
  292. Limit = limit,
  293. StartIndex = startIndex,
  294. IsMissing = isMissing,
  295. IsUnaired = isUnaired,
  296. CollapseBoxSetItems = collapseBoxSetItems,
  297. NameLessThan = nameLessThan,
  298. NameStartsWith = nameStartsWith,
  299. NameStartsWithOrGreater = nameStartsWithOrGreater,
  300. HasImdbId = hasImdbId,
  301. IsPlaceHolder = isPlaceHolder,
  302. IsLocked = isLocked,
  303. MinWidth = minWidth,
  304. MinHeight = minHeight,
  305. MaxWidth = maxWidth,
  306. MaxHeight = maxHeight,
  307. Is3D = is3D,
  308. HasTvdbId = hasTvdbId,
  309. HasTmdbId = hasTmdbId,
  310. HasOverview = hasOverview,
  311. HasOfficialRating = hasOfficialRating,
  312. HasParentalRating = hasParentalRating,
  313. HasSpecialFeature = hasSpecialFeature,
  314. HasSubtitles = hasSubtitles,
  315. HasThemeSong = hasThemeSong,
  316. HasThemeVideo = hasThemeVideo,
  317. HasTrailer = hasTrailer,
  318. IsHD = isHd,
  319. Is4K = is4K,
  320. Tags = RequestHelpers.Split(tags, '|', true),
  321. OfficialRatings = RequestHelpers.Split(officialRatings, '|', true),
  322. Genres = RequestHelpers.Split(genres, '|', true),
  323. ArtistIds = RequestHelpers.GetGuids(artistIds),
  324. AlbumArtistIds = RequestHelpers.GetGuids(albumArtistIds),
  325. ContributingArtistIds = RequestHelpers.GetGuids(contributingArtistIds),
  326. GenreIds = RequestHelpers.GetGuids(genreIds),
  327. StudioIds = RequestHelpers.GetGuids(studioIds),
  328. Person = person,
  329. PersonIds = RequestHelpers.GetGuids(personIds),
  330. PersonTypes = RequestHelpers.Split(personTypes, ',', true),
  331. Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(),
  332. ImageTypes = imageTypes,
  333. VideoTypes = RequestHelpers.Split(videoTypes, ',', true).Select(v => Enum.Parse<VideoType>(v, true)).ToArray(),
  334. AdjacentTo = adjacentTo,
  335. ItemIds = RequestHelpers.GetGuids(ids),
  336. MinCommunityRating = minCommunityRating,
  337. MinCriticRating = minCriticRating,
  338. ParentId = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId),
  339. ParentIndexNumber = parentIndexNumber,
  340. EnableTotalRecordCount = enableTotalRecordCount,
  341. ExcludeItemIds = RequestHelpers.GetGuids(excludeItemIds),
  342. DtoOptions = dtoOptions,
  343. SearchTerm = searchTerm,
  344. MinDateLastSaved = minDateLastSaved?.ToUniversalTime(),
  345. MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
  346. MinPremiereDate = minPremiereDate?.ToUniversalTime(),
  347. MaxPremiereDate = maxPremiereDate?.ToUniversalTime(),
  348. };
  349. if (!string.IsNullOrWhiteSpace(ids) || !string.IsNullOrWhiteSpace(searchTerm))
  350. {
  351. query.CollapseBoxSetItems = false;
  352. }
  353. foreach (var filter in filters)
  354. {
  355. switch (filter)
  356. {
  357. case ItemFilter.Dislikes:
  358. query.IsLiked = false;
  359. break;
  360. case ItemFilter.IsFavorite:
  361. query.IsFavorite = true;
  362. break;
  363. case ItemFilter.IsFavoriteOrLikes:
  364. query.IsFavoriteOrLiked = true;
  365. break;
  366. case ItemFilter.IsFolder:
  367. query.IsFolder = true;
  368. break;
  369. case ItemFilter.IsNotFolder:
  370. query.IsFolder = false;
  371. break;
  372. case ItemFilter.IsPlayed:
  373. query.IsPlayed = true;
  374. break;
  375. case ItemFilter.IsResumable:
  376. query.IsResumable = true;
  377. break;
  378. case ItemFilter.IsUnplayed:
  379. query.IsPlayed = false;
  380. break;
  381. case ItemFilter.Likes:
  382. query.IsLiked = true;
  383. break;
  384. }
  385. }
  386. // Filter by Series Status
  387. if (!string.IsNullOrEmpty(seriesStatus))
  388. {
  389. query.SeriesStatuses = seriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
  390. }
  391. // ExcludeLocationTypes
  392. if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
  393. {
  394. query.IsVirtualItem = false;
  395. }
  396. if (!string.IsNullOrEmpty(locationTypes))
  397. {
  398. var requestedLocationTypes = locationTypes.Split(',');
  399. if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4)
  400. {
  401. query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual.ToString());
  402. }
  403. }
  404. // Min official rating
  405. if (!string.IsNullOrWhiteSpace(minOfficialRating))
  406. {
  407. query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
  408. }
  409. // Max official rating
  410. if (!string.IsNullOrWhiteSpace(maxOfficialRating))
  411. {
  412. query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
  413. }
  414. // Artists
  415. if (!string.IsNullOrEmpty(artists))
  416. {
  417. query.ArtistIds = artists.Split('|').Select(i =>
  418. {
  419. try
  420. {
  421. return _libraryManager.GetArtist(i, new DtoOptions(false));
  422. }
  423. catch
  424. {
  425. return null;
  426. }
  427. }).Where(i => i != null).Select(i => i!.Id).ToArray();
  428. }
  429. // ExcludeArtistIds
  430. if (!string.IsNullOrWhiteSpace(excludeArtistIds))
  431. {
  432. query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
  433. }
  434. if (!string.IsNullOrWhiteSpace(albumIds))
  435. {
  436. query.AlbumIds = RequestHelpers.GetGuids(albumIds);
  437. }
  438. // Albums
  439. if (!string.IsNullOrEmpty(albums))
  440. {
  441. query.AlbumIds = albums.Split('|').SelectMany(i =>
  442. {
  443. return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = i, Limit = 1 });
  444. }).ToArray();
  445. }
  446. // Studios
  447. if (!string.IsNullOrEmpty(studios))
  448. {
  449. query.StudioIds = studios.Split('|').Select(i =>
  450. {
  451. try
  452. {
  453. return _libraryManager.GetStudio(i);
  454. }
  455. catch
  456. {
  457. return null;
  458. }
  459. }).Where(i => i != null).Select(i => i!.Id).ToArray();
  460. }
  461. // Apply default sorting if none requested
  462. if (query.OrderBy.Count == 0)
  463. {
  464. // Albums by artist
  465. if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase))
  466. {
  467. query.OrderBy = new[] { new ValueTuple<string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending), new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) };
  468. }
  469. }
  470. result = folder.GetItems(query);
  471. }
  472. else
  473. {
  474. var itemsArray = folder.GetChildren(user, true);
  475. result = new QueryResult<BaseItem> { Items = itemsArray, TotalRecordCount = itemsArray.Count, StartIndex = 0 };
  476. }
  477. return new QueryResult<BaseItemDto> { StartIndex = startIndex.GetValueOrDefault(), TotalRecordCount = result.TotalRecordCount, Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user) };
  478. }
  479. /// <summary>
  480. /// Gets items based on a query.
  481. /// </summary>
  482. /// <param name="userId">The user id.</param>
  483. /// <param name="startIndex">The start index.</param>
  484. /// <param name="limit">The item limit.</param>
  485. /// <param name="searchTerm">The search term.</param>
  486. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  487. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  488. /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
  489. /// <param name="enableUserData">Optional. Include user data.</param>
  490. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  491. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  492. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param>
  493. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param>
  494. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  495. /// <param name="enableImages">Optional. Include image information in output.</param>
  496. /// <response code="200">Items returned.</response>
  497. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
  498. [HttpGet("Users/{userId}/Items/Resume")]
  499. [ProducesResponseType(StatusCodes.Status200OK)]
  500. public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
  501. [FromRoute, Required] Guid userId,
  502. [FromQuery] int? startIndex,
  503. [FromQuery] int? limit,
  504. [FromQuery] string? searchTerm,
  505. [FromQuery] string? parentId,
  506. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  507. [FromQuery] string? mediaTypes,
  508. [FromQuery] bool? enableUserData,
  509. [FromQuery] int? imageTypeLimit,
  510. [FromQuery] ImageType[] enableImageTypes,
  511. [FromQuery] string? excludeItemTypes,
  512. [FromQuery] string? includeItemTypes,
  513. [FromQuery] bool enableTotalRecordCount = true,
  514. [FromQuery] bool? enableImages = true)
  515. {
  516. var user = _userManager.GetUserById(userId);
  517. var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId);
  518. var dtoOptions = new DtoOptions { Fields = fields }
  519. .AddClientFields(Request)
  520. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  521. var ancestorIds = Array.Empty<Guid>();
  522. var excludeFolderIds = user.GetPreference(PreferenceKind.LatestItemExcludes);
  523. if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0)
  524. {
  525. ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
  526. .Where(i => i is Folder)
  527. .Where(i => !excludeFolderIds.Contains(i.Id.ToString("N", CultureInfo.InvariantCulture)))
  528. .Select(i => i.Id)
  529. .ToArray();
  530. }
  531. var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  532. {
  533. OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
  534. IsResumable = true,
  535. StartIndex = startIndex,
  536. Limit = limit,
  537. ParentId = parentIdGuid,
  538. Recursive = true,
  539. DtoOptions = dtoOptions,
  540. MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
  541. IsVirtualItem = false,
  542. CollapseBoxSetItems = false,
  543. EnableTotalRecordCount = enableTotalRecordCount,
  544. AncestorIds = ancestorIds,
  545. IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
  546. ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
  547. SearchTerm = searchTerm
  548. });
  549. var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user);
  550. return new QueryResult<BaseItemDto>
  551. {
  552. StartIndex = startIndex.GetValueOrDefault(),
  553. TotalRecordCount = itemsResult.TotalRecordCount,
  554. Items = returnItems
  555. };
  556. }
  557. }
  558. }