< 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: 131
Coverable lines: 131
Total lines: 393
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

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.Extensions;
 6using Jellyfin.Api.Helpers;
 7using Jellyfin.Api.ModelBinders;
 8using Jellyfin.Data.Enums;
 9using Jellyfin.Extensions;
 10using MediaBrowser.Controller.Dto;
 11using MediaBrowser.Controller.Entities;
 12using MediaBrowser.Controller.Entities.TV;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Controller.TV;
 15using MediaBrowser.Model.Dto;
 16using MediaBrowser.Model.Entities;
 17using MediaBrowser.Model.Querying;
 18using Microsoft.AspNetCore.Authorization;
 19using Microsoft.AspNetCore.Http;
 20using Microsoft.AspNetCore.Mvc;
 21
 22namespace Jellyfin.Api.Controllers;
 23
 24/// <summary>
 25/// The tv shows controller.
 26/// </summary>
 27[Route("Shows")]
 28[Authorize]
 29public class TvShowsController : BaseJellyfinApiController
 30{
 31    private readonly IUserManager _userManager;
 32    private readonly ILibraryManager _libraryManager;
 33    private readonly IDtoService _dtoService;
 34    private readonly ITVSeriesManager _tvSeriesManager;
 35
 36    /// <summary>
 37    /// Initializes a new instance of the <see cref="TvShowsController"/> class.
 38    /// </summary>
 39    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 40    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 41    /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
 42    /// <param name="tvSeriesManager">Instance of the <see cref="ITVSeriesManager"/> interface.</param>
 043    public TvShowsController(
 044        IUserManager userManager,
 045        ILibraryManager libraryManager,
 046        IDtoService dtoService,
 047        ITVSeriesManager tvSeriesManager)
 48    {
 049        _userManager = userManager;
 050        _libraryManager = libraryManager;
 051        _dtoService = dtoService;
 052        _tvSeriesManager = tvSeriesManager;
 053    }
 54
 55    /// <summary>
 56    /// Gets a list of next up episodes.
 57    /// </summary>
 58    /// <param name="userId">The user id of the user to get the next up episodes for.</param>
 59    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 60    /// <param name="limit">Optional. The maximum number of records to return.</param>
 61    /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
 62    /// <param name="seriesId">Optional. Filter by series id.</param>
 63    /// <param name="parentId">Optional. Specify this to localize the search to a specific item or folder. Omit to use t
 64    /// <param name="enableImages">Optional. Include image information in output.</param>
 65    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
 66    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 67    /// <param name="enableUserData">Optional. Include user data.</param>
 68    /// <param name="nextUpDateCutoff">Optional. Starting date of shows to show in Next Up section.</param>
 69    /// <param name="enableTotalRecordCount">Whether to enable the total records count. Defaults to true.</param>
 70    /// <param name="disableFirstEpisode">Whether to disable sending the first episode in a series as next up.</param>
 71    /// <param name="enableResumable">Whether to include resumable episodes in next up results.</param>
 72    /// <param name="enableRewatching">Whether to include watched episodes in next up results.</param>
 73    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the next up episodes.</returns>
 74    [HttpGet("NextUp")]
 75    [ProducesResponseType(StatusCodes.Status200OK)]
 76    public ActionResult<QueryResult<BaseItemDto>> GetNextUp(
 77        [FromQuery] Guid? userId,
 78        [FromQuery] int? startIndex,
 79        [FromQuery] int? limit,
 80        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
 81        [FromQuery] Guid? seriesId,
 82        [FromQuery] Guid? parentId,
 83        [FromQuery] bool? enableImages,
 84        [FromQuery] int? imageTypeLimit,
 85        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
 86        [FromQuery] bool? enableUserData,
 87        [FromQuery] DateTime? nextUpDateCutoff,
 88        [FromQuery] bool enableTotalRecordCount = true,
 89        [FromQuery] bool disableFirstEpisode = false,
 90        [FromQuery] bool enableResumable = true,
 91        [FromQuery] bool enableRewatching = false)
 92    {
 093        var user = _userManager.GetUserById(RequestHelpers.GetUserId(User, userId));
 094        if (user is null)
 95        {
 096            return NotFound();
 97        }
 98
 099        var options = new DtoOptions { Fields = fields }
 0100            .AddClientFields(User)
 0101            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 102
 0103        var result = _tvSeriesManager.GetNextUp(
 0104            new NextUpQuery
 0105            {
 0106                Limit = limit,
 0107                ParentId = parentId,
 0108                SeriesId = seriesId,
 0109                StartIndex = startIndex,
 0110                User = user,
 0111                EnableTotalRecordCount = enableTotalRecordCount,
 0112                DisableFirstEpisode = disableFirstEpisode,
 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(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
 147        [FromQuery] Guid? parentId,
 148        [FromQuery] bool? enableImages,
 149        [FromQuery] int? imageTypeLimit,
 150        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] 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            .AddClientFields(User)
 0164            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 165
 0166        var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user)
 0167        {
 0168            IncludeItemTypes = new[] { BaseItemKind.Episode },
 0169            OrderBy = new[] { (ItemSortBy.PremiereDate, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending)
 0170            MinPremiereDate = minPremiereDate,
 0171            StartIndex = startIndex,
 0172            Limit = limit,
 0173            ParentId = parentIdGuid,
 0174            Recursive = true,
 0175            DtoOptions = options
 0176        });
 177
 0178        var returnItems = _dtoService.GetBaseItemDtos(itemsResult, options, user);
 179
 0180        return new QueryResult<BaseItemDto>(
 0181            startIndex,
 0182            itemsResult.Count,
 0183            returnItems);
 184    }
 185
 186    /// <summary>
 187    /// Gets episodes for a tv season.
 188    /// </summary>
 189    /// <param name="seriesId">The series id.</param>
 190    /// <param name="userId">The user id.</param>
 191    /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows mul
 192    /// <param name="season">Optional filter by season number.</param>
 193    /// <param name="seasonId">Optional. Filter by season id.</param>
 194    /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
 195    /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
 196    /// <param name="startItemId">Optional. Skip through the list until a given item is found.</param>
 197    /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped fr
 198    /// <param name="limit">Optional. The maximum number of records to return.</param>
 199    /// <param name="enableImages">Optional, include image information in output.</param>
 200    /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
 201    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 202    /// <param name="enableUserData">Optional. Include user data.</param>
 203    /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Ar
 204    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the episodes on success or a <see cref="NotFoundResult"/>
 205    [HttpGet("{seriesId}/Episodes")]
 206    [ProducesResponseType(StatusCodes.Status200OK)]
 207    [ProducesResponseType(StatusCodes.Status404NotFound)]
 208    public ActionResult<QueryResult<BaseItemDto>> GetEpisodes(
 209        [FromRoute, Required] Guid seriesId,
 210        [FromQuery] Guid? userId,
 211        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
 212        [FromQuery] int? season,
 213        [FromQuery] Guid? seasonId,
 214        [FromQuery] bool? isMissing,
 215        [FromQuery] Guid? adjacentTo,
 216        [FromQuery] Guid? startItemId,
 217        [FromQuery] int? startIndex,
 218        [FromQuery] int? limit,
 219        [FromQuery] bool? enableImages,
 220        [FromQuery] int? imageTypeLimit,
 221        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
 222        [FromQuery] bool? enableUserData,
 223        [FromQuery] ItemSortBy? sortBy)
 224    {
 0225        userId = RequestHelpers.GetUserId(User, userId);
 0226        var user = userId.IsNullOrEmpty()
 0227            ? null
 0228            : _userManager.GetUserById(userId.Value);
 229
 230        List<BaseItem> episodes;
 231
 0232        var dtoOptions = new DtoOptions { Fields = fields }
 0233            .AddClientFields(User)
 0234            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 0235        var shouldIncludeMissingEpisodes = (user is not null && user.DisplayMissingEpisodes) || User.GetIsApiKey();
 236
 0237        if (seasonId.HasValue) // Season id was supplied. Get episodes by season id.
 238        {
 0239            var item = _libraryManager.GetItemById<BaseItem>(seasonId.Value);
 0240            if (item is not Season seasonItem)
 241            {
 0242                return NotFound("No season exists with Id " + seasonId);
 243            }
 244
 0245            episodes = seasonItem.GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes);
 246        }
 0247        else if (season.HasValue) // Season number was supplied. Get episodes by season number
 248        {
 0249            var series = _libraryManager.GetItemById<Series>(seriesId);
 0250            if (series is null)
 251            {
 0252                return NotFound("Series not found");
 253            }
 254
 0255            var seasonItem = series
 0256                .GetSeasons(user, dtoOptions)
 0257                .FirstOrDefault(i => i.IndexNumber == season.Value);
 258
 0259            episodes = seasonItem is null ?
 0260                new List<BaseItem>()
 0261                : ((Season)seasonItem).GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes);
 262        }
 263        else // No season number or season id was supplied. Returning all episodes.
 264        {
 0265            if (_libraryManager.GetItemById<BaseItem>(seriesId) is not Series series)
 266            {
 0267                return NotFound("Series not found");
 268            }
 269
 0270            episodes = series.GetEpisodes(user, dtoOptions, shouldIncludeMissingEpisodes).ToList();
 271        }
 272
 273        // Filter after the fact in case the ui doesn't want them
 0274        if (isMissing.HasValue)
 275        {
 0276            var val = isMissing.Value;
 0277            episodes = episodes
 0278                .Where(i => ((Episode)i).IsMissingEpisode == val)
 0279                .ToList();
 280        }
 281
 0282        if (startItemId.HasValue)
 283        {
 0284            episodes = episodes
 0285                .SkipWhile(i => !startItemId.Value.Equals(i.Id))
 0286                .ToList();
 287        }
 288
 289        // This must be the last filter
 0290        if (!adjacentTo.IsNullOrEmpty())
 291        {
 0292            episodes = UserViewBuilder.FilterForAdjacency(episodes, adjacentTo.Value).ToList();
 293        }
 294
 0295        if (sortBy == ItemSortBy.Random)
 296        {
 0297            episodes.Shuffle();
 298        }
 299
 0300        var returnItems = episodes;
 301
 0302        if (startIndex.HasValue || limit.HasValue)
 303        {
 0304            returnItems = ApplyPaging(episodes, startIndex, limit).ToList();
 305        }
 306
 0307        var dtos = _dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
 308
 0309        return new QueryResult<BaseItemDto>(
 0310            startIndex,
 0311            episodes.Count,
 0312            dtos);
 313    }
 314
 315    /// <summary>
 316    /// Gets seasons for a tv series.
 317    /// </summary>
 318    /// <param name="seriesId">The series id.</param>
 319    /// <param name="userId">The user id.</param>
 320    /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows mul
 321    /// <param name="isSpecialSeason">Optional. Filter by special season.</param>
 322    /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param>
 323    /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
 324    /// <param name="enableImages">Optional. Include image information in output.</param>
 325    /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
 326    /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
 327    /// <param name="enableUserData">Optional. Include user data.</param>
 328    /// <returns>A <see cref="QueryResult{BaseItemDto}"/> on success or a <see cref="NotFoundResult"/> if the series was
 329    [HttpGet("{seriesId}/Seasons")]
 330    [ProducesResponseType(StatusCodes.Status200OK)]
 331    [ProducesResponseType(StatusCodes.Status404NotFound)]
 332    public ActionResult<QueryResult<BaseItemDto>> GetSeasons(
 333        [FromRoute, Required] Guid seriesId,
 334        [FromQuery] Guid? userId,
 335        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
 336        [FromQuery] bool? isSpecialSeason,
 337        [FromQuery] bool? isMissing,
 338        [FromQuery] Guid? adjacentTo,
 339        [FromQuery] bool? enableImages,
 340        [FromQuery] int? imageTypeLimit,
 341        [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
 342        [FromQuery] bool? enableUserData)
 343    {
 0344        userId = RequestHelpers.GetUserId(User, userId);
 0345        var user = userId.IsNullOrEmpty()
 0346            ? null
 0347            : _userManager.GetUserById(userId.Value);
 0348        var item = _libraryManager.GetItemById<Series>(seriesId, user);
 0349        if (item is null)
 350        {
 0351            return NotFound();
 352        }
 353
 0354        var seasons = item.GetItemList(new InternalItemsQuery(user)
 0355        {
 0356            IsMissing = isMissing,
 0357            IsSpecialSeason = isSpecialSeason,
 0358            AdjacentTo = adjacentTo
 0359        });
 360
 0361        var dtoOptions = new DtoOptions { Fields = fields }
 0362            .AddClientFields(User)
 0363            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
 364
 0365        var returnItems = _dtoService.GetBaseItemDtos(seasons, dtoOptions, user);
 366
 0367        return new QueryResult<BaseItemDto>(returnItems);
 368    }
 369
 370    /// <summary>
 371    /// Applies the paging.
 372    /// </summary>
 373    /// <param name="items">The items.</param>
 374    /// <param name="startIndex">The start index.</param>
 375    /// <param name="limit">The limit.</param>
 376    /// <returns>IEnumerable{BaseItem}.</returns>
 377    private IEnumerable<BaseItem> ApplyPaging(IEnumerable<BaseItem> items, int? startIndex, int? limit)
 378    {
 379        // Start at
 0380        if (startIndex.HasValue)
 381        {
 0382            items = items.Skip(startIndex.Value);
 383        }
 384
 385        // Return limit
 0386        if (limit.HasValue)
 387        {
 0388            items = items.Take(limit.Value);
 389        }
 390
 0391        return items;
 392    }
 393}

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>)