< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.ItemUpdateController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/ItemUpdateController.cs
Line coverage
21%
Covered lines: 58
Uncovered lines: 212
Coverable lines: 270
Total lines: 571
Line coverage: 21.4%
Branch coverage
23%
Covered branches: 35
Total branches: 152
Branch coverage: 23%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 4/15/2026 - 12:14:34 AM Line coverage: 0% (0/119) Branch coverage: 0% (0/40) Total lines: 5444/19/2026 - 12:14:27 AM Line coverage: 0% (0/260) Branch coverage: 0% (0/140) Total lines: 5445/8/2026 - 12:15:13 AM Line coverage: 0% (0/261) Branch coverage: 0% (0/142) Total lines: 5457/16/2026 - 12:13:45 AM Line coverage: 0% (0/263) Branch coverage: 0% (0/146) Total lines: 5507/18/2026 - 12:15:19 AM Line coverage: 0% (0/265) Branch coverage: 0% (0/146) Total lines: 5547/22/2026 - 12:16:22 AM Line coverage: 21.4% (58/270) Branch coverage: 23% (35/152) Total lines: 571 4/15/2026 - 12:14:34 AM Line coverage: 0% (0/119) Branch coverage: 0% (0/40) Total lines: 5444/19/2026 - 12:14:27 AM Line coverage: 0% (0/260) Branch coverage: 0% (0/140) Total lines: 5445/8/2026 - 12:15:13 AM Line coverage: 0% (0/261) Branch coverage: 0% (0/142) Total lines: 5457/16/2026 - 12:13:45 AM Line coverage: 0% (0/263) Branch coverage: 0% (0/146) Total lines: 5507/18/2026 - 12:15:19 AM Line coverage: 0% (0/265) Branch coverage: 0% (0/146) Total lines: 5547/22/2026 - 12:16:22 AM Line coverage: 21.4% (58/270) Branch coverage: 23% (35/152) Total lines: 571

Coverage delta

Coverage delta 23 -23

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
UpdateItem()0%342180%
GetMetadataEditorInfo(...)0%702260%
UpdateItemContentType(...)0%2040%
UpdateItem()37.23%19029441.07%
GetSeriesStatus(...)0%620%
NormalizeDateTime(...)100%210%
GetContentTypeOptions(...)0%7280%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel.DataAnnotations;
 4using System.Linq;
 5using System.Threading;
 6using System.Threading.Tasks;
 7using Jellyfin.Api.Constants;
 8using Jellyfin.Api.Extensions;
 9using Jellyfin.Api.Helpers;
 10using Jellyfin.Data.Enums;
 11using MediaBrowser.Common.Api;
 12using MediaBrowser.Controller.Configuration;
 13using MediaBrowser.Controller.Entities;
 14using MediaBrowser.Controller.Entities.Audio;
 15using MediaBrowser.Controller.Entities.TV;
 16using MediaBrowser.Controller.Library;
 17using MediaBrowser.Controller.LiveTv;
 18using MediaBrowser.Controller.Providers;
 19using MediaBrowser.Model.Dto;
 20using MediaBrowser.Model.Entities;
 21using MediaBrowser.Model.Globalization;
 22using MediaBrowser.Model.IO;
 23using Microsoft.AspNetCore.Authorization;
 24using Microsoft.AspNetCore.Http;
 25using Microsoft.AspNetCore.Mvc;
 26
 27namespace Jellyfin.Api.Controllers;
 28
 29/// <summary>
 30/// Item update controller.
 31/// </summary>
 32[Route("")]
 33[Authorize(Policy = Policies.RequiresElevation)]
 34public class ItemUpdateController : BaseJellyfinApiController
 35{
 36    private readonly ILibraryManager _libraryManager;
 37    private readonly IProviderManager _providerManager;
 38    private readonly ILocalizationManager _localizationManager;
 39    private readonly IFileSystem _fileSystem;
 40    private readonly IServerConfigurationManager _serverConfigurationManager;
 41
 42    /// <summary>
 43    /// Initializes a new instance of the <see cref="ItemUpdateController"/> class.
 44    /// </summary>
 45    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 46    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 47    /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
 48    /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
 49    /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</p
 250    public ItemUpdateController(
 251        IFileSystem fileSystem,
 252        ILibraryManager libraryManager,
 253        IProviderManager providerManager,
 254        ILocalizationManager localizationManager,
 255        IServerConfigurationManager serverConfigurationManager)
 56    {
 257        _libraryManager = libraryManager;
 258        _providerManager = providerManager;
 259        _localizationManager = localizationManager;
 260        _fileSystem = fileSystem;
 261        _serverConfigurationManager = serverConfigurationManager;
 262    }
 63
 64    /// <summary>
 65    /// Updates an item.
 66    /// </summary>
 67    /// <param name="itemId">The item id.</param>
 68    /// <param name="request">The new item properties.</param>
 69    /// <response code="204">Item updated.</response>
 70    /// <response code="404">Item not found.</response>
 71    /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be
 72    [HttpPost("Items/{itemId}")]
 73    [ProducesResponseType(StatusCodes.Status204NoContent)]
 74    [ProducesResponseType(StatusCodes.Status404NotFound)]
 75    public async Task<ActionResult> UpdateItem([FromRoute, Required] Guid itemId, [FromBody, Required] BaseItemDto reque
 76    {
 077        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 078        if (item is null)
 79        {
 080            return NotFound();
 81        }
 82
 083        var newLockData = request.LockData ?? false;
 084        var isLockedChanged = item.IsLocked != newLockData;
 85
 086        var series = item as Series;
 087        var displayOrderChanged = series is not null && !string.Equals(
 088            series.DisplayOrder ?? string.Empty,
 089            request.DisplayOrder ?? string.Empty,
 090            StringComparison.OrdinalIgnoreCase);
 91
 92        // Do this first so that metadata savers can pull the updates from the database.
 093        if (request.People is not null)
 94        {
 095            _libraryManager.UpdatePeople(
 096                item,
 097                request.People.Select(x => new PersonInfo
 098                {
 099                    Name = x.Name,
 0100                    Role = x.Role,
 0101                    Type = x.Type
 0102                }).ToList());
 103        }
 104
 0105        await UpdateItem(request, item).ConfigureAwait(false);
 106
 0107        item.OnMetadataChanged();
 108
 0109        await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
 110
 0111        if (isLockedChanged && item.IsFolder)
 112        {
 0113            var folder = (Folder)item;
 114
 0115            foreach (var child in folder.GetRecursiveChildren())
 116            {
 0117                child.IsLocked = newLockData;
 0118                await child.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(
 119            }
 120        }
 121
 0122        if (displayOrderChanged)
 123        {
 0124            _providerManager.QueueRefresh(
 0125                series!.Id,
 0126                new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 0127                {
 0128                    MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
 0129                    ImageRefreshMode = MetadataRefreshMode.FullRefresh,
 0130                    ReplaceAllMetadata = true
 0131                },
 0132                RefreshPriority.High);
 133        }
 134
 0135        return NoContent();
 0136    }
 137
 138    /// <summary>
 139    /// Gets metadata editor info for an item.
 140    /// </summary>
 141    /// <param name="itemId">The item id.</param>
 142    /// <response code="200">Item metadata editor returned.</response>
 143    /// <response code="404">Item not found.</response>
 144    /// <returns>An <see cref="OkResult"/> on success containing the metadata editor, or a <see cref="NotFoundResult"/> 
 145    [HttpGet("Items/{itemId}/MetadataEditor")]
 146    [ProducesResponseType(StatusCodes.Status200OK)]
 147    [ProducesResponseType(StatusCodes.Status404NotFound)]
 148    public ActionResult<MetadataEditorInfo> GetMetadataEditorInfo([FromRoute, Required] Guid itemId)
 149    {
 0150        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 0151        if (item is null)
 152        {
 0153            return NotFound();
 154        }
 155
 0156        var info = new MetadataEditorInfo
 0157        {
 0158            ParentalRatingOptions = _localizationManager.GetParentalRatings().ToList(),
 0159            ExternalIdInfos = _providerManager.GetExternalIdInfos(item).ToArray(),
 0160            Countries = _localizationManager.GetCountries().ToArray(),
 0161            Cultures = _localizationManager.GetCultures()
 0162                .DistinctBy(c => c.DisplayName, StringComparer.OrdinalIgnoreCase)
 0163                .OrderBy(c => c.DisplayName)
 0164                .ToArray()
 0165        };
 166
 0167        if (!item.IsVirtualItem
 0168            && item is not ICollectionFolder
 0169            && item is not UserView
 0170            && item is not AggregateFolder
 0171            && item is not LiveTvChannel
 0172            && item is not IItemByName
 0173            && item.SourceType == SourceType.Library)
 174        {
 0175            var inheritedContentType = _libraryManager.GetInheritedContentType(item);
 0176            var configuredContentType = _libraryManager.GetConfiguredContentType(item);
 177
 0178            if (inheritedContentType is null || configuredContentType is not null)
 179            {
 0180                info.ContentTypeOptions = GetContentTypeOptions(true).ToArray();
 0181                info.ContentType = configuredContentType;
 182
 0183                if (inheritedContentType is null
 0184                    || inheritedContentType == CollectionType.tvshows
 0185                    || inheritedContentType == CollectionType.movies)
 186                {
 0187                    info.ContentTypeOptions = info.ContentTypeOptions
 0188                        .Where(i => string.IsNullOrWhiteSpace(i.Value)
 0189                                    || string.Equals(i.Value, "TvShows", StringComparison.OrdinalIgnoreCase)
 0190                                    || string.Equals(i.Value, "Movies", StringComparison.OrdinalIgnoreCase))
 0191                        .ToArray();
 192                }
 193            }
 194        }
 195
 0196        return info;
 197    }
 198
 199    /// <summary>
 200    /// Updates an item's content type.
 201    /// </summary>
 202    /// <param name="itemId">The item id.</param>
 203    /// <param name="contentType">The content type of the item.</param>
 204    /// <response code="204">Item content type updated.</response>
 205    /// <response code="404">Item not found.</response>
 206    /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be
 207    [HttpPost("Items/{itemId}/ContentType")]
 208    [ProducesResponseType(StatusCodes.Status204NoContent)]
 209    [ProducesResponseType(StatusCodes.Status404NotFound)]
 210    public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string? contentType)
 211    {
 0212        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 0213        if (item is null)
 214        {
 0215            return NotFound();
 216        }
 217
 0218        var path = item.ContainingFolderPath;
 219
 0220        var types = _serverConfigurationManager.Configuration.ContentTypes
 0221            .Where(i => !string.IsNullOrWhiteSpace(i.Name))
 0222            .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
 0223            .ToList();
 224
 0225        if (!string.IsNullOrWhiteSpace(contentType))
 226        {
 0227            types.Add(new NameValuePair
 0228            {
 0229                Name = path,
 0230                Value = contentType
 0231            });
 232        }
 233
 0234        _serverConfigurationManager.Configuration.ContentTypes = types.ToArray();
 0235        _serverConfigurationManager.SaveConfiguration();
 0236        return NoContent();
 237    }
 238
 239    internal async Task UpdateItem(BaseItemDto request, BaseItem item)
 240    {
 2241        item.Name = request.Name;
 2242        item.ForcedSortName = request.ForcedSortName;
 243
 2244        item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;
 2245        item.OriginalLanguage = string.IsNullOrWhiteSpace(request.OriginalLanguage) ? null : request.OriginalLanguage;
 246
 2247        item.CriticRating = request.CriticRating;
 248
 2249        item.CommunityRating = request.CommunityRating;
 2250        item.IndexNumber = request.IndexNumber;
 2251        item.ParentIndexNumber = request.ParentIndexNumber;
 2252        item.Overview = request.Overview;
 253
 2254        if (request.Genres is not null)
 255        {
 0256            item.Genres = request.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 257        }
 258
 2259        if (item is Episode episode)
 260        {
 0261            episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber;
 0262            episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
 0263            episode.AirsBeforeSeasonNumber = request.AirsBeforeSeasonNumber;
 264        }
 265
 2266        if (request.Height is not null && item is LiveTvChannel channel)
 267        {
 0268            channel.Height = request.Height.Value;
 269        }
 270
 2271        if (request.Taglines is not null)
 272        {
 0273            item.Tagline = request.Taglines.FirstOrDefault();
 274        }
 275
 2276        if (request.Studios is not null)
 277        {
 0278            item.Studios = Array.ConvertAll(request.Studios, x => x.Name).Distinct(StringComparer.OrdinalIgnoreCase).ToA
 279        }
 280
 2281        if (request.DateCreated.HasValue)
 282        {
 0283            item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
 284        }
 285
 2286        if (request.SeriesName is not null && item is IHasSeries hasSeries)
 287        {
 0288            hasSeries.SeriesName = request.SeriesName;
 289        }
 290
 2291        item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : null;
 2292        item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : null;
 2293        item.ProductionYear = request.ProductionYear;
 294
 2295        request.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
 2296        item.OfficialRating = request.OfficialRating;
 2297        item.CustomRating = request.CustomRating;
 298
 2299        var currentTags = item.Tags;
 300        List<string> removedTags;
 301        List<string> addedTags;
 2302        if (request.Tags is not null)
 303        {
 2304            var newTags = request.Tags.Select(t => t.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 2305            removedTags = currentTags.Except(newTags).ToList();
 2306            addedTags = newTags.Except(currentTags).ToList();
 2307            item.Tags = newTags;
 308        }
 309        else
 310        {
 0311            removedTags = [];
 0312            addedTags = [];
 313        }
 314
 2315        if (item is Series rseries)
 316        {
 0317            foreach (var season in rseries.Children.OfType<Season>())
 318            {
 0319                season.SeriesName = rseries.Name;
 320
 0321                if (!season.LockedFields.Contains(MetadataField.OfficialRating))
 322                {
 0323                    season.OfficialRating = request.OfficialRating;
 324                }
 325
 0326                season.CustomRating = request.CustomRating;
 327
 0328                if (!season.LockedFields.Contains(MetadataField.Tags))
 329                {
 0330                    season.Tags = season.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnor
 331                }
 332
 0333                season.OnMetadataChanged();
 0334                await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 335
 0336                foreach (var ep in season.Children.OfType<Episode>())
 337                {
 0338                    ep.SeriesName = rseries.Name;
 339
 0340                    if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 341                    {
 0342                        ep.OfficialRating = request.OfficialRating;
 343                    }
 344
 0345                    ep.CustomRating = request.CustomRating;
 346
 0347                    if (!ep.LockedFields.Contains(MetadataField.Tags))
 348                    {
 0349                        ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCas
 350                    }
 351
 0352                    ep.OnMetadataChanged();
 0353                    await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 354                }
 0355            }
 356        }
 2357        else if (item is Season season)
 358        {
 0359            foreach (var ep in season.Children.OfType<Episode>())
 360            {
 0361                if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 362                {
 0363                    ep.OfficialRating = request.OfficialRating;
 364                }
 365
 0366                ep.CustomRating = request.CustomRating;
 367
 0368                if (!ep.LockedFields.Contains(MetadataField.Tags))
 369                {
 0370                    ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).T
 371                }
 372
 0373                ep.OnMetadataChanged();
 0374                await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(fal
 375            }
 376        }
 2377        else if (item is MusicAlbum album)
 378        {
 0379            foreach (BaseItem track in album.Children)
 380            {
 0381                if (!track.LockedFields.Contains(MetadataField.OfficialRating))
 382                {
 0383                    track.OfficialRating = request.OfficialRating;
 384                }
 385
 0386                track.CustomRating = request.CustomRating;
 387
 0388                if (!track.LockedFields.Contains(MetadataField.Tags))
 389                {
 0390                    track.Tags = track.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreC
 391                }
 392
 0393                track.OnMetadataChanged();
 0394                await track.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(
 395            }
 396        }
 397
 2398        if (request.ProductionLocations is not null)
 399        {
 0400            item.ProductionLocations = request.ProductionLocations.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 401        }
 402
 2403        item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
 2404        item.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
 405
 2406        if (item is IHasDisplayOrder hasDisplayOrder)
 407        {
 0408            hasDisplayOrder.DisplayOrder = request.DisplayOrder;
 409        }
 410
 2411        if (item is IHasAspectRatio hasAspectRatio)
 412        {
 2413            hasAspectRatio.AspectRatio = request.AspectRatio;
 414        }
 415
 2416        item.IsLocked = request.LockData ?? false;
 417
 2418        if (request.LockedFields is not null)
 419        {
 0420            item.LockedFields = request.LockedFields;
 421        }
 422
 423        // Only allow this for series. Runtimes for media comes from ffprobe.
 2424        if (item is Series)
 425        {
 0426            item.RunTimeTicks = request.RunTimeTicks;
 427        }
 428
 2429        if (request.ProviderIds is not null)
 430        {
 0431            foreach (var pair in request.ProviderIds.ToList())
 432            {
 0433                if (string.IsNullOrEmpty(pair.Value))
 434                {
 0435                    request.ProviderIds.Remove(pair.Key);
 436                }
 437            }
 438
 0439            item.ProviderIds = request.ProviderIds;
 440        }
 441
 2442        if (item is Video video)
 443        {
 2444            video.Video3DFormat = request.Video3DFormat;
 445        }
 446
 2447        if (request.AlbumArtists is not null)
 448        {
 0449            if (item is IHasAlbumArtist hasAlbumArtists)
 450            {
 0451                hasAlbumArtists.AlbumArtists = Array.ConvertAll(request.AlbumArtists, i => i.Name.Trim()).Distinct(Strin
 452            }
 453        }
 454
 2455        if (request.ArtistItems is not null)
 456        {
 0457            if (item is IHasArtist hasArtists)
 458            {
 0459                hasArtists.Artists = Array.ConvertAll(request.ArtistItems, i => i.Name.Trim()).Distinct(StringComparer.O
 460            }
 461        }
 462
 463        switch (item)
 464        {
 465            case Audio song:
 0466                song.Album = request.Album;
 0467                break;
 468            case MusicVideo musicVideo:
 0469                musicVideo.Album = request.Album;
 0470                break;
 471            case Series series:
 472                {
 0473                    series.Status = GetSeriesStatus(request);
 474
 0475                    if (request.AirDays is not null)
 476                    {
 0477                        series.AirDays = request.AirDays;
 0478                        series.AirTime = request.AirTime;
 479                    }
 480
 481                    break;
 482                }
 483        }
 2484    }
 485
 486    private SeriesStatus? GetSeriesStatus(BaseItemDto item)
 487    {
 0488        if (string.IsNullOrEmpty(item.Status))
 489        {
 0490            return null;
 491        }
 492
 0493        return Enum.Parse<SeriesStatus>(item.Status, true);
 494    }
 495
 496    private DateTime NormalizeDateTime(DateTime val)
 497    {
 0498        return DateTime.SpecifyKind(val, DateTimeKind.Utc);
 499    }
 500
 501    private List<NameValuePair> GetContentTypeOptions(bool isForItem)
 502    {
 0503        var list = new List<NameValuePair>();
 504
 0505        if (isForItem)
 506        {
 0507            list.Add(new NameValuePair
 0508            {
 0509                Name = "Inherit",
 0510                Value = string.Empty
 0511            });
 512        }
 513
 0514        list.Add(new NameValuePair
 0515        {
 0516            Name = "Movies",
 0517            Value = "movies"
 0518        });
 0519        list.Add(new NameValuePair
 0520        {
 0521            Name = "Music",
 0522            Value = "music"
 0523        });
 0524        list.Add(new NameValuePair
 0525        {
 0526            Name = "Shows",
 0527            Value = "tvshows"
 0528        });
 529
 0530        if (!isForItem)
 531        {
 0532            list.Add(new NameValuePair
 0533            {
 0534                Name = "Books",
 0535                Value = "books"
 0536            });
 537        }
 538
 0539        list.Add(new NameValuePair
 0540        {
 0541            Name = "HomeVideos",
 0542            Value = "homevideos"
 0543        });
 0544        list.Add(new NameValuePair
 0545        {
 0546            Name = "MusicVideos",
 0547            Value = "musicvideos"
 0548        });
 0549        list.Add(new NameValuePair
 0550        {
 0551            Name = "Photos",
 0552            Value = "photos"
 0553        });
 554
 0555        if (!isForItem)
 556        {
 0557            list.Add(new NameValuePair
 0558            {
 0559                Name = "MixedContent",
 0560                Value = string.Empty
 0561            });
 562        }
 563
 0564        foreach (var val in list)
 565        {
 0566            val.Name = _localizationManager.GetLocalizedString(val.Name);
 567        }
 568
 0569        return list;
 570    }
 571}