< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.TvShowsController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/TvShowsController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 126
Coverable lines: 126
Total lines: 390
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 46
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 9/19/2025 - 12:11:12 AM Line coverage: 0% (0/130) Branch coverage: 0% (0/46) Total lines: 39412/1/2025 - 12:11:46 AM Line coverage: 0% (0/126) Branch coverage: 0% (0/46) Total lines: 390 9/19/2025 - 12:11:12 AM Line coverage: 0% (0/130) Branch coverage: 0% (0/46) Total lines: 39412/1/2025 - 12:11:46 AM Line coverage: 0% (0/126) Branch coverage: 0% (0/46) Total lines: 390

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetNextUp(...)0%2040%
GetUpcomingEpisodes(...)0%2040%
GetEpisodes(...)0%930300%
GetSeasons(...)0%2040%
ApplyPaging(...)0%2040%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel.DataAnnotations;
 4using System.Linq;
 5using Jellyfin.Api.Attributes;
 6using Jellyfin.Api.Extensions;
 7using Jellyfin.Api.Helpers;
 8using Jellyfin.Api.ModelBinders;
 9using Jellyfin.Data.Enums;
 10using Jellyfin.Database.Implementations.Enums;
 11using Jellyfin.Extensions;
 12using MediaBrowser.Controller.Dto;
 13using MediaBrowser.Controller.Entities;
 14using MediaBrowser.Controller.Entities.TV;
 15using MediaBrowser.Controller.Library;
 16using MediaBrowser.Controller.TV;
 17using MediaBrowser.Model.Dto;
 18using MediaBrowser.Model.Entities;
 19using MediaBrowser.Model.Querying;
 20using Microsoft.AspNetCore.Authorization;
 21using Microsoft.AspNetCore.Http;
 22using Microsoft.AspNetCore.Mvc;
 23
 24namespace Jellyfin.Api.Controllers;
 25
 26/// <summary>
 27/// The tv shows controller.
 28/// </summary>
 29[Route("Shows")]
 30[Authorize]
 31public class TvShowsController : BaseJellyfinApiController
 32{
 33    private readonly IUserManager _userManager;
 34    private readonly ILibraryManager _libraryManager;
 35    private readonly IDtoService _dtoService;
 36    private readonly ITVSeriesManager _tvSeriesManager;
 37
 38    /// <summary>
 39    /// Initializes a new instance of the <see cref="TvShowsController"/> class.
 40    /// </summary>
 41    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 42    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 43    /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
 44    /// <param name="tvSeriesManager">Instance of the <see cref="ITVSeriesManager"/> interface.</param>
 045    public TvShowsController(
 046        IUserManager userManager,
 047        ILibraryManager libraryManager,
 048        IDtoService dtoService,
 049        ITVSeriesManager tvSeriesManager)
 50    {
 051        _userManager = userManager;
 052        _libraryManager = libraryManager;
 053        _dtoService = dtoService;
 054        _tvSeriesManager = tvSeriesManager;
 055    }
 56
 57    /// <summary>
 58    /// Gets a list of next up episodes.
 59    /// </summary>
 60    /// <param name="userId">The user id of the user to get the next up episodes for.</param>
 61    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 62    /// <param name="limit">Optional. The maximum number of records to return.</param>
 63    /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
 64    /// <param name="seriesId">Optional. Filter by series id.</param>
 65    /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use t
 66    /// <param name="enableImages">Optional. Include image information in output.</param>
 67    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
 68    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 69    /// <param name="enableUserData">Optional. Include user data.</param>
 70    /// <param name="nextUpDateCutoff">Optional. Starting date of shows to show in Next Up section.</param>
 71    /// <param name="enableTotalRecordCount">Whether to enable the total records count. Defaults to true.</param>
 72    /// <param name="disableFirstEpisode">Whether to disable sending the first episode in a series as next up.</param>
 73    /// <param name="enableResumable">Whether to include resumable episodes in next up results.</param>
 74    /// <param name="enableRewatching">Whether to include watched episodes in next up results.</param>
 75    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the next up episodes.</returns>
 76    [HttpGet("NextUp")]
 77    [ProducesResponseType(StatusCodes.Status200OK)]
 78    public ActionResult<QueryResult<BaseItemDto>> GetNextUp(
 79        [FromQuery] Guid? userId,
 80        [FromQuery] int? startIndex,
 81        [FromQuery] int? limit,
 82        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
 83        [FromQuery] Guid? seriesId,
 84        [FromQuery] Guid? parentId,
 85        [FromQuery] bool? enableImages,
 86        [FromQuery] int? imageTypeLimit,
 87        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
 88        [FromQuery] bool? enableUserData,
 89        [FromQuery] DateTime? nextUpDateCutoff,
 90        [FromQuery] bool enableTotalRecordCount = true,
 91        [FromQuery][ParameterObsolete] bool disableFirstEpisode = false,
 92        [FromQuery] bool enableResumable = true,
 93        [FromQuery] bool enableRewatching = false)
 94    {
 095        var user = _userManager.GetUserById(RequestHelpers.GetUserId(User, userId));
 096        if (user is null)
 97        {
 098            return NotFound();
 99        }
 100
 0101        var options = new DtoOptions { Fields = fields }
 0102            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 103
 0104        var result = _tvSeriesManager.GetNextUp(
 0105            new NextUpQuery
 0106            {
 0107                Limit = limit,
 0108                ParentId = parentId,
 0109                SeriesId = seriesId,
 0110                StartIndex = startIndex,
 0111                User = user,
 0112                EnableTotalRecordCount = enableTotalRecordCount,
 0113                NextUpDateCutoff = nextUpDateCutoff ?? DateTime.MinValue,
 0114                EnableResumable = enableResumable,
 0115                EnableRewatching = enableRewatching
 0116            },
 0117            options);
 118
 0119        var returnItems = _dtoService.GetBaseItemDtos(result.Items, options, user);
 120
 0121        return new QueryResult<BaseItemDto>(
 0122            startIndex,
 0123            result.TotalRecordCount,
 0124            returnItems);
 125    }
 126
 127    /// <summary>
 128    /// Gets a list of upcoming episodes.
 129    /// </summary>
 130    /// <param name="userId">The user id of the user to get the upcoming episodes for.</param>
 131    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 132    /// <param name="limit">Optional. The maximum number of records to return.</param>
 133    /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
 134    /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use t
 135    /// <param name="enableImages">Optional. Include image information in output.</param>
 136    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
 137    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 138    /// <param name="enableUserData">Optional. Include user data.</param>
 139    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the upcoming episodes.</returns>
 140    [HttpGet("Upcoming")]
 141    [ProducesResponseType(StatusCodes.Status200OK)]
 142    public ActionResult<QueryResult<BaseItemDto>> GetUpcomingEpisodes(
 143        [FromQuery] Guid? userId,
 144        [FromQuery] int? startIndex,
 145        [FromQuery] int? limit,
 146        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
 147        [FromQuery] Guid? parentId,
 148        [FromQuery] bool? enableImages,
 149        [FromQuery] int? imageTypeLimit,
 150        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
 151        [FromQuery] bool? enableUserData)
 152    {
 0153        userId = RequestHelpers.GetUserId(User, userId);
 0154        var user = userId.IsNullOrEmpty()
 0155            ? null
 0156            : _userManager.GetUserById(userId.Value);
 157
 0158        var minPremiereDate = DateTime.UtcNow.Date.AddDays(-1);
 159
 0160        var parentIdGuid = parentId ?? Guid.Empty;
 161
 0162        var options = new DtoOptions { Fields = fields }
 0163            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 164
 0165        var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user)
 0166        {
 0167            IncludeItemTypes = new[] { BaseItemKind.Episode },
 0168            OrderBy = new[] { (ItemSortBy.PremiereDate, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending)
 0169            MinPremiereDate = minPremiereDate,
 0170            StartIndex = startIndex,
 0171            Limit = limit,
 0172            ParentId = parentIdGuid,
 0173            Recursive = true,
 0174            DtoOptions = options
 0175        });
 176
 0177        var returnItems = _dtoService.GetBaseItemDtos(itemsResult, options, user);
 178
 0179        return new QueryResult<BaseItemDto>(
 0180            startIndex,
 0181            itemsResult.Count,
 0182            returnItems);
 183    }
 184
 185    /// <summary>
 186    /// Gets episodes for a tv season.
 187    /// </summary>
 188    /// <param name="seriesId">The series id.</param>
 189    /// <param name="userId">The user id.</param>
 190    /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows mul
 191    /// <param name="season">Optional filter by season number.</param>
 192    /// <param name="seasonId">Optional. Filter by season id.</param>
 193    /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
 194    /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
 195    /// <param name="startItemId">Optional. Skip through the list until a given item is found.</param>
 196    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 197    /// <param name="limit">Optional. The maximum number of records to return.</param>
 198    /// <param name="enableImages">Optional, include image information in output.</param>
 199    /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
 200    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 201    /// <param name="enableUserData">Optional. Include user data.</param>
 202    /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Ar
 203    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the episodes on success or a <see cref="NotFoundResult"/>
 204    [HttpGet("{seriesId}/Episodes")]
 205    [ProducesResponseType(StatusCodes.Status200OK)]
 206    [ProducesResponseType(StatusCodes.Status404NotFound)]
 207    public ActionResult<QueryResult<BaseItemDto>> GetEpisodes(
 208        [FromRoute, Required] Guid seriesId,
 209        [FromQuery] Guid? userId,
 210        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
 211        [FromQuery] int? season,
 212        [FromQuery] Guid? seasonId,
 213        [FromQuery] bool? isMissing,
 214        [FromQuery] Guid? adjacentTo,
 215        [FromQuery] Guid? startItemId,
 216        [FromQuery] int? startIndex,
 217        [FromQuery] int? limit,
 218        [FromQuery] bool? enableImages,
 219        [FromQuery] int? imageTypeLimit,
 220        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
 221        [FromQuery] bool? enableUserData,
 222        [FromQuery] ItemSortBy? sortBy)
 223    {
 0224        userId = RequestHelpers.GetUserId(User, userId);
 0225        var user = userId.IsNullOrEmpty()
 0226            ? null
 0227            : _userManager.GetUserById(userId.Value);
 228
 229        List<BaseItem> episodes;
 230
 0231        var dtoOptions = new DtoOptions { Fields = fields }
 0232            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 0233        var shouldIncludeMissingEpisodes = (user is not null && user.DisplayMissingEpisodes) || User.GetIsApiKey();
 234
 0235        if (seasonId.HasValue) // Season id was supplied. Get episodes by season id.
 236        {
 0237            var item = _libraryManager.GetItemById<BaseItem>(seasonId.Value);
 0238            if (item is not Season seasonItem)
 239            {
 0240                return NotFound("No season exists with Id " + seasonId);
 241            }
 242
 0243            episodes = seasonItem.GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes);
 244        }
 0245        else if (season.HasValue) // Season number was supplied. Get episodes by season number
 246        {
 0247            var series = _libraryManager.GetItemById<Series>(seriesId);
 0248            if (series is null)
 249            {
 0250                return NotFound("Series not found");
 251            }
 252
 0253            var seasonItem = series
 0254                .GetSeasons(user, dtoOptions)
 0255                .FirstOrDefault(i => i.IndexNumber == season.Value);
 256
 0257            episodes = seasonItem is null ?
 0258                new List<BaseItem>()
 0259                : ((Season)seasonItem).GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes);
 260        }
 261        else // No season number or season id was supplied. Returning all episodes.
 262        {
 0263            if (_libraryManager.GetItemById<BaseItem>(seriesId) is not Series series)
 264            {
 0265                return NotFound("Series not found");
 266            }
 267
 0268            episodes = series.GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes).ToList();
 269        }
 270
 271        // Filter after the fact in case the ui doesn't want them
 0272        if (isMissing.HasValue)
 273        {
 0274            var val = isMissing.Value;
 0275            episodes = episodes
 0276                .Where(i => ((Episode)i).IsMissingEpisode == val)
 0277                .ToList();
 278        }
 279
 0280        if (startItemId.HasValue)
 281        {
 0282            episodes = episodes
 0283                .SkipWhile(i => !startItemId.Value.Equals(i.Id))
 0284                .ToList();
 285        }
 286
 287        // This must be the last filter
 0288        if (!adjacentTo.IsNullOrEmpty())
 289        {
 0290            episodes = UserViewBuilder.FilterForAdjacency(episodes, adjacentTo.Value).ToList();
 291        }
 292
 0293        if (sortBy == ItemSortBy.Random)
 294        {
 0295            episodes.Shuffle();
 296        }
 297
 0298        var returnItems = episodes;
 299
 0300        if (startIndex.HasValue || limit.HasValue)
 301        {
 0302            returnItems = ApplyPaging(episodes, startIndex, limit).ToList();
 303        }
 304
 0305        var dtos = _dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
 306
 0307        return new QueryResult<BaseItemDto>(
 0308            startIndex,
 0309            episodes.Count,
 0310            dtos);
 311    }
 312
 313    /// <summary>
 314    /// Gets seasons for a tv series.
 315    /// </summary>
 316    /// <param name="seriesId">The series id.</param>
 317    /// <param name="userId">The user id.</param>
 318    /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows mul
 319    /// <param name="isSpecialSeason">Optional. Filter by special season.</param>
 320    /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
 321    /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
 322    /// <param name="enableImages">Optional. Include image information in output.</param>
 323    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
 324    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 325    /// <param name="enableUserData">Optional. Include user data.</param>
 326    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> on success or a <see cref="NotFoundResult"/> if the series was
 327    [HttpGet("{seriesId}/Seasons")]
 328    [ProducesResponseType(StatusCodes.Status200OK)]
 329    [ProducesResponseType(StatusCodes.Status404NotFound)]
 330    public ActionResult<QueryResult<BaseItemDto>> GetSeasons(
 331        [FromRoute, Required] Guid seriesId,
 332        [FromQuery] Guid? userId,
 333        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
 334        [FromQuery] bool? isSpecialSeason,
 335        [FromQuery] bool? isMissing,
 336        [FromQuery] Guid? adjacentTo,
 337        [FromQuery] bool? enableImages,
 338        [FromQuery] int? imageTypeLimit,
 339        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
 340        [FromQuery] bool? enableUserData)
 341    {
 0342        userId = RequestHelpers.GetUserId(User, userId);
 0343        var user = userId.IsNullOrEmpty()
 0344            ? null
 0345            : _userManager.GetUserById(userId.Value);
 0346        var item = _libraryManager.GetItemById<Series>(seriesId, user);
 0347        if (item is null)
 348        {
 0349            return NotFound();
 350        }
 351
 0352        var seasons = item.GetItemList(new InternalItemsQuery(user)
 0353        {
 0354            IsMissing = isMissing,
 0355            IsSpecialSeason = isSpecialSeason,
 0356            AdjacentTo = adjacentTo
 0357        });
 358
 0359        var dtoOptions = new DtoOptions { Fields = fields }
 0360            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 361
 0362        var returnItems = _dtoService.GetBaseItemDtos(seasons, dtoOptions, user);
 363
 0364        return new QueryResult<BaseItemDto>(returnItems);
 365    }
 366
 367    /// <summary>
 368    /// Applies the paging.
 369    /// </summary>
 370    /// <param name="items">The items.</param>
 371    /// <param name="startIndex">The start index.</param>
 372    /// <param name="limit">The limit.</param>
 373    /// <returns>IEnumerable{BaseItem}.</returns>
 374    private IEnumerable<BaseItem> ApplyPaging(IEnumerable<BaseItem> items, int? startIndex, int? limit)
 375    {
 376        // Start at
 0377        if (startIndex.HasValue)
 378        {
 0379            items = items.Skip(startIndex.Value);
 380        }
 381
 382        // Return limit
 0383        if (limit.HasValue)
 384        {
 0385            items = items.Take(limit.Value);
 386        }
 387
 0388        return items;
 389    }
 390}

Methods/Properties

.ctor(MediaBrowser.Controller.Library.IUserManager,MediaBrowser.Controller.Library.ILibraryManager,MediaBrowser.Controller.Dto.IDtoService,MediaBrowser.Controller.TV.ITVSeriesManager)
GetNextUp(System.Nullable`1<System.Guid>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Querying.ItemFields[],System.Nullable`1<System.Guid>,System.Nullable`1<System.Guid>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Entities.ImageType[],System.Nullable`1<System.Boolean>,System.Nullable`1<System.DateTime>,System.Boolean,System.Boolean,System.Boolean,System.Boolean)
GetUpcomingEpisodes(System.Nullable`1<System.Guid>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Querying.ItemFields[],System.Nullable`1<System.Guid>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Entities.ImageType[],System.Nullable`1<System.Boolean>)
GetEpisodes(System.Guid,System.Nullable`1<System.Guid>,MediaBrowser.Model.Querying.ItemFields[],System.Nullable`1<System.Int32>,System.Nullable`1<System.Guid>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Guid>,System.Nullable`1<System.Guid>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Entities.ImageType[],System.Nullable`1<System.Boolean>,System.Nullable`1<Jellyfin.Data.Enums.ItemSortBy>)
GetSeasons(System.Guid,System.Nullable`1<System.Guid>,MediaBrowser.Model.Querying.ItemFields[],System.Nullable`1<System.Boolean>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Guid>,System.Nullable`1<System.Boolean>,System.Nullable`1<System.Int32>,MediaBrowser.Model.Entities.ImageType[],System.Nullable`1<System.Boolean>)
ApplyPaging(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>)