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