ItemsController.cs 59 KB

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