GenresController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Globalization;
  4. using System.Linq;
  5. using Jellyfin.Api.Constants;
  6. using Jellyfin.Api.Extensions;
  7. using Jellyfin.Api.Helpers;
  8. using Jellyfin.Api.ModelBinders;
  9. using Jellyfin.Data.Entities;
  10. using MediaBrowser.Controller.Dto;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Querying;
  16. using Microsoft.AspNetCore.Authorization;
  17. using Microsoft.AspNetCore.Http;
  18. using Microsoft.AspNetCore.Mvc;
  19. using Genre = MediaBrowser.Controller.Entities.Genre;
  20. namespace Jellyfin.Api.Controllers
  21. {
  22. /// <summary>
  23. /// The genres controller.
  24. /// </summary>
  25. [Authorize(Policy = Policies.DefaultAuthorization)]
  26. public class GenresController : BaseJellyfinApiController
  27. {
  28. private readonly IUserManager _userManager;
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IDtoService _dtoService;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="GenresController"/> class.
  33. /// </summary>
  34. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  35. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  36. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  37. public GenresController(
  38. IUserManager userManager,
  39. ILibraryManager libraryManager,
  40. IDtoService dtoService)
  41. {
  42. _userManager = userManager;
  43. _libraryManager = libraryManager;
  44. _dtoService = dtoService;
  45. }
  46. /// <summary>
  47. /// Gets all genres from a given item, folder, or the entire library.
  48. /// </summary>
  49. /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
  50. /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
  51. /// <param name="limit">Optional. The maximum number of records to return.</param>
  52. /// <param name="searchTerm">The search term.</param>
  53. /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
  54. /// <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>
  55. /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param>
  56. /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.</param>
  57. /// <param name="filters">Optional. Specify additional filters to apply.</param>
  58. /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
  59. /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
  60. /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
  61. /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
  62. /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
  63. /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
  64. /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
  65. /// <param name="enableUserData">Optional, include user data.</param>
  66. /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
  67. /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
  68. /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
  69. /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
  70. /// <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>
  71. /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
  72. /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
  73. /// <param name="userId">User id.</param>
  74. /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
  75. /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
  76. /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
  77. /// <param name="enableImages">Optional, include image information in output.</param>
  78. /// <param name="enableTotalRecordCount">Optional. Include total record count.</param>
  79. /// <response code="200">Genres returned.</response>
  80. /// <returns>An <see cref="OkResult"/> containing the queryresult of genres.</returns>
  81. [HttpGet]
  82. [ProducesResponseType(StatusCodes.Status200OK)]
  83. public ActionResult<QueryResult<BaseItemDto>> GetGenres(
  84. [FromQuery] double? minCommunityRating,
  85. [FromQuery] int? startIndex,
  86. [FromQuery] int? limit,
  87. [FromQuery] string? searchTerm,
  88. [FromQuery] string? parentId,
  89. [FromQuery] string? fields,
  90. [FromQuery] string? excludeItemTypes,
  91. [FromQuery] string? includeItemTypes,
  92. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
  93. [FromQuery] bool? isFavorite,
  94. [FromQuery] string? mediaTypes,
  95. [FromQuery] string? genres,
  96. [FromQuery] string? genreIds,
  97. [FromQuery] string? officialRatings,
  98. [FromQuery] string? tags,
  99. [FromQuery] string? years,
  100. [FromQuery] bool? enableUserData,
  101. [FromQuery] int? imageTypeLimit,
  102. [FromQuery] ImageType[] enableImageTypes,
  103. [FromQuery] string? person,
  104. [FromQuery] string? personIds,
  105. [FromQuery] string? personTypes,
  106. [FromQuery] string? studios,
  107. [FromQuery] string? studioIds,
  108. [FromQuery] Guid? userId,
  109. [FromQuery] string? nameStartsWithOrGreater,
  110. [FromQuery] string? nameStartsWith,
  111. [FromQuery] string? nameLessThan,
  112. [FromQuery] bool? enableImages = true,
  113. [FromQuery] bool enableTotalRecordCount = true)
  114. {
  115. var dtoOptions = new DtoOptions()
  116. .AddItemFields(fields)
  117. .AddClientFields(Request)
  118. .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
  119. User? user = null;
  120. BaseItem parentItem;
  121. if (userId.HasValue && !userId.Equals(Guid.Empty))
  122. {
  123. user = _userManager.GetUserById(userId.Value);
  124. parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
  125. }
  126. else
  127. {
  128. parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
  129. }
  130. var query = new InternalItemsQuery(user)
  131. {
  132. ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
  133. IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
  134. MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
  135. StartIndex = startIndex,
  136. Limit = limit,
  137. IsFavorite = isFavorite,
  138. NameLessThan = nameLessThan,
  139. NameStartsWith = nameStartsWith,
  140. NameStartsWithOrGreater = nameStartsWithOrGreater,
  141. Tags = RequestHelpers.Split(tags, '|', true),
  142. OfficialRatings = RequestHelpers.Split(officialRatings, '|', true),
  143. Genres = RequestHelpers.Split(genres, '|', true),
  144. GenreIds = RequestHelpers.GetGuids(genreIds),
  145. StudioIds = RequestHelpers.GetGuids(studioIds),
  146. Person = person,
  147. PersonIds = RequestHelpers.GetGuids(personIds),
  148. PersonTypes = RequestHelpers.Split(personTypes, ',', true),
  149. Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(),
  150. MinCommunityRating = minCommunityRating,
  151. DtoOptions = dtoOptions,
  152. SearchTerm = searchTerm,
  153. EnableTotalRecordCount = enableTotalRecordCount
  154. };
  155. if (!string.IsNullOrWhiteSpace(parentId))
  156. {
  157. if (parentItem is Folder)
  158. {
  159. query.AncestorIds = new[] { new Guid(parentId) };
  160. }
  161. else
  162. {
  163. query.ItemIds = new[] { new Guid(parentId) };
  164. }
  165. }
  166. // Studios
  167. if (!string.IsNullOrEmpty(studios))
  168. {
  169. query.StudioIds = studios.Split('|')
  170. .Select(i =>
  171. {
  172. try
  173. {
  174. return _libraryManager.GetStudio(i);
  175. }
  176. catch
  177. {
  178. return null;
  179. }
  180. }).Where(i => i != null)
  181. .Select(i => i!.Id)
  182. .ToArray();
  183. }
  184. foreach (var filter in filters)
  185. {
  186. switch (filter)
  187. {
  188. case ItemFilter.Dislikes:
  189. query.IsLiked = false;
  190. break;
  191. case ItemFilter.IsFavorite:
  192. query.IsFavorite = true;
  193. break;
  194. case ItemFilter.IsFavoriteOrLikes:
  195. query.IsFavoriteOrLiked = true;
  196. break;
  197. case ItemFilter.IsFolder:
  198. query.IsFolder = true;
  199. break;
  200. case ItemFilter.IsNotFolder:
  201. query.IsFolder = false;
  202. break;
  203. case ItemFilter.IsPlayed:
  204. query.IsPlayed = true;
  205. break;
  206. case ItemFilter.IsResumable:
  207. query.IsResumable = true;
  208. break;
  209. case ItemFilter.IsUnplayed:
  210. query.IsPlayed = false;
  211. break;
  212. case ItemFilter.Likes:
  213. query.IsLiked = true;
  214. break;
  215. }
  216. }
  217. var result = new QueryResult<(BaseItem, ItemCounts)>();
  218. var dtos = result.Items.Select(i =>
  219. {
  220. var (baseItem, counts) = i;
  221. var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
  222. if (!string.IsNullOrWhiteSpace(includeItemTypes))
  223. {
  224. dto.ChildCount = counts.ItemCount;
  225. dto.ProgramCount = counts.ProgramCount;
  226. dto.SeriesCount = counts.SeriesCount;
  227. dto.EpisodeCount = counts.EpisodeCount;
  228. dto.MovieCount = counts.MovieCount;
  229. dto.TrailerCount = counts.TrailerCount;
  230. dto.AlbumCount = counts.AlbumCount;
  231. dto.SongCount = counts.SongCount;
  232. dto.ArtistCount = counts.ArtistCount;
  233. }
  234. return dto;
  235. });
  236. return new QueryResult<BaseItemDto>
  237. {
  238. Items = dtos.ToArray(),
  239. TotalRecordCount = result.TotalRecordCount
  240. };
  241. }
  242. /// <summary>
  243. /// Gets a genre, by name.
  244. /// </summary>
  245. /// <param name="genreName">The genre name.</param>
  246. /// <param name="userId">The user id.</param>
  247. /// <response code="200">Genres returned.</response>
  248. /// <returns>An <see cref="OkResult"/> containing the genre.</returns>
  249. [HttpGet("{genreName}")]
  250. [ProducesResponseType(StatusCodes.Status200OK)]
  251. public ActionResult<BaseItemDto> GetGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
  252. {
  253. var dtoOptions = new DtoOptions()
  254. .AddClientFields(Request);
  255. Genre item = new Genre();
  256. if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1)
  257. {
  258. var result = GetItemFromSlugName<Genre>(_libraryManager, genreName, dtoOptions);
  259. if (result != null)
  260. {
  261. item = result;
  262. }
  263. }
  264. else
  265. {
  266. item = _libraryManager.GetGenre(genreName);
  267. }
  268. if (userId.HasValue && !userId.Equals(Guid.Empty))
  269. {
  270. var user = _userManager.GetUserById(userId.Value);
  271. return _dtoService.GetBaseItemDto(item, dtoOptions, user);
  272. }
  273. return _dtoService.GetBaseItemDto(item, dtoOptions);
  274. }
  275. private T GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
  276. where T : BaseItem, new()
  277. {
  278. var result = libraryManager.GetItemList(new InternalItemsQuery
  279. {
  280. Name = name.Replace(BaseItem.SlugChar, '&'),
  281. IncludeItemTypes = new[] { typeof(T).Name },
  282. DtoOptions = dtoOptions
  283. }).OfType<T>().FirstOrDefault();
  284. result ??= libraryManager.GetItemList(new InternalItemsQuery
  285. {
  286. Name = name.Replace(BaseItem.SlugChar, '/'),
  287. IncludeItemTypes = new[] { typeof(T).Name },
  288. DtoOptions = dtoOptions
  289. }).OfType<T>().FirstOrDefault();
  290. result ??= libraryManager.GetItemList(new InternalItemsQuery
  291. {
  292. Name = name.Replace(BaseItem.SlugChar, '?'),
  293. IncludeItemTypes = new[] { typeof(T).Name },
  294. DtoOptions = dtoOptions
  295. }).OfType<T>().FirstOrDefault();
  296. return result;
  297. }
  298. }
  299. }