ItemsController.cs 34 KB

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