GenresController.cs 15 KB

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