ItemsController.cs 59 KB

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