< Summary - Jellyfin

Information
Class: MediaBrowser.Controller.Entities.Video
Assembly: MediaBrowser.Controller
File(s): /srv/git/jellyfin/MediaBrowser.Controller/Entities/Video.cs
Line coverage
48%
Covered lines: 146
Uncovered lines: 154
Coverable lines: 300
Total lines: 886
Line coverage: 48.6%
Branch coverage
49%
Covered branches: 84
Total branches: 170
Branch coverage: 49.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/2/2026 - 12:12:50 AM Line coverage: 11% (20/181) Branch coverage: 12.5% (11/88) Total lines: 5665/4/2026 - 12:15:16 AM Line coverage: 8.6% (20/232) Branch coverage: 9.8% (11/112) Total lines: 6685/8/2026 - 12:15:13 AM Line coverage: 9% (21/232) Branch coverage: 9.8% (11/112) Total lines: 6685/20/2026 - 12:15:44 AM Line coverage: 9% (21/232) Branch coverage: 8.9% (10/112) Total lines: 6685/27/2026 - 12:15:38 AM Line coverage: 9.7% (23/235) Branch coverage: 11.6% (14/120) Total lines: 6796/6/2026 - 12:15:50 AM Line coverage: 9.8% (23/234) Branch coverage: 11.6% (14/120) Total lines: 6807/6/2026 - 12:16:28 AM Line coverage: 25.7% (69/268) Branch coverage: 27.4% (39/142) Total lines: 7958/3/2026 - 12:16:46 AM Line coverage: 33.1% (97/293) Branch coverage: 34.7% (57/164) Total lines: 8698/6/2026 - 12:17:15 AM Line coverage: 48.6% (146/300) Branch coverage: 49.4% (84/170) Total lines: 886 5/2/2026 - 12:12:50 AM Line coverage: 11% (20/181) Branch coverage: 12.5% (11/88) Total lines: 5665/4/2026 - 12:15:16 AM Line coverage: 8.6% (20/232) Branch coverage: 9.8% (11/112) Total lines: 6685/8/2026 - 12:15:13 AM Line coverage: 9% (21/232) Branch coverage: 9.8% (11/112) Total lines: 6685/20/2026 - 12:15:44 AM Line coverage: 9% (21/232) Branch coverage: 8.9% (10/112) Total lines: 6685/27/2026 - 12:15:38 AM Line coverage: 9.7% (23/235) Branch coverage: 11.6% (14/120) Total lines: 6796/6/2026 - 12:15:50 AM Line coverage: 9.8% (23/234) Branch coverage: 11.6% (14/120) Total lines: 6807/6/2026 - 12:16:28 AM Line coverage: 25.7% (69/268) Branch coverage: 27.4% (39/142) Total lines: 7958/3/2026 - 12:16:46 AM Line coverage: 33.1% (97/293) Branch coverage: 34.7% (57/164) Total lines: 8698/6/2026 - 12:17:15 AM Line coverage: 48.6% (146/300) Branch coverage: 49.4% (84/170) Total lines: 886

Coverage delta

Coverage delta 16 -16

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
get_SupportsPlayedStatus()100%210%
get_SupportsPeople()100%210%
get_SupportsInheritedParentImages()100%210%
get_SupportsPositionTicksResume()0%7280%
get_SupportsThemeMedia()100%210%
get_SupportsAddingToPlaylist()100%210%
get_MediaSourceCount()100%11100%
get_IsStacked()100%11100%
get_HasLocalAlternateVersions()100%11100%
get_SourceType()50%2266.66%
get_IsCompleteMedia()0%620%
get_EnableDefaultVideoUserDataKeys()100%210%
get_ContainingFolderPath()75%8883.33%
get_FileNameWithoutExtension()50%8660%
get_Is3D()100%210%
get_MediaType()100%11100%
GetMediaSourceCount(...)37.5%23838.46%
GetInheritedOriginalLanguage()50%10866.66%
GetUserDataKeys()0%156120%
SetPrimaryVersionId(...)100%210%
MarkPlayed(...)100%210%
MarkUnplayed(...)100%210%
PropagatePlayedState(...)100%1818100%
GetAllVersions()100%11100%
GetAlternateVersion(...)100%11100%
CreatePresentationUniqueKey()0%620%
CanDownload()0%2040%
IsActiveRecording()100%11100%
CanDelete()0%620%
GetAdditionalPartIds()100%210%
GetUserDataKey(...)0%620%
GetAdditionalParts(...)100%210%
UpdateFromResolvedItem(...)0%7280%
RefreshedOwnedItems()85.71%171476.19%
RefreshMetadataForVersions()64.28%391450%
RefreshMetadataForOwnedVideo(...)100%11100%
RefreshMetadataForOwnedVideo()18.75%571645.71%
UpdateToRepositoryAsync()0%620%
GetDeletePaths()0%620%
GetDefaultVideoStream()0%620%
GetExtraOwnerIds()100%11100%
GetOwnedVersionIds()100%11100%
GetOwnerIdForExtra(...)87.5%8892.85%
MatchedVersionNameLength(...)78.57%1414100%
GetAllItemsForMediaSources()87.5%88100%

File(s)

/srv/git/jellyfin/MediaBrowser.Controller/Entities/Video.cs

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CS1591
 4
 5using System;
 6using System.Collections.Generic;
 7using System.Globalization;
 8using System.Linq;
 9using System.Text.Json.Serialization;
 10using System.Threading;
 11using System.Threading.Tasks;
 12using Jellyfin.Data.Enums;
 13using Jellyfin.Database.Implementations.Entities;
 14using Jellyfin.Extensions;
 15using MediaBrowser.Controller.Library;
 16using MediaBrowser.Controller.LiveTv;
 17using MediaBrowser.Controller.Persistence;
 18using MediaBrowser.Controller.Providers;
 19using MediaBrowser.Model.Dto;
 20using MediaBrowser.Model.Entities;
 21using MediaBrowser.Model.IO;
 22using MediaBrowser.Model.MediaInfo;
 23using Microsoft.Extensions.Logging;
 24
 25namespace MediaBrowser.Controller.Entities
 26{
 27    /// <summary>
 28    /// Class Video.
 29    /// </summary>
 30    public class Video : BaseItem,
 31        IHasAspectRatio,
 32        ISupportsPlaceHolders,
 33        IHasMediaSources
 34    {
 64235        public Video()
 36        {
 64237            AdditionalParts = [];
 64238            LocalAlternateVersions = [];
 64239            SubtitleFiles = [];
 64240            AudioFiles = [];
 64241            LinkedAlternateVersions = [];
 64242        }
 43
 44        [JsonIgnore]
 45        public Guid? PrimaryVersionId { get; set; }
 46
 47        public string[] AdditionalParts { get; set; }
 48
 49        public string[] LocalAlternateVersions { get; set; }
 50
 51        public LinkedChild[] LinkedAlternateVersions { get; set; }
 52
 53        [JsonIgnore]
 054        public override bool SupportsPlayedStatus => true;
 55
 56        [JsonIgnore]
 057        public override bool SupportsPeople => true;
 58
 59        [JsonIgnore]
 060        public override bool SupportsInheritedParentImages => true;
 61
 62        [JsonIgnore]
 63        public override bool SupportsPositionTicksResume
 64        {
 65            get
 66            {
 067                var extraType = ExtraType;
 068                if (extraType.HasValue)
 69                {
 070                    if (extraType.Value == Model.Entities.ExtraType.Sample)
 71                    {
 072                        return false;
 73                    }
 74
 075                    if (extraType.Value == Model.Entities.ExtraType.ThemeVideo)
 76                    {
 077                        return false;
 78                    }
 79
 080                    if (extraType.Value == Model.Entities.ExtraType.Trailer)
 81                    {
 082                        return false;
 83                    }
 84                }
 85
 086                return true;
 87            }
 88        }
 89
 90        [JsonIgnore]
 091        public override bool SupportsThemeMedia => true;
 92
 93        /// <summary>
 94        /// Gets or sets the timestamp.
 95        /// </summary>
 96        /// <value>The timestamp.</value>
 97        public TransportStreamTimestamp? Timestamp { get; set; }
 98
 99        /// <summary>
 100        /// Gets or sets the subtitle paths.
 101        /// </summary>
 102        /// <value>The subtitle paths.</value>
 103        public string[] SubtitleFiles { get; set; }
 104
 105        /// <summary>
 106        /// Gets or sets the audio paths.
 107        /// </summary>
 108        /// <value>The audio paths.</value>
 109        public string[] AudioFiles { get; set; }
 110
 111        /// <summary>
 112        /// Gets or sets a value indicating whether this instance has subtitles.
 113        /// </summary>
 114        /// <value><c>true</c> if this instance has subtitles; otherwise, <c>false</c>.</value>
 115        public bool HasSubtitles { get; set; }
 116
 117        public bool IsPlaceHolder { get; set; }
 118
 119        /// <summary>
 120        /// Gets or sets the default index of the video stream.
 121        /// </summary>
 122        /// <value>The default index of the video stream.</value>
 123        public int? DefaultVideoStreamIndex { get; set; }
 124
 125        /// <summary>
 126        /// Gets or sets the type of the video.
 127        /// </summary>
 128        /// <value>The type of the video.</value>
 129        public VideoType VideoType { get; set; }
 130
 131        /// <summary>
 132        /// Gets or sets the type of the iso.
 133        /// </summary>
 134        /// <value>The type of the iso.</value>
 135        public IsoType? IsoType { get; set; }
 136
 137        /// <summary>
 138        /// Gets or sets the video3 D format.
 139        /// </summary>
 140        /// <value>The video3 D format.</value>
 141        public Video3DFormat? Video3DFormat { get; set; }
 142
 143        /// <summary>
 144        /// Gets or sets the aspect ratio.
 145        /// </summary>
 146        /// <value>The aspect ratio.</value>
 147        public string AspectRatio { get; set; }
 148
 149        [JsonIgnore]
 0150        public override bool SupportsAddingToPlaylist => true;
 151
 152        [JsonIgnore]
 153        public int MediaSourceCount
 154        {
 155            get
 156            {
 1157                return GetMediaSourceCount();
 158            }
 159        }
 160
 161        [JsonIgnore]
 77162        public bool IsStacked => AdditionalParts.Length > 0;
 163
 164        [JsonIgnore]
 15165        public override bool HasLocalAlternateVersions => LibraryManager.GetLocalAlternateVersionIds(this).Any();
 166
 167        public static IRecordingsManager RecordingsManager { get; set; }
 168
 169        [JsonIgnore]
 170        public override SourceType SourceType
 171        {
 172            get
 173            {
 45174                if (IsActiveRecording())
 175                {
 0176                    return SourceType.LiveTV;
 177                }
 178
 45179                return base.SourceType;
 180            }
 181        }
 182
 183        [JsonIgnore]
 184        public bool IsCompleteMedia
 185        {
 186            get
 187            {
 0188                if (SourceType == SourceType.Channel)
 189                {
 0190                    return !Tags.Contains("livestream", StringComparison.OrdinalIgnoreCase);
 191                }
 192
 0193                return !IsActiveRecording();
 194            }
 195        }
 196
 197        [JsonIgnore]
 0198        protected virtual bool EnableDefaultVideoUserDataKeys => true;
 199
 200        [JsonIgnore]
 201        public override string ContainingFolderPath
 202        {
 203            get
 204            {
 68205                if (IsStacked)
 206                {
 0207                    return System.IO.Path.GetDirectoryName(Path);
 208                }
 209
 68210                if (!IsPlaceHolder)
 211                {
 68212                    if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
 213                    {
 1214                        return Path;
 215                    }
 216                }
 217
 67218                return base.ContainingFolderPath;
 219            }
 220        }
 221
 222        [JsonIgnore]
 223        public override string FileNameWithoutExtension
 224        {
 225            get
 226            {
 31227                if (IsFileProtocol)
 228                {
 31229                    if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd)
 230                    {
 0231                        return System.IO.Path.GetFileName(Path);
 232                    }
 233
 31234                    return System.IO.Path.GetFileNameWithoutExtension(Path);
 235                }
 236
 0237                return null;
 238            }
 239        }
 240
 241        /// <summary>
 242        /// Gets a value indicating whether [is3 D].
 243        /// </summary>
 244        /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
 245        [JsonIgnore]
 0246        public bool Is3D => Video3DFormat.HasValue;
 247
 248        /// <summary>
 249        /// Gets the type of the media.
 250        /// </summary>
 251        /// <value>The type of the media.</value>
 252        [JsonIgnore]
 52253        public override MediaType MediaType => MediaType.Video;
 254
 255        private int GetMediaSourceCount(HashSet<Guid> callstack = null)
 256        {
 1257            callstack ??= [];
 1258            if (PrimaryVersionId.HasValue)
 259            {
 0260                var item = LibraryManager.GetItemById(PrimaryVersionId.Value);
 0261                if (item is Video video)
 262                {
 0263                    if (callstack.Contains(video.Id))
 264                    {
 265                        // Count alternate versions using LibraryManager
 0266                        var linkedCount = LibraryManager.GetLinkedAlternateVersions(video).Count();
 0267                        var localCount = LibraryManager.GetLocalAlternateVersionIds(video).Count();
 0268                        return linkedCount + localCount + 1;
 269                    }
 270
 0271                    callstack.Add(video.Id);
 0272                    return video.GetMediaSourceCount(callstack);
 273                }
 274            }
 275
 276            // Count alternate versions using LibraryManager
 1277            var linkedVersionCount = LibraryManager.GetLinkedAlternateVersions(this).Count();
 1278            var localVersionCount = LibraryManager.GetLocalAlternateVersionIds(this).Count();
 1279            return linkedVersionCount + localVersionCount + 1;
 280        }
 281
 282        /// <inheritdoc />
 283        public override string GetInheritedOriginalLanguage()
 284        {
 31285            if (ExtraType.GetValueOrDefault() == Model.Entities.ExtraType.Trailer)
 286            {
 0287                return GetOwner()?.GetInheritedOriginalLanguage();
 288            }
 289
 31290            return OriginalLanguage ?? GetOwner()?.GetInheritedOriginalLanguage();
 291        }
 292
 293        public override List<string> GetUserDataKeys()
 294        {
 0295            var list = base.GetUserDataKeys();
 296
 0297            if (EnableDefaultVideoUserDataKeys)
 298            {
 0299                if (ExtraType.HasValue)
 300                {
 0301                    var key = this.GetProviderId(MetadataProvider.Tmdb);
 0302                    if (!string.IsNullOrEmpty(key))
 303                    {
 0304                        list.Insert(0, GetUserDataKey(key));
 305                    }
 306
 0307                    key = this.GetProviderId(MetadataProvider.Imdb);
 0308                    if (!string.IsNullOrEmpty(key))
 309                    {
 0310                        list.Insert(0, GetUserDataKey(key));
 311                    }
 312                }
 313                else
 314                {
 0315                    var key = this.GetProviderId(MetadataProvider.Imdb);
 0316                    if (!string.IsNullOrEmpty(key))
 317                    {
 0318                        list.Insert(0, key);
 319                    }
 320
 0321                    key = this.GetProviderId(MetadataProvider.Tmdb);
 0322                    if (!string.IsNullOrEmpty(key))
 323                    {
 0324                        list.Insert(0, key);
 325                    }
 326                }
 327            }
 328
 0329            return list;
 330        }
 331
 332        public void SetPrimaryVersionId(Guid? id)
 333        {
 0334            PrimaryVersionId = id;
 0335            PresentationUniqueKey = CreatePresentationUniqueKey();
 0336        }
 337
 338        /// <summary>
 339        /// Marks the played status of this video and propagates it to its alternate versions.
 340        /// </summary>
 341        /// <param name="user">The user.</param>
 342        /// <param name="datePlayed">The date played.</param>
 343        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 344        public override void MarkPlayed(User user, DateTime? datePlayed, bool resetPosition)
 345        {
 0346            base.MarkPlayed(user, datePlayed, resetPosition);
 0347            PropagatePlayedState(user, true, resetPosition);
 0348        }
 349
 350        /// <summary>
 351        /// Marks this video unplayed and propagates the change to its alternate versions.
 352        /// </summary>
 353        /// <param name="user">The user.</param>
 354        public override void MarkUnplayed(User user)
 355        {
 0356            base.MarkUnplayed(user);
 357
 358            // MarkUnplayed always clears the position on this video, so reset the versions too.
 0359            PropagatePlayedState(user, false, true);
 0360        }
 361
 362        /// <summary>
 363        /// Propagates the played status to every alternate version of this video.
 364        /// </summary>
 365        /// <param name="user">The user.</param>
 366        /// <param name="played">The played status to apply to the alternate versions.</param>
 367        /// <param name="resetPosition">When marking played, controls whether each version's resume point
 368        /// is also reset (<c>true</c>) or left untouched (<c>false</c>). Ignored when marking unplayed,
 369        /// which always fully resets every version.</param>
 370        public void PropagatePlayedState(User user, bool played, bool resetPosition = true)
 371        {
 4372            ArgumentNullException.ThrowIfNull(user);
 373
 4374            if (!PrimaryVersionId.HasValue && LinkedAlternateVersions.Length == 0 && !HasLocalAlternateVersions)
 375            {
 1376                return;
 377            }
 378
 24379            foreach (var (item, _) in GetAllItemsForMediaSources())
 380            {
 9381                if (item.Id.Equals(Id) || item is not Video)
 382                {
 383                    continue;
 384                }
 385
 6386                if (played)
 387                {
 4388                    var dto = new UpdateUserItemDataDto { Played = true };
 4389                    if (resetPosition)
 390                    {
 2391                        dto.PlaybackPositionTicks = 0;
 392                    }
 393
 394                    // SaveUserData only writes the fields set on the DTO, so play count and other state are preserved.
 4395                    UserDataManager.SaveUserData(user, item, dto, UserDataSaveReason.TogglePlayed);
 396                }
 397                else
 398                {
 2399                    var data = UserDataManager.GetUserData(user, item);
 2400                    if (data is null)
 401                    {
 402                        continue;
 403                    }
 404
 2405                    ResetPlayedState(data);
 2406                    UserDataManager.SaveUserData(user, item, data, UserDataSaveReason.TogglePlayed, CancellationToken.No
 407                }
 408            }
 3409        }
 410
 411        /// <summary>
 412        /// Gets this video together with all of its alternate versions (local and linked and, when this
 413        /// is itself an alternate, the primary and the primary's other versions), deduplicated.
 414        /// </summary>
 415        /// <returns>This video and every alternate version of it.</returns>
 416        public IReadOnlyList<Video> GetAllVersions()
 417        {
 10418            return GetAllItemsForMediaSources()
 10419                .Select(i => i.Item)
 10420                .OfType<Video>()
 10421                .ToList();
 422        }
 423
 424        /// <summary>
 425        /// Gets the alternate version of this video that matches the supplied item id.
 426        /// </summary>
 427        /// <param name="itemId">The version item id (the playback media source id).</param>
 428        /// <returns>The matching version, or <c>null</c> when the id is not a version of this video.</returns>
 429        public Video GetAlternateVersion(Guid itemId)
 430        {
 4431            return GetAllVersions().FirstOrDefault(i => i.Id.Equals(itemId));
 432        }
 433
 434        public override string CreatePresentationUniqueKey()
 435        {
 0436            if (PrimaryVersionId.HasValue)
 437            {
 0438                return PrimaryVersionId.Value.ToString("N", CultureInfo.InvariantCulture);
 439            }
 440
 0441            return base.CreatePresentationUniqueKey();
 442        }
 443
 444        public override bool CanDownload()
 445        {
 0446            if (VideoType == VideoType.Dvd || VideoType == VideoType.BluRay)
 447            {
 0448                return false;
 449            }
 450
 0451            return IsFileProtocol;
 452        }
 453
 454        protected override bool IsActiveRecording()
 455        {
 51456            return RecordingsManager.GetActiveRecordingInfo(Path) is not null;
 457        }
 458
 459        public override bool CanDelete()
 460        {
 0461            if (IsActiveRecording())
 462            {
 0463                return false;
 464            }
 465
 0466            return base.CanDelete();
 467        }
 468
 469        public IEnumerable<Guid> GetAdditionalPartIds()
 470        {
 0471            return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
 472        }
 473
 474        private string GetUserDataKey(string providerId)
 475        {
 0476            var key = providerId + "-" + ExtraType.ToString().ToLowerInvariant();
 477
 478            // Make sure different trailers have their own data.
 0479            if (RunTimeTicks.HasValue)
 480            {
 0481                key += "-" + RunTimeTicks.Value.ToString(CultureInfo.InvariantCulture);
 482            }
 483
 0484            return key;
 485        }
 486
 487        /// <summary>
 488        /// Gets the additional parts.
 489        /// </summary>
 490        /// <param name="user">The user to apply parental restrictions for, or <c>null</c> to skip restriction checks.</
 491        /// <returns>IEnumerable{Video}.</returns>
 492        public IOrderedEnumerable<Video> GetAdditionalParts(User user = null)
 493        {
 0494            return GetAdditionalPartIds()
 0495                .Select(i => LibraryManager.GetItemById<Video>(i))
 0496                .Where(i => i is not null && (user is null || i.IsVisible(user)))
 0497                .OrderBy(i => i.SortName);
 498        }
 499
 500        internal override ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
 501        {
 0502            var updateType = base.UpdateFromResolvedItem(newItem);
 503
 0504            if (newItem is Video newVideo)
 505            {
 0506                if (!AdditionalParts.SequenceEqual(newVideo.AdditionalParts, StringComparer.Ordinal))
 507                {
 0508                    AdditionalParts = newVideo.AdditionalParts;
 0509                    updateType |= ItemUpdateType.MetadataImport;
 510                }
 511
 0512                if (!LocalAlternateVersions.SequenceEqual(newVideo.LocalAlternateVersions, StringComparer.Ordinal))
 513                {
 0514                    LocalAlternateVersions = newVideo.LocalAlternateVersions;
 0515                    updateType |= ItemUpdateType.MetadataImport;
 516                }
 517
 0518                if (VideoType != newVideo.VideoType)
 519                {
 0520                    VideoType = newVideo.VideoType;
 0521                    updateType |= ItemUpdateType.MetadataImport;
 522                }
 523            }
 524
 0525            return updateType;
 526        }
 527
 528        protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystem
 529        {
 2530            var hasChanges = false;
 531
 532            // The extras of a version group are maintained by its primary.
 2533            if (!PrimaryVersionId.HasValue)
 534            {
 2535                hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwa
 536            }
 537
 538            // Clean up LocalAlternateVersions - remove paths that no longer exist
 2539            if (LocalAlternateVersions.Length > 0)
 540            {
 2541                var validPaths = LocalAlternateVersions.Where(FileSystem.FileExists).ToArray();
 2542                if (validPaths.Length != LocalAlternateVersions.Length)
 543                {
 0544                    LocalAlternateVersions = validPaths;
 0545                    hasChanges = true;
 546                }
 547            }
 548
 2549            if (IsStacked)
 550            {
 0551                var tasks = AdditionalParts
 0552                    .Select(i => RefreshMetadataForOwnedVideo(options, true, i, typeof(Video), cancellationToken));
 553
 0554                await Task.WhenAll(tasks).ConfigureAwait(false);
 555            }
 556
 557            // Must have a parent to have additional parts or alternate versions
 558            // In other words, it must be part of the Parent/Child tree
 559            // The additional parts won't have additional parts themselves
 2560            if (IsFileProtocol && SupportsOwnedItems)
 561            {
 562                // Check if LinkedChildren are in sync before processing
 2563                var existingVersionCount = LibraryManager.GetLocalAlternateVersionIds(this).Count();
 2564                var tasks = LocalAlternateVersions
 2565                    .Select(i => RefreshMetadataForVersions(options, false, i, cancellationToken));
 566
 2567                await Task.WhenAll(tasks).ConfigureAwait(false);
 568
 2569                if (existingVersionCount != LocalAlternateVersions.Length)
 570                {
 2571                    hasChanges = true;
 572                }
 573            }
 574
 2575            return hasChanges;
 2576        }
 577
 578        private async Task RefreshMetadataForVersions(
 579            MetadataRefreshOptions options,
 580            bool copyTitleMetadata,
 581            string path,
 582            CancellationToken cancellationToken)
 583        {
 584            // Ensure the alternate version exists with the correct type (e.g. Movie, not Video)
 585            // before refreshing. This must happen here rather than in RefreshMetadataForOwnedVideo
 586            // because that method is also used for stacked parts which should keep their resolved type.
 2587            var id = LibraryManager.GetNewItemId(path, GetType());
 2588            if (LibraryManager.GetItemById(id) is not Video && FileSystem.FileExists(path))
 589            {
 2590                var parentFolder = GetParent() as Folder;
 2591                var collectionType = LibraryManager.GetContentType(this);
 2592                var altVideo = LibraryManager.ResolveAlternateVersion(path, GetType(), parentFolder, collectionType);
 2593                if (altVideo is not null)
 594                {
 0595                    altVideo.OwnerId = Id;
 0596                    altVideo.SetPrimaryVersionId(Id);
 0597                    altVideo.IsInMixedFolder = IsInMixedFolder;
 0598                    LibraryManager.CreateItem(altVideo, GetParent());
 599                }
 600            }
 601
 602            // A version is resolved on its own, so it does not learn whether the folder it sits in
 603            // holds other items. It has to share that with the version it belongs to, before the
 604            // refresh below acts on it.
 2605            if (LibraryManager.GetItemById(id) is Video resolvedVersion && resolvedVersion.IsInMixedFolder != IsInMixedF
 606            {
 0607                resolvedVersion.IsInMixedFolder = IsInMixedFolder;
 0608                await resolvedVersion.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).Configur
 609            }
 610
 2611            await RefreshMetadataForOwnedVideo(options, copyTitleMetadata, path, cancellationToken).ConfigureAwait(false
 612
 613            // Create LinkedChild entry for this local alternate version
 614            // This ensures the relationship exists in the database even if the alternate version
 615            // was created after the primary video was first saved
 2616            if (LibraryManager.GetItemById(id) is Video video)
 617            {
 0618                LibraryManager.UpsertLinkedChild(Id, video.Id, LinkedChildType.LocalAlternateVersion);
 619
 620                // Ensure PrimaryVersionId is set for existing alternate versions that may not have it
 0621                if (!video.PrimaryVersionId.HasValue)
 622                {
 0623                    video.SetPrimaryVersionId(Id);
 0624                    await video.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(f
 625                }
 626            }
 2627        }
 628
 629        private new Task RefreshMetadataForOwnedVideo(
 630            MetadataRefreshOptions options,
 631            bool copyTitleMetadata,
 632            string path,
 633            CancellationToken cancellationToken)
 2634            => RefreshMetadataForOwnedVideo(options, copyTitleMetadata, path, GetType(), cancellationToken);
 635
 636        private async Task RefreshMetadataForOwnedVideo(
 637            MetadataRefreshOptions options,
 638            bool copyTitleMetadata,
 639            string path,
 640            Type itemType,
 641            CancellationToken cancellationToken)
 642        {
 2643            var newOptions = new MetadataRefreshOptions(options)
 2644            {
 2645                SearchResult = null
 2646            };
 647
 2648            var id = LibraryManager.GetNewItemId(path, itemType);
 649
 650            // Check if the file still exists
 2651            if (!FileSystem.FileExists(path))
 652            {
 653                // File was removed - clean up any orphaned database entry
 0654                if (LibraryManager.GetItemById(id) is Video orphanedVideo && orphanedVideo.OwnerId.Equals(Id))
 655                {
 0656                    Logger.LogInformation("Owned video file no longer exists, removing orphaned item: {Path}", path);
 0657                    LibraryManager.DeleteItem(orphanedVideo, new DeleteOptions { DeleteFileLocation = false });
 658                }
 659
 0660                return;
 661            }
 662
 2663            if (LibraryManager.GetItemById(id) is not Video video)
 664            {
 2665                var parentFolder = GetParent() as Folder;
 2666                var collectionType = LibraryManager.GetContentType(this);
 2667                video = LibraryManager.ResolvePath(
 2668                    FileSystem.GetFileSystemInfo(path),
 2669                    parentFolder,
 2670                    collectionType: collectionType) as Video;
 671
 2672                if (video is null)
 673                {
 2674                    return;
 675                }
 676
 677                // Ensure parts use the expected base type (e.g. Video, not Movie)
 0678                if (video.GetType() != itemType && Activator.CreateInstance(itemType) is Video correctVideo)
 679                {
 0680                    correctVideo.Path = video.Path;
 0681                    correctVideo.Name = video.Name;
 0682                    correctVideo.VideoType = video.VideoType;
 0683                    correctVideo.ProductionYear = video.ProductionYear;
 0684                    correctVideo.ExtraType = video.ExtraType;
 0685                    video = correctVideo;
 686                }
 687
 0688                video.Id = id;
 0689                video.OwnerId = Id;
 0690                video.IsInMixedFolder = IsInMixedFolder;
 0691                LibraryManager.CreateItem(video, parentFolder);
 0692                newOptions.ForceSave = true;
 693            }
 694
 0695            if (video.OwnerId.IsEmpty())
 696            {
 0697                video.OwnerId = Id;
 698            }
 699
 0700            await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(fa
 2701        }
 702
 703        /// <inheritdoc />
 704        public override async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationTo
 705        {
 0706            await base.UpdateToRepositoryAsync(updateReason, cancellationToken).ConfigureAwait(false);
 707
 0708            var localAlternates = LibraryManager.GetLocalAlternateVersionIds(this)
 0709                .Select(i => LibraryManager.GetItemById(i))
 0710                .Where(i => i is not null);
 711
 0712            foreach (var item in localAlternates)
 713            {
 0714                item.ImageInfos = ImageInfos;
 0715                item.Overview = Overview;
 0716                item.ProductionYear = ProductionYear;
 0717                item.PremiereDate = PremiereDate;
 0718                item.CommunityRating = CommunityRating;
 0719                item.OfficialRating = OfficialRating;
 0720                item.Genres = Genres;
 0721                item.ProviderIds = ProviderIds;
 722
 0723                await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(fa
 724            }
 0725        }
 726
 727        public override IEnumerable<FileSystemMetadata> GetDeletePaths()
 728        {
 0729            if (!IsInMixedFolder)
 730            {
 0731                return new[]
 0732                {
 0733                    new FileSystemMetadata
 0734                    {
 0735                        FullName = ContainingFolderPath,
 0736                        IsDirectory = true
 0737                    }
 0738                };
 739            }
 740
 0741            return base.GetDeletePaths();
 742        }
 743
 744        public virtual MediaStream GetDefaultVideoStream()
 745        {
 0746            if (!DefaultVideoStreamIndex.HasValue)
 747            {
 0748                return null;
 749            }
 750
 0751            return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
 0752            {
 0753                ItemId = Id,
 0754                Index = DefaultVideoStreamIndex.Value
 0755            }).FirstOrDefault();
 756        }
 757
 758        /// <summary>
 759        /// Gets the ids of the items whose owned extras belong to this item.
 760        /// Extras are linked to a single version but need tp be surfaced for all versions.
 761        /// </summary>
 762        /// <returns>An array containing the owner ids.</returns>
 763        protected override Guid[] GetExtraOwnerIds()
 764        {
 3765            return GetAllItemsForMediaSources()
 3766                .Select(i => i.Item.Id)
 3767                .Distinct()
 3768                .ToArray();
 769        }
 770
 771        /// <inheritdoc />
 772        protected override Guid[] GetOwnedVersionIds()
 773        {
 774            // Only the versions that live beside this one in the folder this scan covers. Linked
 775            // versions are items of their own and maintain their extras themselves.
 2776            return [Id, .. LibraryManager.GetLocalAlternateVersionIds(this)];
 777        }
 778
 779        /// <inheritdoc />
 780        protected override Guid GetOwnerIdForExtra(BaseItem extra)
 781        {
 5782            if (string.IsNullOrEmpty(extra.Path))
 783            {
 0784                return Id;
 785            }
 786
 5787            var extraDirectory = System.IO.Path.GetDirectoryName(extra.Path.AsSpan());
 5788            var extraFileName = System.IO.Path.GetFileNameWithoutExtension(extra.Path.AsSpan());
 789
 5790            var ownerId = Id;
 5791            var matchedLength = MatchedVersionNameLength(Path, extraDirectory, extraFileName);
 792
 30793            foreach (var versionId in LibraryManager.GetLocalAlternateVersionIds(this))
 794            {
 10795                var version = LibraryManager.GetItemById(versionId);
 10796                if (version is null)
 797                {
 798                    continue;
 799                }
 800
 801                // "Movie - [2160p]-trailer.mkv" belongs to "Movie - [2160p].mkv" rather than to the
 802                // primary version, whose name it also starts with when the primary is plain "Movie.mkv"
 10803                var length = MatchedVersionNameLength(version.Path, extraDirectory, extraFileName);
 10804                if (length > matchedLength)
 805                {
 2806                    matchedLength = length;
 2807                    ownerId = versionId;
 808                }
 809            }
 810
 5811            return ownerId;
 812        }
 813
 814        /// <summary>
 815        /// Gets how much of an extra's file name is the name of the given version file, or 0 when the
 816        /// extra is not named after it.
 817        /// </summary>
 818        /// <param name="versionPath">The path of the version.</param>
 819        /// <param name="extraDirectory">The directory the extra lives in.</param>
 820        /// <param name="extraFileName">The file name of the extra, without extension.</param>
 821        /// <returns>The length of the match.</returns>
 822        private static int MatchedVersionNameLength(string versionPath, ReadOnlySpan<char> extraDirectory, ReadOnlySpan<
 823        {
 15824            if (string.IsNullOrEmpty(versionPath)
 15825                || !System.IO.Path.GetDirectoryName(versionPath.AsSpan()).Equals(extraDirectory, StringComparison.Ordina
 826            {
 3827                return 0;
 828            }
 829
 12830            var versionFileName = System.IO.Path.GetFileNameWithoutExtension(versionPath.AsSpan());
 12831            if (versionFileName.IsEmpty || !extraFileName.StartsWith(versionFileName, StringComparison.OrdinalIgnoreCase
 832            {
 5833                return 0;
 834            }
 835
 836            // The version name has to end where the extra's own name begins, so that a version
 837            // named "Movie - 4K" does not claim the extras of "Movie - 4Kish"
 7838            var remainder = extraFileName[versionFileName.Length..];
 839
 7840            return !remainder.IsEmpty && (remainder[0] == ' ' || Array.IndexOf(VersionDelimiters, remainder[0]) >= 0)
 7841                ? versionFileName.Length
 7842                : 0;
 843        }
 844
 845        protected override IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
 846        {
 25847            var primary = PrimaryVersionId.HasValue
 25848                ? LibraryManager.GetItemById(PrimaryVersionId.Value) as Video
 25849                : null;
 850
 25851            var primaryLinked = primary is null
 25852                ? []
 25853                : LibraryManager.GetLinkedAlternateVersions(primary).ToList();
 854
 855            // Grouping marks user-merged (splittable) sources. The primary is only such a source when
 856            // this video is linked onto it; for local (file-based) alternates the primary is just
 857            // another default source.
 25858            var primaryType = primaryLinked.Any(i => i.Id.Equals(Id))
 25859                ? MediaSourceType.Grouping
 25860                : MediaSourceType.Default;
 861
 862            // This video and its linked alternates, when this is itself an alternate, the primary and the primary's lin
 25863            var grouped = new[] { ((BaseItem)this, MediaSourceType.Default) }
 25864                .Concat(LibraryManager.GetLinkedAlternateVersions(this).Select(i => ((BaseItem)i, MediaSourceType.Groupi
 25865                .Concat(primary is null
 25866                    ? []
 25867                    : primaryLinked.Select(i => ((BaseItem)i, MediaSourceType.Grouping)).Prepend(((BaseItem)primary, pri
 25868                .ToList();
 869
 870            // The local (file-based) alternate versions of every grouped item.
 25871            var localAlternates = grouped
 25872                .Select(i => i.Item1)
 25873                .OfType<Video>()
 25874                .SelectMany(LibraryManager.GetLocalAlternateVersionIds)
 25875                .Select(LibraryManager.GetItemById)
 25876                .Where(i => i is not null)
 25877                .Select(i => (i, MediaSourceType.Default));
 878
 879            // Deduplicate
 25880            return grouped
 25881                .Concat(localAlternates)
 25882                .DistinctBy(i => i.Item1.Id)
 25883                .ToList();
 884        }
 885    }
 886}

Methods/Properties

.ctor()
get_SupportsPlayedStatus()
get_SupportsPeople()
get_SupportsInheritedParentImages()
get_SupportsPositionTicksResume()
get_SupportsThemeMedia()
get_SupportsAddingToPlaylist()
get_MediaSourceCount()
get_IsStacked()
get_HasLocalAlternateVersions()
get_SourceType()
get_IsCompleteMedia()
get_EnableDefaultVideoUserDataKeys()
get_ContainingFolderPath()
get_FileNameWithoutExtension()
get_Is3D()
get_MediaType()
GetMediaSourceCount(System.Collections.Generic.HashSet`1<System.Guid>)
GetInheritedOriginalLanguage()
GetUserDataKeys()
SetPrimaryVersionId(System.Nullable`1<System.Guid>)
MarkPlayed(Jellyfin.Database.Implementations.Entities.User,System.Nullable`1<System.DateTime>,System.Boolean)
MarkUnplayed(Jellyfin.Database.Implementations.Entities.User)
PropagatePlayedState(Jellyfin.Database.Implementations.Entities.User,System.Boolean,System.Boolean)
GetAllVersions()
GetAlternateVersion(System.Guid)
CreatePresentationUniqueKey()
CanDownload()
IsActiveRecording()
CanDelete()
GetAdditionalPartIds()
GetUserDataKey(System.String)
GetAdditionalParts(Jellyfin.Database.Implementations.Entities.User)
UpdateFromResolvedItem(MediaBrowser.Controller.Entities.BaseItem)
RefreshedOwnedItems()
RefreshMetadataForVersions()
RefreshMetadataForOwnedVideo(MediaBrowser.Controller.Providers.MetadataRefreshOptions,System.Boolean,System.String,System.Threading.CancellationToken)
RefreshMetadataForOwnedVideo()
UpdateToRepositoryAsync()
GetDeletePaths()
GetDefaultVideoStream()
GetExtraOwnerIds()
GetOwnedVersionIds()
GetOwnerIdForExtra(MediaBrowser.Controller.Entities.BaseItem)
MatchedVersionNameLength(System.String,System.ReadOnlySpan`1<System.Char>,System.ReadOnlySpan`1<System.Char>)
GetAllItemsForMediaSources()