ItemsController.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Linq;
  4. using Jellyfin.Api.Extensions;
  5. using Jellyfin.Api.Helpers;
  6. using Jellyfin.Api.ModelBinders;
  7. using Jellyfin.Data.Enums;
  8. using Jellyfin.Extensions;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Dto;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Session;
  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. /// <summary>
  24. /// The items controller.
  25. /// </summary>
  26. [Route("")]
  27. [Authorize]
  28. public class ItemsController : BaseJellyfinApiController
  29. {
  30. private readonly IUserManager _userManager;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly ILocalizationManager _localization;
  33. private readonly IDtoService _dtoService;
  34. private readonly ILogger<ItemsController> _logger;
  35. private readonly ISessionManager _sessionManager;
  36. private readonly IUserDataManager _userDataRepository;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="ItemsController"/> class.
  39. /// </summary>
  40. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  41. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  42. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  43. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  44. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  45. /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
  46. /// <param name="userDataRepository">Instance of the <see cref="IUserDataManager"/> interface.</param>
  47. public ItemsController(
  48. IUserManager userManager,
  49. ILibraryManager libraryManager,
  50. ILocalizationManager localization,
  51. IDtoService dtoService,
  52. ILogger<ItemsController> logger,
  53. ISessionManager sessionManager,
  54. IUserDataManager userDataRepository)
  55. {
  56. _userManager = userManager;
  57. _libraryManager = libraryManager;
  58. _localization = localization;
  59. _dtoService = dtoService;
  60. _logger = logger;
  61. _sessionManager = sessionManager;
  62. _userDataRepository = userDataRepository;
  63. }
  64. /// <summary>
  65. /// Gets items based on a query.
  66. /// </summary>
  67. /// <param name="userId">The user id supplied as query parameter; this is required when not using an API key.</param>
  68. /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
  69. /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
  70. /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
  71. /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
  72. /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
  73. /// <param name="hasTrailer">Optional filter by items with trailers.</param>
  74. /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
  75. /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
  76. /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
  77. /// <param name="isHd">Optional filter by items that are HD or not.</param>
  78. /// <param name="is4K">Optional filter by items that are 4K or not.</param>
  79. /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
  80. /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
  81. /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
  82. /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
  83. /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
  84. /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
  85. /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
  86. /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
  87. /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
  88. /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
  89. /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
  90. /// <param name="hasImdbId">Optional filter by items that have an IMDb id or not.</param>
  91. /// <param name="hasTmdbId">Optional filter by items that have a TMDb id or not.</param>
  92. /// <param name="hasTvdbId">Optional filter by items that have a TVDb id or not.</param>
  93. /// <param name="isMovie">Optional filter for live tv movies.</param>
  94. /// <param name="isSeries">Optional filter for live tv series.</param>
  95. /// <param name="isNews">Optional filter for live tv news.</param>
  96. /// <param name="isKids">Optional filter for live tv kids.</param>
  97. /// <param name="isSports">Optional filter for live tv sports.</param>
  98. /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
  99. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  100. /// <param name="limit">Optional. The maximum number of records to return.</param>
  101. /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
  102. /// <param name="searchTerm">Optional. Filter based on a search term.</param>
  103. /// <param name="sortOrder">Sort Order - Ascending, Descending.</param>
  104. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  105. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  106. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  107. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  108. /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
  109. /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
  110. /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
  111. /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
  112. /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
  113. /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
  114. /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
  115. /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
  116. /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
  117. /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
  118. /// <param name="enableUserData">Optional, include user data.</param>
  119. /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
  120. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  121. /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
  122. /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
  123. /// <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>
  124. /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
  125. /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
  126. /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
  127. /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
  128. /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
  129. /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
  130. /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
  131. /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
  132. /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
  133. /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
  134. /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
  135. /// <param name="isLocked">Optional filter by items that are locked.</param>
  136. /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
  137. /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
  138. /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
  139. /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
  140. /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
  141. /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
  142. /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
  143. /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
  144. /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
  145. /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
  146. /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
  147. /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
  148. /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
  149. /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
  150. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  151. /// <param name="enableImages">Optional, include image information in output.</param>
  152. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
  153. [HttpGet("Items")]
  154. [ProducesResponseType(StatusCodes.Status200OK)]
  155. public ActionResult<QueryResult<BaseItemDto>> GetItems(
  156. [FromQuery] Guid? userId,
  157. [FromQuery] string? maxOfficialRating,
  158. [FromQuery] bool? hasThemeSong,
  159. [FromQuery] bool? hasThemeVideo,
  160. [FromQuery] bool? hasSubtitles,
  161. [FromQuery] bool? hasSpecialFeature,
  162. [FromQuery] bool? hasTrailer,
  163. [FromQuery] Guid? adjacentTo,
  164. [FromQuery] int? parentIndexNumber,
  165. [FromQuery] bool? hasParentalRating,
  166. [FromQuery] bool? isHd,
  167. [FromQuery] bool? is4K,
  168. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
  169. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
  170. [FromQuery] bool? isMissing,
  171. [FromQuery] bool? isUnaired,
  172. [FromQuery] double? minCommunityRating,
  173. [FromQuery] double? minCriticRating,
  174. [FromQuery] DateTime? minPremiereDate,
  175. [FromQuery] DateTime? minDateLastSaved,
  176. [FromQuery] DateTime? minDateLastSavedForUser,
  177. [FromQuery] DateTime? maxPremiereDate,
  178. [FromQuery] bool? hasOverview,
  179. [FromQuery] bool? hasImdbId,
  180. [FromQuery] bool? hasTmdbId,
  181. [FromQuery] bool? hasTvdbId,
  182. [FromQuery] bool? isMovie,
  183. [FromQuery] bool? isSeries,
  184. [FromQuery] bool? isNews,
  185. [FromQuery] bool? isKids,
  186. [FromQuery] bool? isSports,
  187. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
  188. [FromQuery] int? startIndex,
  189. [FromQuery] int? limit,
  190. [FromQuery] bool? recursive,
  191. [FromQuery] string? searchTerm,
  192. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
  193. [FromQuery] Guid? parentId,
  194. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  195. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
  196. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
  197. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
  198. [FromQuery] bool? isFavorite,
  199. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaTypes,
  200. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
  201. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemSortBy[] sortBy,
  202. [FromQuery] bool? isPlayed,
  203. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
  204. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
  205. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
  206. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
  207. [FromQuery] bool? enableUserData,
  208. [FromQuery] int? imageTypeLimit,
  209. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  210. [FromQuery] string? person,
  211. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
  212. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
  213. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
  214. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
  215. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
  216. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
  217. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
  218. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
  219. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
  220. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
  221. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  222. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
  223. [FromQuery] string? minOfficialRating,
  224. [FromQuery] bool? isLocked,
  225. [FromQuery] bool? isPlaceHolder,
  226. [FromQuery] bool? hasOfficialRating,
  227. [FromQuery] bool? collapseBoxSetItems,
  228. [FromQuery] int? minWidth,
  229. [FromQuery] int? minHeight,
  230. [FromQuery] int? maxWidth,
  231. [FromQuery] int? maxHeight,
  232. [FromQuery] bool? is3D,
  233. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
  234. [FromQuery] string? nameStartsWithOrGreater,
  235. [FromQuery] string? nameStartsWith,
  236. [FromQuery] string? nameLessThan,
  237. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
  238. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
  239. [FromQuery] bool enableTotalRecordCount = true,
  240. [FromQuery] bool? enableImages = true)
  241. {
  242. var isApiKey = User.GetIsApiKey();
  243. // if api key is used (auth.IsApiKey == true), then `user` will be null throughout this method
  244. userId = RequestHelpers.GetUserId(User, userId);
  245. var user = !isApiKey && !userId.IsNullOrEmpty()
  246. ? _userManager.GetUserById(userId.Value) ?? throw new ResourceNotFoundException()
  247. : null;
  248. // beyond this point, we're either using an api key or we have a valid user
  249. if (!isApiKey && user is null)
  250. {
  251. return BadRequest("userId is required");
  252. }
  253. var dtoOptions = new DtoOptions { Fields = fields }
  254. .AddClientFields(User)
  255. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  256. if (includeItemTypes.Length == 1
  257. && includeItemTypes[0] == BaseItemKind.BoxSet)
  258. {
  259. parentId = null;
  260. }
  261. var item = _libraryManager.GetParentItem(parentId, userId);
  262. QueryResult<BaseItem> result;
  263. if (item is not Folder folder)
  264. {
  265. folder = _libraryManager.GetUserRootFolder();
  266. }
  267. CollectionType? collectionType = null;
  268. if (folder is IHasCollectionType hasCollectionType)
  269. {
  270. collectionType = hasCollectionType.CollectionType;
  271. }
  272. if (collectionType == CollectionType.playlists)
  273. {
  274. recursive = true;
  275. includeItemTypes = new[] { BaseItemKind.Playlist };
  276. }
  277. if (item is not UserRootFolder
  278. // api keys can always access all folders
  279. && !isApiKey
  280. // check the item is visible for the user
  281. && !item.IsVisible(user))
  282. {
  283. _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}", user!.Username, item.Name);
  284. return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}.");
  285. }
  286. if ((recursive.HasValue && recursive.Value) || ids.Length != 0 || item is not UserRootFolder)
  287. {
  288. var query = new InternalItemsQuery(user)
  289. {
  290. IsPlayed = isPlayed,
  291. MediaTypes = mediaTypes,
  292. IncludeItemTypes = includeItemTypes,
  293. ExcludeItemTypes = excludeItemTypes,
  294. Recursive = recursive ?? false,
  295. OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
  296. IsFavorite = isFavorite,
  297. Limit = limit,
  298. StartIndex = startIndex,
  299. IsMissing = isMissing,
  300. IsUnaired = isUnaired,
  301. CollapseBoxSetItems = collapseBoxSetItems,
  302. NameLessThan = nameLessThan,
  303. NameStartsWith = nameStartsWith,
  304. NameStartsWithOrGreater = nameStartsWithOrGreater,
  305. HasImdbId = hasImdbId,
  306. IsPlaceHolder = isPlaceHolder,
  307. IsLocked = isLocked,
  308. MinWidth = minWidth,
  309. MinHeight = minHeight,
  310. MaxWidth = maxWidth,
  311. MaxHeight = maxHeight,
  312. Is3D = is3D,
  313. HasTvdbId = hasTvdbId,
  314. HasTmdbId = hasTmdbId,
  315. IsMovie = isMovie,
  316. IsSeries = isSeries,
  317. IsNews = isNews,
  318. IsKids = isKids,
  319. IsSports = isSports,
  320. HasOverview = hasOverview,
  321. HasOfficialRating = hasOfficialRating,
  322. HasParentalRating = hasParentalRating,
  323. HasSpecialFeature = hasSpecialFeature,
  324. HasSubtitles = hasSubtitles,
  325. HasThemeSong = hasThemeSong,
  326. HasThemeVideo = hasThemeVideo,
  327. HasTrailer = hasTrailer,
  328. IsHD = isHd,
  329. Is4K = is4K,
  330. Tags = tags,
  331. OfficialRatings = officialRatings,
  332. Genres = genres,
  333. ArtistIds = artistIds,
  334. AlbumArtistIds = albumArtistIds,
  335. ContributingArtistIds = contributingArtistIds,
  336. GenreIds = genreIds,
  337. StudioIds = studioIds,
  338. Person = person,
  339. PersonIds = personIds,
  340. PersonTypes = personTypes,
  341. Years = years,
  342. ImageTypes = imageTypes,
  343. VideoTypes = videoTypes,
  344. AdjacentTo = adjacentTo,
  345. ItemIds = ids,
  346. MinCommunityRating = minCommunityRating,
  347. MinCriticRating = minCriticRating,
  348. ParentId = parentId ?? Guid.Empty,
  349. ParentIndexNumber = parentIndexNumber,
  350. EnableTotalRecordCount = enableTotalRecordCount,
  351. ExcludeItemIds = excludeItemIds,
  352. DtoOptions = dtoOptions,
  353. SearchTerm = searchTerm,
  354. MinDateLastSaved = minDateLastSaved?.ToUniversalTime(),
  355. MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
  356. MinPremiereDate = minPremiereDate?.ToUniversalTime(),
  357. MaxPremiereDate = maxPremiereDate?.ToUniversalTime(),
  358. };
  359. if (ids.Length != 0 || !string.IsNullOrWhiteSpace(searchTerm))
  360. {
  361. query.CollapseBoxSetItems = false;
  362. }
  363. foreach (var filter in filters)
  364. {
  365. switch (filter)
  366. {
  367. case ItemFilter.Dislikes:
  368. query.IsLiked = false;
  369. break;
  370. case ItemFilter.IsFavorite:
  371. query.IsFavorite = true;
  372. break;
  373. case ItemFilter.IsFavoriteOrLikes:
  374. query.IsFavoriteOrLiked = true;
  375. break;
  376. case ItemFilter.IsFolder:
  377. query.IsFolder = true;
  378. break;
  379. case ItemFilter.IsNotFolder:
  380. query.IsFolder = false;
  381. break;
  382. case ItemFilter.IsPlayed:
  383. query.IsPlayed = true;
  384. break;
  385. case ItemFilter.IsResumable:
  386. query.IsResumable = true;
  387. break;
  388. case ItemFilter.IsUnplayed:
  389. query.IsPlayed = false;
  390. break;
  391. case ItemFilter.Likes:
  392. query.IsLiked = true;
  393. break;
  394. }
  395. }
  396. // Filter by Series Status
  397. if (seriesStatus.Length != 0)
  398. {
  399. query.SeriesStatuses = seriesStatus;
  400. }
  401. // Exclude Blocked Unrated Items
  402. var blockedUnratedItems = user?.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems);
  403. if (blockedUnratedItems is not null)
  404. {
  405. query.BlockUnratedItems = blockedUnratedItems;
  406. }
  407. // ExcludeLocationTypes
  408. if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
  409. {
  410. query.IsVirtualItem = false;
  411. }
  412. if (locationTypes.Length > 0 && locationTypes.Length < 4)
  413. {
  414. query.IsVirtualItem = locationTypes.Contains(LocationType.Virtual);
  415. }
  416. // Min official rating
  417. if (!string.IsNullOrWhiteSpace(minOfficialRating))
  418. {
  419. query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
  420. }
  421. // Max official rating
  422. if (!string.IsNullOrWhiteSpace(maxOfficialRating))
  423. {
  424. query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
  425. }
  426. // Artists
  427. if (artists.Length != 0)
  428. {
  429. query.ArtistIds = artists.Select(i =>
  430. {
  431. try
  432. {
  433. return _libraryManager.GetArtist(i, new DtoOptions(false));
  434. }
  435. catch
  436. {
  437. return null;
  438. }
  439. }).Where(i => i is not null).Select(i => i!.Id).ToArray();
  440. }
  441. // ExcludeArtistIds
  442. if (excludeArtistIds.Length != 0)
  443. {
  444. query.ExcludeArtistIds = excludeArtistIds;
  445. }
  446. if (albumIds.Length != 0)
  447. {
  448. query.AlbumIds = albumIds;
  449. }
  450. // Albums
  451. if (albums.Length != 0)
  452. {
  453. query.AlbumIds = albums.SelectMany(i =>
  454. {
  455. return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { BaseItemKind.MusicAlbum }, Name = i, Limit = 1 });
  456. }).ToArray();
  457. }
  458. // Studios
  459. if (studios.Length != 0)
  460. {
  461. query.StudioIds = studios.Select(i =>
  462. {
  463. try
  464. {
  465. return _libraryManager.GetStudio(i);
  466. }
  467. catch
  468. {
  469. return null;
  470. }
  471. }).Where(i => i is not null).Select(i => i!.Id).ToArray();
  472. }
  473. // Apply default sorting if none requested
  474. if (query.OrderBy.Count == 0)
  475. {
  476. // Albums by artist
  477. if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.MusicAlbum)
  478. {
  479. query.OrderBy = new[] { (ItemSortBy.ProductionYear, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Ascending) };
  480. }
  481. }
  482. query.Parent = null;
  483. result = folder.GetItems(query);
  484. }
  485. else
  486. {
  487. var itemsArray = folder.GetChildren(user, true);
  488. result = new QueryResult<BaseItem>(itemsArray);
  489. }
  490. return new QueryResult<BaseItemDto>(
  491. startIndex,
  492. result.TotalRecordCount,
  493. _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user));
  494. }
  495. /// <summary>
  496. /// Gets items based on a query.
  497. /// </summary>
  498. /// <param name="userId">The user id supplied as query parameter.</param>
  499. /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
  500. /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
  501. /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
  502. /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
  503. /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
  504. /// <param name="hasTrailer">Optional filter by items with trailers.</param>
  505. /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
  506. /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
  507. /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
  508. /// <param name="isHd">Optional filter by items that are HD or not.</param>
  509. /// <param name="is4K">Optional filter by items that are 4K or not.</param>
  510. /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
  511. /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
  512. /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
  513. /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
  514. /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
  515. /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
  516. /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
  517. /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
  518. /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
  519. /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
  520. /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
  521. /// <param name="hasImdbId">Optional filter by items that have an IMDb id or not.</param>
  522. /// <param name="hasTmdbId">Optional filter by items that have a TMDb id or not.</param>
  523. /// <param name="hasTvdbId">Optional filter by items that have a TVDb id or not.</param>
  524. /// <param name="isMovie">Optional filter for live tv movies.</param>
  525. /// <param name="isSeries">Optional filter for live tv series.</param>
  526. /// <param name="isNews">Optional filter for live tv news.</param>
  527. /// <param name="isKids">Optional filter for live tv kids.</param>
  528. /// <param name="isSports">Optional filter for live tv sports.</param>
  529. /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
  530. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  531. /// <param name="limit">Optional. The maximum number of records to return.</param>
  532. /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
  533. /// <param name="searchTerm">Optional. Filter based on a search term.</param>
  534. /// <param name="sortOrder">Sort Order - Ascending, Descending.</param>
  535. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  536. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  537. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  538. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  539. /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
  540. /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
  541. /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
  542. /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
  543. /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
  544. /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
  545. /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
  546. /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
  547. /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
  548. /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
  549. /// <param name="enableUserData">Optional, include user data.</param>
  550. /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
  551. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  552. /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
  553. /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
  554. /// <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>
  555. /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
  556. /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
  557. /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
  558. /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
  559. /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
  560. /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
  561. /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
  562. /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
  563. /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
  564. /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
  565. /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
  566. /// <param name="isLocked">Optional filter by items that are locked.</param>
  567. /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
  568. /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
  569. /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
  570. /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
  571. /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
  572. /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
  573. /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
  574. /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
  575. /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
  576. /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
  577. /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
  578. /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
  579. /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
  580. /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
  581. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  582. /// <param name="enableImages">Optional, include image information in output.</param>
  583. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
  584. [HttpGet("Users/{userId}/Items")]
  585. [Obsolete("Kept for backwards compatibility")]
  586. [ApiExplorerSettings(IgnoreApi = true)]
  587. [ProducesResponseType(StatusCodes.Status200OK)]
  588. public ActionResult<QueryResult<BaseItemDto>> GetItemsByUserIdLegacy(
  589. [FromRoute] Guid userId,
  590. [FromQuery] string? maxOfficialRating,
  591. [FromQuery] bool? hasThemeSong,
  592. [FromQuery] bool? hasThemeVideo,
  593. [FromQuery] bool? hasSubtitles,
  594. [FromQuery] bool? hasSpecialFeature,
  595. [FromQuery] bool? hasTrailer,
  596. [FromQuery] Guid? adjacentTo,
  597. [FromQuery] int? parentIndexNumber,
  598. [FromQuery] bool? hasParentalRating,
  599. [FromQuery] bool? isHd,
  600. [FromQuery] bool? is4K,
  601. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
  602. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
  603. [FromQuery] bool? isMissing,
  604. [FromQuery] bool? isUnaired,
  605. [FromQuery] double? minCommunityRating,
  606. [FromQuery] double? minCriticRating,
  607. [FromQuery] DateTime? minPremiereDate,
  608. [FromQuery] DateTime? minDateLastSaved,
  609. [FromQuery] DateTime? minDateLastSavedForUser,
  610. [FromQuery] DateTime? maxPremiereDate,
  611. [FromQuery] bool? hasOverview,
  612. [FromQuery] bool? hasImdbId,
  613. [FromQuery] bool? hasTmdbId,
  614. [FromQuery] bool? hasTvdbId,
  615. [FromQuery] bool? isMovie,
  616. [FromQuery] bool? isSeries,
  617. [FromQuery] bool? isNews,
  618. [FromQuery] bool? isKids,
  619. [FromQuery] bool? isSports,
  620. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
  621. [FromQuery] int? startIndex,
  622. [FromQuery] int? limit,
  623. [FromQuery] bool? recursive,
  624. [FromQuery] string? searchTerm,
  625. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
  626. [FromQuery] Guid? parentId,
  627. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  628. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
  629. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
  630. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
  631. [FromQuery] bool? isFavorite,
  632. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaTypes,
  633. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
  634. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemSortBy[] sortBy,
  635. [FromQuery] bool? isPlayed,
  636. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
  637. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
  638. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
  639. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
  640. [FromQuery] bool? enableUserData,
  641. [FromQuery] int? imageTypeLimit,
  642. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  643. [FromQuery] string? person,
  644. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
  645. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
  646. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
  647. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
  648. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
  649. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
  650. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
  651. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
  652. [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
  653. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
  654. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
  655. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
  656. [FromQuery] string? minOfficialRating,
  657. [FromQuery] bool? isLocked,
  658. [FromQuery] bool? isPlaceHolder,
  659. [FromQuery] bool? hasOfficialRating,
  660. [FromQuery] bool? collapseBoxSetItems,
  661. [FromQuery] int? minWidth,
  662. [FromQuery] int? minHeight,
  663. [FromQuery] int? maxWidth,
  664. [FromQuery] int? maxHeight,
  665. [FromQuery] bool? is3D,
  666. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
  667. [FromQuery] string? nameStartsWithOrGreater,
  668. [FromQuery] string? nameStartsWith,
  669. [FromQuery] string? nameLessThan,
  670. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
  671. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
  672. [FromQuery] bool enableTotalRecordCount = true,
  673. [FromQuery] bool? enableImages = true)
  674. => GetItems(
  675. userId,
  676. maxOfficialRating,
  677. hasThemeSong,
  678. hasThemeVideo,
  679. hasSubtitles,
  680. hasSpecialFeature,
  681. hasTrailer,
  682. adjacentTo,
  683. parentIndexNumber,
  684. hasParentalRating,
  685. isHd,
  686. is4K,
  687. locationTypes,
  688. excludeLocationTypes,
  689. isMissing,
  690. isUnaired,
  691. minCommunityRating,
  692. minCriticRating,
  693. minPremiereDate,
  694. minDateLastSaved,
  695. minDateLastSavedForUser,
  696. maxPremiereDate,
  697. hasOverview,
  698. hasImdbId,
  699. hasTmdbId,
  700. hasTvdbId,
  701. isMovie,
  702. isSeries,
  703. isNews,
  704. isKids,
  705. isSports,
  706. excludeItemIds,
  707. startIndex,
  708. limit,
  709. recursive,
  710. searchTerm,
  711. sortOrder,
  712. parentId,
  713. fields,
  714. excludeItemTypes,
  715. includeItemTypes,
  716. filters,
  717. isFavorite,
  718. mediaTypes,
  719. imageTypes,
  720. sortBy,
  721. isPlayed,
  722. genres,
  723. officialRatings,
  724. tags,
  725. years,
  726. enableUserData,
  727. imageTypeLimit,
  728. enableImageTypes,
  729. person,
  730. personIds,
  731. personTypes,
  732. studios,
  733. artists,
  734. excludeArtistIds,
  735. artistIds,
  736. albumArtistIds,
  737. contributingArtistIds,
  738. albums,
  739. albumIds,
  740. ids,
  741. videoTypes,
  742. minOfficialRating,
  743. isLocked,
  744. isPlaceHolder,
  745. hasOfficialRating,
  746. collapseBoxSetItems,
  747. minWidth,
  748. minHeight,
  749. maxWidth,
  750. maxHeight,
  751. is3D,
  752. seriesStatus,
  753. nameStartsWithOrGreater,
  754. nameStartsWith,
  755. nameLessThan,
  756. studioIds,
  757. genreIds,
  758. enableTotalRecordCount,
  759. enableImages);
  760. /// <summary>
  761. /// Gets items based on a query.
  762. /// </summary>
  763. /// <param name="userId">The user id.</param>
  764. /// <param name="startIndex">The start index.</param>
  765. /// <param name="limit">The item limit.</param>
  766. /// <param name="searchTerm">The search term.</param>
  767. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  768. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  769. /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
  770. /// <param name="enableUserData">Optional. Include user data.</param>
  771. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  772. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  773. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  774. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  775. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  776. /// <param name="enableImages">Optional. Include image information in output.</param>
  777. /// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param>
  778. /// <response code="200">Items returned.</response>
  779. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
  780. [HttpGet("UserItems/Resume")]
  781. [ProducesResponseType(StatusCodes.Status200OK)]
  782. public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
  783. [FromQuery] Guid? userId,
  784. [FromQuery] int? startIndex,
  785. [FromQuery] int? limit,
  786. [FromQuery] string? searchTerm,
  787. [FromQuery] Guid? parentId,
  788. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  789. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaTypes,
  790. [FromQuery] bool? enableUserData,
  791. [FromQuery] int? imageTypeLimit,
  792. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  793. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
  794. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
  795. [FromQuery] bool enableTotalRecordCount = true,
  796. [FromQuery] bool? enableImages = true,
  797. [FromQuery] bool excludeActiveSessions = false)
  798. {
  799. var requestUserId = RequestHelpers.GetUserId(User, userId);
  800. var user = _userManager.GetUserById(requestUserId);
  801. if (user is null)
  802. {
  803. return NotFound();
  804. }
  805. var parentIdGuid = parentId ?? Guid.Empty;
  806. var dtoOptions = new DtoOptions { Fields = fields }
  807. .AddClientFields(User)
  808. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  809. var ancestorIds = Array.Empty<Guid>();
  810. var excludeFolderIds = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes);
  811. if (parentIdGuid.IsEmpty() && excludeFolderIds.Length > 0)
  812. {
  813. ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
  814. .Where(i => i is Folder)
  815. .Where(i => !excludeFolderIds.Contains(i.Id))
  816. .Select(i => i.Id)
  817. .ToArray();
  818. }
  819. var excludeItemIds = Array.Empty<Guid>();
  820. if (excludeActiveSessions)
  821. {
  822. excludeItemIds = _sessionManager.Sessions
  823. .Where(s => s.UserId.Equals(requestUserId) && s.NowPlayingItem is not null)
  824. .Select(s => s.NowPlayingItem.Id)
  825. .ToArray();
  826. }
  827. var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  828. {
  829. OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
  830. IsResumable = true,
  831. StartIndex = startIndex,
  832. Limit = limit,
  833. ParentId = parentIdGuid,
  834. Recursive = true,
  835. DtoOptions = dtoOptions,
  836. MediaTypes = mediaTypes,
  837. IsVirtualItem = false,
  838. CollapseBoxSetItems = false,
  839. EnableTotalRecordCount = enableTotalRecordCount,
  840. AncestorIds = ancestorIds,
  841. IncludeItemTypes = includeItemTypes,
  842. ExcludeItemTypes = excludeItemTypes,
  843. SearchTerm = searchTerm,
  844. ExcludeItemIds = excludeItemIds
  845. });
  846. var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user);
  847. return new QueryResult<BaseItemDto>(
  848. startIndex,
  849. itemsResult.TotalRecordCount,
  850. returnItems);
  851. }
  852. /// <summary>
  853. /// Gets items based on a query.
  854. /// </summary>
  855. /// <param name="userId">The user id.</param>
  856. /// <param name="startIndex">The start index.</param>
  857. /// <param name="limit">The item limit.</param>
  858. /// <param name="searchTerm">The search term.</param>
  859. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  860. /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
  861. /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
  862. /// <param name="enableUserData">Optional. Include user data.</param>
  863. /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
  864. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  865. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
  866. /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
  867. /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
  868. /// <param name="enableImages">Optional. Include image information in output.</param>
  869. /// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param>
  870. /// <response code="200">Items returned.</response>
  871. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
  872. [HttpGet("Users/{userId}/Items/Resume")]
  873. [Obsolete("Kept for backwards compatibility")]
  874. [ApiExplorerSettings(IgnoreApi = true)]
  875. [ProducesResponseType(StatusCodes.Status200OK)]
  876. public ActionResult<QueryResult<BaseItemDto>> GetResumeItemsLegacy(
  877. [FromRoute, Required] Guid userId,
  878. [FromQuery] int? startIndex,
  879. [FromQuery] int? limit,
  880. [FromQuery] string? searchTerm,
  881. [FromQuery] Guid? parentId,
  882. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
  883. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaTypes,
  884. [FromQuery] bool? enableUserData,
  885. [FromQuery] int? imageTypeLimit,
  886. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
  887. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
  888. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
  889. [FromQuery] bool enableTotalRecordCount = true,
  890. [FromQuery] bool? enableImages = true,
  891. [FromQuery] bool excludeActiveSessions = false)
  892. => GetResumeItems(
  893. userId,
  894. startIndex,
  895. limit,
  896. searchTerm,
  897. parentId,
  898. fields,
  899. mediaTypes,
  900. enableUserData,
  901. imageTypeLimit,
  902. enableImageTypes,
  903. excludeItemTypes,
  904. includeItemTypes,
  905. enableTotalRecordCount,
  906. enableImages,
  907. excludeActiveSessions);
  908. /// <summary>
  909. /// Get Item User Data.
  910. /// </summary>
  911. /// <param name="userId">The user id.</param>
  912. /// <param name="itemId">The item id.</param>
  913. /// <response code="200">return item user data.</response>
  914. /// <response code="404">Item is not found.</response>
  915. /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
  916. [HttpGet("UserItems/{itemId}/UserData")]
  917. [ProducesResponseType(StatusCodes.Status200OK)]
  918. [ProducesResponseType(StatusCodes.Status404NotFound)]
  919. public ActionResult<UserItemDataDto> GetItemUserData(
  920. [FromQuery] Guid? userId,
  921. [FromRoute, Required] Guid itemId)
  922. {
  923. var requestUserId = RequestHelpers.GetUserId(User, userId);
  924. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
  925. {
  926. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to view this item user data.");
  927. }
  928. var user = _userManager.GetUserById(requestUserId) ?? throw new ResourceNotFoundException();
  929. var item = _libraryManager.GetItemById(itemId);
  930. return (item == null) ? NotFound() : _userDataRepository.GetUserDataDto(item, user);
  931. }
  932. /// <summary>
  933. /// Get Item User Data.
  934. /// </summary>
  935. /// <param name="userId">The user id.</param>
  936. /// <param name="itemId">The item id.</param>
  937. /// <response code="200">return item user data.</response>
  938. /// <response code="404">Item is not found.</response>
  939. /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
  940. [HttpGet("Users/{userId}/Items/{itemId}/UserData")]
  941. [ProducesResponseType(StatusCodes.Status200OK)]
  942. [ProducesResponseType(StatusCodes.Status404NotFound)]
  943. [Obsolete("Kept for backwards compatibility")]
  944. [ApiExplorerSettings(IgnoreApi = true)]
  945. public ActionResult<UserItemDataDto> GetItemUserDataLegacy(
  946. [FromRoute, Required] Guid userId,
  947. [FromRoute, Required] Guid itemId)
  948. => GetItemUserData(userId, itemId);
  949. /// <summary>
  950. /// Update Item User Data.
  951. /// </summary>
  952. /// <param name="userId">The user id.</param>
  953. /// <param name="itemId">The item id.</param>
  954. /// <param name="userDataDto">New user data object.</param>
  955. /// <response code="200">return updated user item data.</response>
  956. /// <response code="404">Item is not found.</response>
  957. /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
  958. [HttpPost("UserItems/{itemId}/UserData")]
  959. [ProducesResponseType(StatusCodes.Status200OK)]
  960. [ProducesResponseType(StatusCodes.Status404NotFound)]
  961. public ActionResult<UserItemDataDto> UpdateItemUserData(
  962. [FromQuery] Guid? userId,
  963. [FromRoute, Required] Guid itemId,
  964. [FromBody, Required] UpdateUserItemDataDto userDataDto)
  965. {
  966. var requestUserId = RequestHelpers.GetUserId(User, userId);
  967. if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
  968. {
  969. return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update this item user data.");
  970. }
  971. var user = _userManager.GetUserById(requestUserId) ?? throw new ResourceNotFoundException();
  972. var item = _libraryManager.GetItemById(itemId);
  973. if (item == null)
  974. {
  975. return NotFound();
  976. }
  977. _userDataRepository.SaveUserData(user, item, userDataDto, UserDataSaveReason.UpdateUserData);
  978. return _userDataRepository.GetUserDataDto(item, user);
  979. }
  980. /// <summary>
  981. /// Update Item User Data.
  982. /// </summary>
  983. /// <param name="userId">The user id.</param>
  984. /// <param name="itemId">The item id.</param>
  985. /// <param name="userDataDto">New user data object.</param>
  986. /// <response code="200">return updated user item data.</response>
  987. /// <response code="404">Item is not found.</response>
  988. /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
  989. [HttpPost("Users/{userId}/Items/{itemId}/UserData")]
  990. [ProducesResponseType(StatusCodes.Status200OK)]
  991. [ProducesResponseType(StatusCodes.Status404NotFound)]
  992. [Obsolete("Kept for backwards compatibility")]
  993. [ApiExplorerSettings(IgnoreApi = true)]
  994. public ActionResult<UserItemDataDto> UpdateItemUserDataLegacy(
  995. [FromRoute, Required] Guid userId,
  996. [FromRoute, Required] Guid itemId,
  997. [FromBody, Required] UpdateUserItemDataDto userDataDto)
  998. => UpdateItemUserData(userId, itemId, userDataDto);
  999. }