ItemsController.cs 59 KB

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