GenresController.cs 15 KB

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