< 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: 116
Coverable lines: 116
Total lines: 541
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 38
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%
GetMetadataEditorInfo(...)0%600240%
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 || inheritedContentType == CollectionType.tvshows)
 184                {
 0185                    info.ContentTypeOptions = info.ContentTypeOptions
 0186                        .Where(i => string.IsNullOrWhiteSpace(i.Value)
 0187                                    || string.Equals(i.Value, "TvShows", StringComparison.OrdinalIgnoreCase))
 0188                        .ToArray();
 189                }
 190            }
 191        }
 192
 0193        return info;
 194    }
 195
 196    /// <summary>
 197    /// Updates an item's content type.
 198    /// </summary>
 199    /// <param name="itemId">The item id.</param>
 200    /// <param name="contentType">The content type of the item.</param>
 201    /// <response code="204">Item content type updated.</response>
 202    /// <response code="404">Item not found.</response>
 203    /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be
 204    [HttpPost("Items/{itemId}/ContentType")]
 205    [ProducesResponseType(StatusCodes.Status204NoContent)]
 206    [ProducesResponseType(StatusCodes.Status404NotFound)]
 207    public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string? contentType)
 208    {
 0209        var item = _libraryManager.GetItemById<BaseItem>(itemId, User.GetUserId());
 0210        if (item is null)
 211        {
 0212            return NotFound();
 213        }
 214
 0215        var path = item.ContainingFolderPath;
 216
 0217        var types = _serverConfigurationManager.Configuration.ContentTypes
 0218            .Where(i => !string.IsNullOrWhiteSpace(i.Name))
 0219            .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
 0220            .ToList();
 221
 0222        if (!string.IsNullOrWhiteSpace(contentType))
 223        {
 0224            types.Add(new NameValuePair
 0225            {
 0226                Name = path,
 0227                Value = contentType
 0228            });
 229        }
 230
 0231        _serverConfigurationManager.Configuration.ContentTypes = types.ToArray();
 0232        _serverConfigurationManager.SaveConfiguration();
 0233        return NoContent();
 234    }
 235
 236    private async Task UpdateItem(BaseItemDto request, BaseItem item)
 237    {
 238        item.Name = request.Name;
 239        item.ForcedSortName = request.ForcedSortName;
 240
 241        item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;
 242
 243        item.CriticRating = request.CriticRating;
 244
 245        item.CommunityRating = request.CommunityRating;
 246        item.IndexNumber = request.IndexNumber;
 247        item.ParentIndexNumber = request.ParentIndexNumber;
 248        item.Overview = request.Overview;
 249        item.Genres = request.Genres;
 250
 251        if (item is Episode episode)
 252        {
 253            episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber;
 254            episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
 255            episode.AirsBeforeSeasonNumber = request.AirsBeforeSeasonNumber;
 256        }
 257
 258        if (request.Height is not null && item is LiveTvChannel channel)
 259        {
 260            channel.Height = request.Height.Value;
 261        }
 262
 263        if (request.Taglines is not null)
 264        {
 265            item.Tagline = request.Taglines.FirstOrDefault();
 266        }
 267
 268        if (request.Studios is not null)
 269        {
 270            item.Studios = Array.ConvertAll(request.Studios, x => x.Name);
 271        }
 272
 273        if (request.DateCreated.HasValue)
 274        {
 275            item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
 276        }
 277
 278        item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : null;
 279        item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : null;
 280        item.ProductionYear = request.ProductionYear;
 281
 282        request.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
 283        item.OfficialRating = request.OfficialRating;
 284        item.CustomRating = request.CustomRating;
 285
 286        var currentTags = item.Tags;
 287        var newTags = request.Tags;
 288        var removedTags = currentTags.Except(newTags).ToList();
 289        var addedTags = newTags.Except(currentTags).ToList();
 290        item.Tags = newTags;
 291
 292        if (item is Series rseries)
 293        {
 294            foreach (var season in rseries.Children.OfType<Season>())
 295            {
 296                if (!season.LockedFields.Contains(MetadataField.OfficialRating))
 297                {
 298                    season.OfficialRating = request.OfficialRating;
 299                }
 300
 301                season.CustomRating = request.CustomRating;
 302
 303                if (!season.LockedFields.Contains(MetadataField.Tags))
 304                {
 305                    season.Tags = season.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnor
 306                }
 307
 308                season.OnMetadataChanged();
 309                await season.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 310
 311                foreach (var ep in season.Children.OfType<Episode>())
 312                {
 313                    if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 314                    {
 315                        ep.OfficialRating = request.OfficialRating;
 316                    }
 317
 318                    ep.CustomRating = request.CustomRating;
 319
 320                    if (!ep.LockedFields.Contains(MetadataField.Tags))
 321                    {
 322                        ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCas
 323                    }
 324
 325                    ep.OnMetadataChanged();
 326                    await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait
 327                }
 328            }
 329        }
 330        else if (item is Season season)
 331        {
 332            foreach (var ep in season.Children.OfType<Episode>())
 333            {
 334                if (!ep.LockedFields.Contains(MetadataField.OfficialRating))
 335                {
 336                    ep.OfficialRating = request.OfficialRating;
 337                }
 338
 339                ep.CustomRating = request.CustomRating;
 340
 341                if (!ep.LockedFields.Contains(MetadataField.Tags))
 342                {
 343                    ep.Tags = ep.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreCase).T
 344                }
 345
 346                ep.OnMetadataChanged();
 347                await ep.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(fal
 348            }
 349        }
 350        else if (item is MusicAlbum album)
 351        {
 352            foreach (BaseItem track in album.Children)
 353            {
 354                if (!track.LockedFields.Contains(MetadataField.OfficialRating))
 355                {
 356                    track.OfficialRating = request.OfficialRating;
 357                }
 358
 359                track.CustomRating = request.CustomRating;
 360
 361                if (!track.LockedFields.Contains(MetadataField.Tags))
 362                {
 363                    track.Tags = track.Tags.Concat(addedTags).Except(removedTags).Distinct(StringComparer.OrdinalIgnoreC
 364                }
 365
 366                track.OnMetadataChanged();
 367                await track.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(
 368            }
 369        }
 370
 371        if (request.ProductionLocations is not null)
 372        {
 373            item.ProductionLocations = request.ProductionLocations;
 374        }
 375
 376        item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
 377        item.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
 378
 379        if (item is IHasDisplayOrder hasDisplayOrder)
 380        {
 381            hasDisplayOrder.DisplayOrder = request.DisplayOrder;
 382        }
 383
 384        if (item is IHasAspectRatio hasAspectRatio)
 385        {
 386            hasAspectRatio.AspectRatio = request.AspectRatio;
 387        }
 388
 389        item.IsLocked = request.LockData ?? false;
 390
 391        if (request.LockedFields is not null)
 392        {
 393            item.LockedFields = request.LockedFields;
 394        }
 395
 396        // Only allow this for series. Runtimes for media comes from ffprobe.
 397        if (item is Series)
 398        {
 399            item.RunTimeTicks = request.RunTimeTicks;
 400        }
 401
 402        foreach (var pair in request.ProviderIds.ToList())
 403        {
 404            if (string.IsNullOrEmpty(pair.Value))
 405            {
 406                request.ProviderIds.Remove(pair.Key);
 407            }
 408        }
 409
 410        item.ProviderIds = request.ProviderIds;
 411
 412        if (item is Video video)
 413        {
 414            video.Video3DFormat = request.Video3DFormat;
 415        }
 416
 417        if (request.AlbumArtists is not null)
 418        {
 419            if (item is IHasAlbumArtist hasAlbumArtists)
 420            {
 421                hasAlbumArtists.AlbumArtists = Array.ConvertAll(request.AlbumArtists, i => i.Name);
 422            }
 423        }
 424
 425        if (request.ArtistItems is not null)
 426        {
 427            if (item is IHasArtist hasArtists)
 428            {
 429                hasArtists.Artists = Array.ConvertAll(request.ArtistItems, i => i.Name);
 430            }
 431        }
 432
 433        switch (item)
 434        {
 435            case Audio song:
 436                song.Album = request.Album;
 437                break;
 438            case MusicVideo musicVideo:
 439                musicVideo.Album = request.Album;
 440                break;
 441            case Series series:
 442                {
 443                    series.Status = GetSeriesStatus(request);
 444
 445                    if (request.AirDays is not null)
 446                    {
 447                        series.AirDays = request.AirDays;
 448                        series.AirTime = request.AirTime;
 449                    }
 450
 451                    break;
 452                }
 453        }
 454    }
 455
 456    private SeriesStatus? GetSeriesStatus(BaseItemDto item)
 457    {
 0458        if (string.IsNullOrEmpty(item.Status))
 459        {
 0460            return null;
 461        }
 462
 0463        return Enum.Parse<SeriesStatus>(item.Status, true);
 464    }
 465
 466    private DateTime NormalizeDateTime(DateTime val)
 467    {
 0468        return DateTime.SpecifyKind(val, DateTimeKind.Utc);
 469    }
 470
 471    private List<NameValuePair> GetContentTypeOptions(bool isForItem)
 472    {
 0473        var list = new List<NameValuePair>();
 474
 0475        if (isForItem)
 476        {
 0477            list.Add(new NameValuePair
 0478            {
 0479                Name = "Inherit",
 0480                Value = string.Empty
 0481            });
 482        }
 483
 0484        list.Add(new NameValuePair
 0485        {
 0486            Name = "Movies",
 0487            Value = "movies"
 0488        });
 0489        list.Add(new NameValuePair
 0490        {
 0491            Name = "Music",
 0492            Value = "music"
 0493        });
 0494        list.Add(new NameValuePair
 0495        {
 0496            Name = "Shows",
 0497            Value = "tvshows"
 0498        });
 499
 0500        if (!isForItem)
 501        {
 0502            list.Add(new NameValuePair
 0503            {
 0504                Name = "Books",
 0505                Value = "books"
 0506            });
 507        }
 508
 0509        list.Add(new NameValuePair
 0510        {
 0511            Name = "HomeVideos",
 0512            Value = "homevideos"
 0513        });
 0514        list.Add(new NameValuePair
 0515        {
 0516            Name = "MusicVideos",
 0517            Value = "musicvideos"
 0518        });
 0519        list.Add(new NameValuePair
 0520        {
 0521            Name = "Photos",
 0522            Value = "photos"
 0523        });
 524
 0525        if (!isForItem)
 526        {
 0527            list.Add(new NameValuePair
 0528            {
 0529                Name = "MixedContent",
 0530                Value = string.Empty
 0531            });
 532        }
 533
 0534        foreach (var val in list)
 535        {
 0536            val.Name = _localizationManager.GetLocalizedString(val.Name);
 537        }
 538
 0539        return list;
 540    }
 541}