< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.GenresController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/GenresController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 71
Coverable lines: 71
Total lines: 214
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 28
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/16/2026 - 12:15:55 AM Line coverage: 0% (0/70) Branch coverage: 0% (0/22) Total lines: 20910/29/2026 - 12:17:11 AM Line coverage: 0% (0/71) Branch coverage: 0% (0/28) Total lines: 214 5/16/2026 - 12:15:55 AM Line coverage: 0% (0/70) Branch coverage: 0% (0/22) Total lines: 20910/29/2026 - 12:17:11 AM Line coverage: 0% (0/71) Branch coverage: 0% (0/28) Total lines: 214

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetGenres(...)0%342180%
GetGenre(...)0%4260%
GetItemFromSlugName(...)0%2040%

File(s)

/srv/git/jellyfin/Jellyfin.Api/Controllers/GenresController.cs

#LineLine coverage
 1using System;
 2using System.ComponentModel.DataAnnotations;
 3using System.Linq;
 4using Jellyfin.Api.Extensions;
 5using Jellyfin.Api.Helpers;
 6using Jellyfin.Api.ModelBinders;
 7using Jellyfin.Data.Enums;
 8using Jellyfin.Database.Implementations.Entities;
 9using Jellyfin.Database.Implementations.Enums;
 10using Jellyfin.Extensions;
 11using MediaBrowser.Controller.Dto;
 12using MediaBrowser.Controller.Entities;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Model.Dto;
 15using MediaBrowser.Model.Entities;
 16using MediaBrowser.Model.Querying;
 17using Microsoft.AspNetCore.Authorization;
 18using Microsoft.AspNetCore.Http;
 19using Microsoft.AspNetCore.Mvc;
 20using Genre = MediaBrowser.Controller.Entities.Genre;
 21
 22namespace Jellyfin.Api.Controllers;
 23
 24/// <summary>
 25/// The genres controller.
 26/// </summary>
 27[Authorize]
 28[Tags("Genre")]
 29public class GenresController : BaseJellyfinApiController
 30{
 31    private readonly IUserManager _userManager;
 32    private readonly ILibraryManager _libraryManager;
 33    private readonly IDtoService _dtoService;
 34
 35    /// <summary>
 36    /// Initializes a new instance of the <see cref="GenresController"/> class.
 37    /// </summary>
 38    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 39    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 40    /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
 041    public GenresController(
 042        IUserManager userManager,
 043        ILibraryManager libraryManager,
 044        IDtoService dtoService)
 45    {
 046        _userManager = userManager;
 047        _libraryManager = libraryManager;
 048        _dtoService = dtoService;
 049    }
 50
 51    /// <summary>
 52    /// Gets all genres from a given item, folder, or the entire library.
 53    /// </summary>
 54    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 55    /// <param name="limit">Optional. The maximum number of records to return.</param>
 56    /// <param name="searchTerm">The search term.</param>
 57    /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</
 58    /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
 59    /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This all
 60    /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allo
 61    /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
 62    /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
 63    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 64    /// <param name="userId">User id.</param>
 65    /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a gi
 66    /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</p
 67    /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</
 68    /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited.</param>
 69    /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
 70    /// <param name="enableImages">Optional, include image information in output.</param>
 71    /// <param name="enableTotalRecordCount">Optional. Include total record count.</param>
 72    /// <response code="200">Genres returned.</response>
 73    /// <returns>An <see cref="OkResult"/> containing the queryresult of genres.</returns>
 74    [HttpGet]
 75    [ProducesResponseType(StatusCodes.Status200OK)]
 76    public ActionResult<QueryResult<BaseItemDto>> GetGenres(
 77        [FromQuery] int? startIndex,
 78        [FromQuery] int? limit,
 79        [FromQuery] string? searchTerm,
 80        [FromQuery] Guid? parentId,
 81        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
 82        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] excludeItemTypes,
 83        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] BaseItemKind[] includeItemTypes,
 84        [FromQuery] bool? isFavorite,
 85        [FromQuery] int? imageTypeLimit,
 86        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
 87        [FromQuery] Guid? userId,
 88        [FromQuery] string? nameStartsWithOrGreater,
 89        [FromQuery] string? nameStartsWith,
 90        [FromQuery] string? nameLessThan,
 91        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemSortBy[] sortBy,
 92        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] SortOrder[] sortOrder,
 93        [FromQuery] bool? enableImages = true,
 94        [FromQuery] bool enableTotalRecordCount = true)
 95    {
 096        userId = RequestHelpers.GetUserId(User, userId);
 097        var dtoOptions = new DtoOptions { Fields = fields }
 098            .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
 99
 100        // Asking for a type filter has always implied wanting that type's counts back.
 0101        if (includeItemTypes.Length != 0 && !dtoOptions.ContainsField(ItemFields.ItemCounts))
 102        {
 0103            dtoOptions.Fields = [.. dtoOptions.Fields, ItemFields.ItemCounts];
 104        }
 105
 0106        User? user = userId.IsNullOrEmpty()
 0107            ? null
 0108            : _userManager.GetUserById(userId.Value);
 109
 0110        var parentItem = _libraryManager.GetParentItem(parentId, userId);
 111
 0112        var query = new InternalItemsQuery(user)
 0113        {
 0114            ExcludeItemTypes = excludeItemTypes,
 0115            IncludeItemTypes = includeItemTypes,
 0116            StartIndex = startIndex,
 0117            Limit = limit,
 0118            IsFavorite = isFavorite,
 0119            NameLessThan = nameLessThan,
 0120            NameStartsWith = nameStartsWith,
 0121            NameStartsWithOrGreater = nameStartsWithOrGreater,
 0122            DtoOptions = dtoOptions,
 0123            SearchTerm = searchTerm,
 0124            EnableTotalRecordCount = enableTotalRecordCount,
 0125            OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder)
 0126        };
 127
 0128        if (parentId.HasValue)
 129        {
 0130            if (parentItem is Folder)
 131            {
 0132                query.AncestorIds = new[] { parentId.Value };
 133            }
 134            else
 135            {
 0136                query.ItemIds = new[] { parentId.Value };
 137            }
 138        }
 139
 140        QueryResult<(BaseItem, ItemCounts)> result;
 0141        if (parentItem is ICollectionFolder parentCollectionFolder
 0142            && (parentCollectionFolder.CollectionType == CollectionType.music
 0143                || parentCollectionFolder.CollectionType == CollectionType.musicvideos))
 144        {
 0145            result = _libraryManager.GetMusicGenres(query);
 146        }
 147        else
 148        {
 0149            result = _libraryManager.GetGenres(query);
 150        }
 151
 0152        return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, user);
 153    }
 154
 155    /// <summary>
 156    /// Gets a genre, by name.
 157    /// </summary>
 158    /// <param name="genreName">The genre name.</param>
 159    /// <param name="userId">The user id.</param>
 160    /// <response code="200">Genres returned.</response>
 161    /// <returns>An <see cref="OkResult"/> containing the genre.</returns>
 162    [HttpGet("{genreName}")]
 163    [ProducesResponseType(StatusCodes.Status200OK)]
 164    public ActionResult<BaseItemDto> GetGenre([FromRoute, Required] string genreName, [FromQuery] Guid? userId)
 165    {
 0166        userId = RequestHelpers.GetUserId(User, userId);
 0167        var dtoOptions = new DtoOptions();
 168
 169        Genre? item;
 0170        if (genreName.Contains(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase))
 171        {
 0172            item = GetItemFromSlugName<Genre>(_libraryManager, genreName, dtoOptions, BaseItemKind.Genre);
 173        }
 174        else
 175        {
 0176            item = _libraryManager.GetGenre(genreName);
 177        }
 178
 0179        item ??= new Genre();
 180
 0181        var user = userId.IsNullOrEmpty()
 0182            ? null
 0183            : _userManager.GetUserById(userId.Value);
 184
 0185        return _dtoService.GetBaseItemDto(item, dtoOptions, user);
 186    }
 187
 188    private T? GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions, BaseItemKind b
 189        where T : BaseItem, new()
 190    {
 0191        var result = libraryManager.GetItemList(new InternalItemsQuery
 0192        {
 0193            Name = name.Replace(BaseItem.SlugChar, '&'),
 0194            IncludeItemTypes = new[] { baseItemKind },
 0195            DtoOptions = dtoOptions
 0196        }).OfType<T>().FirstOrDefault();
 197
 0198        result ??= libraryManager.GetItemList(new InternalItemsQuery
 0199        {
 0200            Name = name.Replace(BaseItem.SlugChar, '/'),
 0201            IncludeItemTypes = new[] { baseItemKind },
 0202            DtoOptions = dtoOptions
 0203        }).OfType<T>().FirstOrDefault();
 204
 0205        result ??= libraryManager.GetItemList(new InternalItemsQuery
 0206        {
 0207            Name = name.Replace(BaseItem.SlugChar, '?'),
 0208            IncludeItemTypes = new[] { baseItemKind },
 0209            DtoOptions = dtoOptions
 0210        }).OfType<T>().FirstOrDefault();
 211
 0212        return result;
 213    }
 214}