ItemsController.cs 34 KB

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