GenresController.cs 15 KB

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