ItemsController.cs 34 KB

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