ItemsController.cs 33 KB

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