< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.ItemUpdateController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/ItemUpdateController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 119
Coverable lines: 119
Total lines: 544
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 40
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/15/2025 - 12:10:55 AM Line coverage: 0% (0/116) Branch coverage: 0% (0/38) Total lines: 54112/25/2025 - 12:11:57 AM Line coverage: 0% (0/119) Branch coverage: 0% (0/40) Total lines: 544 9/15/2025 - 12:10:55 AM Line coverage: 0% (0/116) Branch coverage: 0% (0/38) Total lines: 54112/25/2025 - 12:11:57 AM Line coverage: 0% (0/119) Branch coverage: 0% (0/40) Total lines: 544

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetMetadataEditorInfo(...)0%702260%
UpdateItemContentType(...)0%2040%
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
 050    public ItemUpdateController(
 051        IFileSystem fileSystem,
 052        ILibraryManager libraryManager,
 053        IProviderManager providerManager,
 054        ILocalizationManager localizationManager,
 055        IServerConfigurationManager serverConfigurationManager)
 56    {
 057        _libraryManager = libraryManager;
 058        _providerManager = providerManager;
 059        _localizationManager = localizationManager;
 060        _fileSystem = fileSystem;
 061        _serverConfigurationManager = serverConfigurationManager;
 062    }
 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    {
 77        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 78        if (item is null)
 79        {
 80            return NotFound();
 81        }
 82
 83        var newLockData = request.LockData ?? false;
 84        var isLockedChanged = item.IsLocked != newLockData;
 85
 86        var series = item as Series;
 87        var displayOrderChanged = series is not null && !string.Equals(
 88            series.DisplayOrder ?? string.Empty,
 89            request.DisplayOrder ?? string.Empty,
 90            StringComparison.OrdinalIgnoreCase);
 91
 92        // Do this first so that metadata savers can pull the updates from the database.
 93        if (request.People is not null)
 94        {
 95            _libraryManager.UpdatePeople(
 96                item,
 97                request.People.Select(x => new PersonInfo
 98                {
 99                    Name = x.Name,
 100                    Role = x.Role,
 101                    Type = x.Type
 102                }).ToList());
 103        }
 104
 105        await UpdateItem(request, item).ConfigureAwait(false);
 106
 107        item.OnMetadataChanged();
 108
 109        await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
 110
 111        if (isLockedChanged && item.IsFolder)
 112        {
 113            var folder = (Folder)item;
 114
 115            foreach (var child in folder.GetRecursiveChildren())
 116            {
 117                child.IsLocked = newLockData;
 118                await child.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(
 119            }
 120        }
 121
 122        if (displayOrderChanged)
 123        {
 124            _providerManager.QueueRefresh(
 125                series!.Id,
 126                new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 127                {
 128                    MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
 129                    ImageRefreshMode = MetadataRefreshMode.FullRefresh,
 130                    ReplaceAllMetadata = true
 131                },
 132                RefreshPriority.High);
 133        }
 134
 135        return NoContent();
 136    }
 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    private async Task UpdateItem(BaseItemDto request, BaseItem item)
 240    {
 241        item.Name = request.Name;
 242        item.ForcedSortName = request.ForcedSortName;
 243
 244        item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;
 245
 246        item.CriticRating = request.CriticRating;
 247
 248        item.CommunityRating = request.CommunityRating;
 249        item.IndexNumber = request.IndexNumber;
 250        item.ParentIndexNumber = request.ParentIndexNumber;
 251        item.Overview = request.Overview;
 252        item.Genres = request.Genres;
 253
 254        if (item is Episode episode)
 255        {
 256            episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber;
 257            episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
 258            episode.AirsBeforeSeasonNumber = request.AirsBeforeSeasonNumber;
 259        }
 260
 261        if (request.Height is not null && item is LiveTvChannel channel)
 262        {
 263            channel.Height = request.Height.Value;
 264        }
 265
 266        if (request.Taglines is not null)
 267        {
 268            item.Tagline = request.Taglines.FirstOrDefault();
 269        }
 270
 271        if (request.Studios is not null)
 272        {
 273            item.Studios = Array.ConvertAll(request.Studios, x => x.Name);
 274        }
 275
 276        if (request.DateCreated.HasValue)
 277        {
 278            item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
 279        }
 280
 281        item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : null;
 282        item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : null;
 283        item.ProductionYear = request.ProductionYear;
 284
 285        request.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
 286        item.OfficialRating = request.OfficialRating;
 287        item.CustomRating = request.CustomRating;
 288
 289        var currentTags = item.Tags;
 290        var newTags = request.Tags;
 291        var removedTags = currentTags.Except(newTags).ToList();
 292        var addedTags = newTags.Except(currentTags).ToList();
 293        item.Tags = newTags;
 294
 295        if (item is Series rseries)
 296        {
 297            foreach (var season in rseries.Children.OfType<Season>())
 298            {
 299                if (!season.LockedFields.Contains(MetadataField.OfficialRating))
 300                {
 301                    season.OfficialRating = request.OfficialRating;
 302                }
 303
 304                season.CustomRating = request.CustomRating;
 305
 306                if (!season.LockedFields.Contains(MetadataField.Tags))
 307                {
 308                    season.Tags = season.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnor
 309                }
 310
 311                season.OnMetadataChanged();
 312                await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 313
 314                foreach (var ep in season.Children.OfType<Episode>())
 315                {
 316                    if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 317                    {
 318                        ep.OfficialRating = request.OfficialRating;
 319                    }
 320
 321                    ep.CustomRating = request.CustomRating;
 322
 323                    if (!ep.LockedFields.Contains(MetadataField.Tags))
 324                    {
 325                        ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCas
 326                    }
 327
 328                    ep.OnMetadataChanged();
 329                    await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 330                }
 331            }
 332        }
 333        else if (item is Season season)
 334        {
 335            foreach (var ep in season.Children.OfType<Episode>())
 336            {
 337                if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 338                {
 339                    ep.OfficialRating = request.OfficialRating;
 340                }
 341
 342                ep.CustomRating = request.CustomRating;
 343
 344                if (!ep.LockedFields.Contains(MetadataField.Tags))
 345                {
 346                    ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).T
 347                }
 348
 349                ep.OnMetadataChanged();
 350                await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(fal
 351            }
 352        }
 353        else if (item is MusicAlbum album)
 354        {
 355            foreach (BaseItem track in album.Children)
 356            {
 357                if (!track.LockedFields.Contains(MetadataField.OfficialRating))
 358                {
 359                    track.OfficialRating = request.OfficialRating;
 360                }
 361
 362                track.CustomRating = request.CustomRating;
 363
 364                if (!track.LockedFields.Contains(MetadataField.Tags))
 365                {
 366                    track.Tags = track.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreC
 367                }
 368
 369                track.OnMetadataChanged();
 370                await track.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(
 371            }
 372        }
 373
 374        if (request.ProductionLocations is not null)
 375        {
 376            item.ProductionLocations = request.ProductionLocations;
 377        }
 378
 379        item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
 380        item.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
 381
 382        if (item is IHasDisplayOrder hasDisplayOrder)
 383        {
 384            hasDisplayOrder.DisplayOrder = request.DisplayOrder;
 385        }
 386
 387        if (item is IHasAspectRatio hasAspectRatio)
 388        {
 389            hasAspectRatio.AspectRatio = request.AspectRatio;
 390        }
 391
 392        item.IsLocked = request.LockData ?? false;
 393
 394        if (request.LockedFields is not null)
 395        {
 396            item.LockedFields = request.LockedFields;
 397        }
 398
 399        // Only allow this for series. Runtimes for media comes from ffprobe.
 400        if (item is Series)
 401        {
 402            item.RunTimeTicks = request.RunTimeTicks;
 403        }
 404
 405        foreach (var pair in request.ProviderIds.ToList())
 406        {
 407            if (string.IsNullOrEmpty(pair.Value))
 408            {
 409                request.ProviderIds.Remove(pair.Key);
 410            }
 411        }
 412
 413        item.ProviderIds = request.ProviderIds;
 414
 415        if (item is Video video)
 416        {
 417            video.Video3DFormat = request.Video3DFormat;
 418        }
 419
 420        if (request.AlbumArtists is not null)
 421        {
 422            if (item is IHasAlbumArtist hasAlbumArtists)
 423            {
 424                hasAlbumArtists.AlbumArtists = Array.ConvertAll(request.AlbumArtists, i => i.Name);
 425            }
 426        }
 427
 428        if (request.ArtistItems is not null)
 429        {
 430            if (item is IHasArtist hasArtists)
 431            {
 432                hasArtists.Artists = Array.ConvertAll(request.ArtistItems, i => i.Name);
 433            }
 434        }
 435
 436        switch (item)
 437        {
 438            case Audio song:
 439                song.Album = request.Album;
 440                break;
 441            case MusicVideo musicVideo:
 442                musicVideo.Album = request.Album;
 443                break;
 444            case Series series:
 445                {
 446                    series.Status = GetSeriesStatus(request);
 447
 448                    if (request.AirDays is not null)
 449                    {
 450                        series.AirDays = request.AirDays;
 451                        series.AirTime = request.AirTime;
 452                    }
 453
 454                    break;
 455                }
 456        }
 457    }
 458
 459    private SeriesStatus? GetSeriesStatus(BaseItemDto item)
 460    {
 0461        if (string.IsNullOrEmpty(item.Status))
 462        {
 0463            return null;
 464        }
 465
 0466        return Enum.Parse<SeriesStatus>(item.Status, true);
 467    }
 468
 469    private DateTime NormalizeDateTime(DateTime val)
 470    {
 0471        return DateTime.SpecifyKind(val, DateTimeKind.Utc);
 472    }
 473
 474    private List<NameValuePair> GetContentTypeOptions(bool isForItem)
 475    {
 0476        var list = new List<NameValuePair>();
 477
 0478        if (isForItem)
 479        {
 0480            list.Add(new NameValuePair
 0481            {
 0482                Name = "Inherit",
 0483                Value = string.Empty
 0484            });
 485        }
 486
 0487        list.Add(new NameValuePair
 0488        {
 0489            Name = "Movies",
 0490            Value = "movies"
 0491        });
 0492        list.Add(new NameValuePair
 0493        {
 0494            Name = "Music",
 0495            Value = "music"
 0496        });
 0497        list.Add(new NameValuePair
 0498        {
 0499            Name = "Shows",
 0500            Value = "tvshows"
 0501        });
 502
 0503        if (!isForItem)
 504        {
 0505            list.Add(new NameValuePair
 0506            {
 0507                Name = "Books",
 0508                Value = "books"
 0509            });
 510        }
 511
 0512        list.Add(new NameValuePair
 0513        {
 0514            Name = "HomeVideos",
 0515            Value = "homevideos"
 0516        });
 0517        list.Add(new NameValuePair
 0518        {
 0519            Name = "MusicVideos",
 0520            Value = "musicvideos"
 0521        });
 0522        list.Add(new NameValuePair
 0523        {
 0524            Name = "Photos",
 0525            Value = "photos"
 0526        });
 527
 0528        if (!isForItem)
 529        {
 0530            list.Add(new NameValuePair
 0531            {
 0532                Name = "MixedContent",
 0533                Value = string.Empty
 0534            });
 535        }
 536
 0537        foreach (var val in list)
 538        {
 0539            val.Name = _localizationManager.GetLocalizedString(val.Name);
 540        }
 541
 0542        return list;
 543    }
 544}