ItemsController.cs 59 KB

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