< Summary - Jellyfin

Information
Class: MediaBrowser.Controller.Entities.Folder
Assembly: MediaBrowser.Controller
File(s): /srv/git/jellyfin/MediaBrowser.Controller/Entities/Folder.cs
Line coverage
32%
Covered lines: 189
Uncovered lines: 384
Coverable lines: 573
Total lines: 1829
Line coverage: 32.9%
Branch coverage
28%
Covered branches: 107
Total branches: 372
Branch coverage: 28.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 7/25/2025 - 12:11:10 AM Line coverage: 33.1% (180/543) Branch coverage: 29.7% (107/360) Total lines: 17719/17/2025 - 12:11:23 AM Line coverage: 34.3% (194/565) Branch coverage: 29.9% (109/364) Total lines: 18019/21/2025 - 12:11:25 AM Line coverage: 34.3% (194/565) Branch coverage: 30% (110/366) Total lines: 18019/25/2025 - 12:11:18 AM Line coverage: 34.4% (195/566) Branch coverage: 29.7% (109/366) Total lines: 18029/26/2025 - 12:11:03 AM Line coverage: 34.2% (195/569) Branch coverage: 29.7% (109/366) Total lines: 180510/2/2025 - 12:11:36 AM Line coverage: 34.2% (195/569) Branch coverage: 29.7% (109/366) Total lines: 181010/3/2025 - 12:11:15 AM Line coverage: 34.2% (196/573) Branch coverage: 29.8% (111/372) Total lines: 181810/12/2025 - 12:11:07 AM Line coverage: 32.9% (189/573) Branch coverage: 28.7% (107/372) Total lines: 182410/28/2025 - 12:11:27 AM Line coverage: 32.9% (189/573) Branch coverage: 28.7% (107/372) Total lines: 1829 7/25/2025 - 12:11:10 AM Line coverage: 33.1% (180/543) Branch coverage: 29.7% (107/360) Total lines: 17719/17/2025 - 12:11:23 AM Line coverage: 34.3% (194/565) Branch coverage: 29.9% (109/364) Total lines: 18019/21/2025 - 12:11:25 AM Line coverage: 34.3% (194/565) Branch coverage: 30% (110/366) Total lines: 18019/25/2025 - 12:11:18 AM Line coverage: 34.4% (195/566) Branch coverage: 29.7% (109/366) Total lines: 18029/26/2025 - 12:11:03 AM Line coverage: 34.2% (195/569) Branch coverage: 29.7% (109/366) Total lines: 180510/2/2025 - 12:11:36 AM Line coverage: 34.2% (195/569) Branch coverage: 29.7% (109/366) Total lines: 181010/3/2025 - 12:11:15 AM Line coverage: 34.2% (196/573) Branch coverage: 29.8% (111/372) Total lines: 181810/12/2025 - 12:11:07 AM Line coverage: 32.9% (189/573) Branch coverage: 28.7% (107/372) Total lines: 182410/28/2025 - 12:11:27 AM Line coverage: 32.9% (189/573) Branch coverage: 28.7% (107/372) Total lines: 1829

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
get_SupportsThemeMedia()100%210%
get_IsPreSorted()100%210%
get_IsPhysicalRoot()100%11100%
get_SupportsInheritedParentImages()100%210%
get_SupportsPlayedStatus()100%210%
get_IsFolder()100%11100%
get_IsDisplayedAsFolder()100%210%
get_SupportsCumulativeRunTimeTicks()100%11100%
get_SupportsDateLastMediaAdded()100%11100%
get_FileNameWithoutExtension()50%2266.66%
get_Children()100%22100%
set_Children(...)100%11100%
get_RecursiveChildren()100%210%
get_SupportsShortcutChildren()100%11100%
get_FilterLinkedChildrenPerUser()100%11100%
get_SupportsOwnedItems()100%22100%
get_SupportsUserDataFromChildren()25%841635.71%
CanDelete()50%2266.66%
RequiresRefresh()50%4475%
AddChild(...)0%4260%
IsVisible(...)50%801222.22%
LoadChildren()100%11100%
GetRefreshProgress()100%210%
ValidateChildren(...)100%210%
ValidateChildren(...)100%11100%
GetActualChildrenDictionary()37.5%10866.66%
IsLibraryFolderAccessible(...)80%101083.33%
GetNonCachedChildren(...)100%11100%
GetCachedChildren()100%11100%
GetChildCount(...)0%2040%
GetRecursiveChildCount(...)100%210%
QueryRecursive(...)71.42%721433.33%
QueryWithPostFiltering2(...)62.5%9877.27%
RequiresPostFiltering2(...)50%6450%
RequiresPostFiltering(...)50%4203633.33%
SortItemsByRequest(...)100%210%
GetItems(...)0%4260%
GetItemList(...)16.66%13642.85%
GetItemsInternal(...)33.33%31611.53%
PostFilterAndSort(...)0%110100%
CollapseBoxSetItemsIfNeeded(...)0%620%
CollapseBoxSetItems(...)40.9%1332238.88%
AllowBoxSetCollapsing(...)0%4692680%
GetChildren(...)75%4487.5%
GetChildren(...)100%11100%
GetEligibleChildrenForRecursiveChildren(...)100%11100%
AddChildren(...)71.42%171475%
AddChildrenFromCollection(...)50%282073.07%
GetRecursiveChildren(...)100%210%
GetRecursiveChildren()100%210%
GetRecursiveChildren(...)100%210%
GetRecursiveChildren(...)100%210%
GetRecursiveChildren(...)100%210%
AddChildrenToList(...)0%342180%
GetLinkedChildren()25%5457.14%
ContainsLinkedChildByItemId(...)0%110100%
GetLinkedChildren(...)9.09%406227.4%
GetLinkedChildrenInfos()100%210%
RefreshLinkedChildren(...)66.66%6687.8%
MarkPlayed(...)0%110100%
MarkUnplayed(...)0%620%
IsPlayed(...)100%210%
IsUnplayed(...)100%210%
FillUserDataDtoValues(...)8.33%124128%
GetProgress(...)100%11100%

File(s)

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

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CA1002, CA1721, CA1819, CS1591
 4
 5using System;
 6using System.Collections.Generic;
 7using System.Collections.Immutable;
 8using System.IO;
 9using System.Linq;
 10using System.Security;
 11using System.Text.Json.Serialization;
 12using System.Threading;
 13using System.Threading.Tasks;
 14using J2N.Collections.Generic.Extensions;
 15using Jellyfin.Data;
 16using Jellyfin.Data.Enums;
 17using Jellyfin.Database.Implementations.Entities;
 18using Jellyfin.Database.Implementations.Enums;
 19using Jellyfin.Extensions;
 20using MediaBrowser.Controller.Channels;
 21using MediaBrowser.Controller.Collections;
 22using MediaBrowser.Controller.Configuration;
 23using MediaBrowser.Controller.Dto;
 24using MediaBrowser.Controller.Entities.Audio;
 25using MediaBrowser.Controller.Entities.Movies;
 26using MediaBrowser.Controller.Library;
 27using MediaBrowser.Controller.LibraryTaskScheduler;
 28using MediaBrowser.Controller.Providers;
 29using MediaBrowser.Model.Dto;
 30using MediaBrowser.Model.IO;
 31using MediaBrowser.Model.Querying;
 32using Microsoft.Extensions.Logging;
 33using Episode = MediaBrowser.Controller.Entities.TV.Episode;
 34using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
 35using Season = MediaBrowser.Controller.Entities.TV.Season;
 36using Series = MediaBrowser.Controller.Entities.TV.Series;
 37
 38namespace MediaBrowser.Controller.Entities
 39{
 40    /// <summary>
 41    /// Class Folder.
 42    /// </summary>
 43    public class Folder : BaseItem
 44    {
 45        private IEnumerable<BaseItem> _children;
 46
 35547        public Folder()
 48        {
 35549            LinkedChildren = Array.Empty<LinkedChild>();
 35550        }
 51
 52        public static IUserViewManager UserViewManager { get; set; }
 53
 54        public static ILimitedConcurrencyLibraryScheduler LimitedConcurrencyLibraryScheduler { get; set; }
 55
 56        /// <summary>
 57        /// Gets or sets a value indicating whether this instance is root.
 58        /// </summary>
 59        /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
 60        public bool IsRoot { get; set; }
 61
 62        public LinkedChild[] LinkedChildren { get; set; }
 63
 64        [JsonIgnore]
 65        public DateTime? DateLastMediaAdded { get; set; }
 66
 67        [JsonIgnore]
 068        public override bool SupportsThemeMedia => true;
 69
 70        [JsonIgnore]
 071        public virtual bool IsPreSorted => false;
 72
 73        [JsonIgnore]
 1074        public virtual bool IsPhysicalRoot => false;
 75
 76        [JsonIgnore]
 077        public override bool SupportsInheritedParentImages => true;
 78
 79        [JsonIgnore]
 080        public override bool SupportsPlayedStatus => true;
 81
 82        /// <summary>
 83        /// Gets a value indicating whether this instance is folder.
 84        /// </summary>
 85        /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
 86        [JsonIgnore]
 89987        public override bool IsFolder => true;
 88
 89        [JsonIgnore]
 090        public override bool IsDisplayedAsFolder => true;
 91
 92        [JsonIgnore]
 9093        public virtual bool SupportsCumulativeRunTimeTicks => false;
 94
 95        [JsonIgnore]
 3496        public virtual bool SupportsDateLastMediaAdded => false;
 97
 98        [JsonIgnore]
 99        public override string FileNameWithoutExtension
 100        {
 101            get
 102            {
 304103                if (IsFileProtocol)
 104                {
 304105                    return System.IO.Path.GetFileName(Path);
 106                }
 107
 0108                return null;
 109            }
 110        }
 111
 112        /// <summary>
 113        /// Gets or Sets the actual children.
 114        /// </summary>
 115        /// <value>The actual children.</value>
 116        [JsonIgnore]
 117        public virtual IEnumerable<BaseItem> Children
 118        {
 1119119            get => _children ??= LoadChildren();
 205120            set => _children = value;
 121        }
 122
 123        /// <summary>
 124        /// Gets thread-safe access to all recursive children of this folder - without regard to user.
 125        /// </summary>
 126        /// <value>The recursive children.</value>
 127        [JsonIgnore]
 0128        public IEnumerable<BaseItem> RecursiveChildren => GetRecursiveChildren();
 129
 130        [JsonIgnore]
 22131        protected virtual bool SupportsShortcutChildren => false;
 132
 10133        protected virtual bool FilterLinkedChildrenPerUser => false;
 134
 135        [JsonIgnore]
 90136        protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren;
 137
 138        [JsonIgnore]
 139        public virtual bool SupportsUserDataFromChildren
 140        {
 141            get
 142            {
 143                // These are just far too slow.
 9144                if (this is ICollectionFolder)
 145                {
 3146                    return false;
 147                }
 148
 6149                if (this is UserView)
 150                {
 0151                    return false;
 152                }
 153
 6154                if (this is UserRootFolder)
 155                {
 6156                    return false;
 157                }
 158
 0159                if (this is Channel)
 160                {
 0161                    return false;
 162                }
 163
 0164                if (SourceType != SourceType.Library)
 165                {
 0166                    return false;
 167                }
 168
 0169                if (this is IItemByName)
 170                {
 0171                    if (this is not IHasDualAccess hasDualAccess || hasDualAccess.IsAccessedByName)
 172                    {
 0173                        return false;
 174                    }
 175                }
 176
 0177                return true;
 178            }
 179        }
 180
 181        public static ICollectionManager CollectionManager { get; set; }
 182
 183        public override bool CanDelete()
 184        {
 6185            if (IsRoot)
 186            {
 6187                return false;
 188            }
 189
 0190            return base.CanDelete();
 191        }
 192
 193        public override bool RequiresRefresh()
 194        {
 56195            var baseResult = base.RequiresRefresh();
 196
 56197            if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
 198            {
 0199                baseResult = true;
 200            }
 201
 56202            return baseResult;
 203        }
 204
 205        /// <summary>
 206        /// Adds the child.
 207        /// </summary>
 208        /// <param name="item">The item.</param>
 209        /// <exception cref="InvalidOperationException">Unable to add  + item.Name.</exception>
 210        public void AddChild(BaseItem item)
 211        {
 0212            item.SetParent(this);
 213
 0214            if (item.Id.IsEmpty())
 215            {
 0216                item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
 217            }
 218
 0219            if (item.DateCreated == DateTime.MinValue)
 220            {
 0221                item.DateCreated = DateTime.UtcNow;
 222            }
 223
 0224            if (item.DateModified == DateTime.MinValue)
 225            {
 0226                item.DateModified = DateTime.UtcNow;
 227            }
 228
 0229            LibraryManager.CreateItem(item, this);
 0230        }
 231
 232        public override bool IsVisible(User user, bool skipAllowedTagsCheck = false)
 233        {
 13234            if (this is ICollectionFolder && this is not BasePluginFolder)
 235            {
 0236                var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders);
 0237                if (blockedMediaFolders.Length > 0)
 238                {
 0239                    if (blockedMediaFolders.Contains(Id))
 240                    {
 0241                        return false;
 242                    }
 243                }
 244                else
 245                {
 0246                    if (!user.HasPermission(PermissionKind.EnableAllFolders)
 0247                        && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(Id))
 248                    {
 0249                        return false;
 250                    }
 251                }
 252            }
 253
 13254            return base.IsVisible(user, skipAllowedTagsCheck);
 255        }
 256
 257        /// <summary>
 258        /// Loads our children.  Validation will occur externally.
 259        /// We want this synchronous.
 260        /// </summary>
 261        /// <returns>Returns children.</returns>
 262        protected virtual IReadOnlyList<BaseItem> LoadChildren()
 263        {
 264            // logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
 265            // just load our children from the repo - the library will be validated and maintained in other processes
 124266            return GetCachedChildren();
 267        }
 268
 269        public override double? GetRefreshProgress()
 270        {
 0271            return ProviderManager.GetRefreshProgress(Id);
 272        }
 273
 274        public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
 275        {
 0276            return ValidateChildren(progress, new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellation
 277        }
 278
 279        /// <summary>
 280        /// Validates that the children of the folder still exist.
 281        /// </summary>
 282        /// <param name="progress">The progress.</param>
 283        /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
 284        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
 285        /// <param name="allowRemoveRoot">remove item even this folder is root.</param>
 286        /// <param name="cancellationToken">The cancellation token.</param>
 287        /// <returns>Task.</returns>
 288        public Task ValidateChildren(IProgress<double> progress, MetadataRefreshOptions metadataRefreshOptions, bool rec
 289        {
 61290            Children = null; // invalidate cached children.
 61291            return ValidateChildrenInternal(progress, recursive, true, allowRemoveRoot, metadataRefreshOptions, metadata
 292        }
 293
 294        private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
 295        {
 59296            var dictionary = new Dictionary<Guid, BaseItem>();
 297
 59298            Children = null; // invalidate cached children.
 59299            var childrenList = Children.ToList();
 300
 208301            foreach (var child in childrenList)
 302            {
 45303                var id = child.Id;
 45304                if (dictionary.ContainsKey(id))
 305                {
 0306                    Logger.LogError(
 0307                        "Found folder containing items with duplicate id. Path: {Path}, Child Name: {ChildName}",
 0308                        Path ?? Name,
 0309                        child.Path ?? child.Name);
 310                }
 311                else
 312                {
 45313                    dictionary[id] = child;
 314                }
 315            }
 316
 59317            return dictionary;
 318        }
 319
 320        /// <summary>
 321        /// Validates the children internal.
 322        /// </summary>
 323        /// <param name="progress">The progress.</param>
 324        /// <param name="recursive">if set to <c>true</c> [recursive].</param>
 325        /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
 326        /// <param name="allowRemoveRoot">remove item even this folder is root.</param>
 327        /// <param name="refreshOptions">The refresh options.</param>
 328        /// <param name="directoryService">The directory service.</param>
 329        /// <param name="cancellationToken">The cancellation token.</param>
 330        /// <returns>Task.</returns>
 331        protected virtual async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshCh
 332        {
 333            if (recursive)
 334            {
 335                ProviderManager.OnRefreshStart(this);
 336            }
 337
 338            try
 339            {
 340                if (GetParents().Any(f => f.Id.Equals(Id)))
 341                {
 342                    throw new InvalidOperationException("Recursive datastructure detected abort processing this item.");
 343                }
 344
 345                await ValidateChildrenInternal2(progress, recursive, refreshChildMetadata, allowRemoveRoot, refreshOptio
 346            }
 347            finally
 348            {
 349                if (recursive)
 350                {
 351                    ProviderManager.OnRefreshComplete(this);
 352                }
 353            }
 354        }
 355
 356        private static bool IsLibraryFolderAccessible(IDirectoryService directoryService, BaseItem item, bool checkColle
 357        {
 107358            if (!checkCollection && (item is BoxSet || string.Equals(item.FileNameWithoutExtension, "collections", Strin
 359            {
 0360                return true;
 361            }
 362
 363            // For top parents i.e. Library folders, skip the validation if it's empty or inaccessible
 107364            if (item.IsTopParent && !directoryService.IsAccessible(item.ContainingFolderPath))
 365            {
 38366                Logger.LogWarning("Library folder {LibraryFolderPath} is inaccessible or empty, skipping", item.Containi
 38367                return false;
 368            }
 369
 69370            return true;
 371        }
 372
 373        private async Task ValidateChildrenInternal2(IProgress<double> progress, bool recursive, bool refreshChildMetada
 374        {
 375            if (!IsLibraryFolderAccessible(directoryService, this, allowRemoveRoot))
 376            {
 377                return;
 378            }
 379
 380            cancellationToken.ThrowIfCancellationRequested();
 381
 382            var validChildren = new List<BaseItem>();
 383            var validChildrenNeedGeneration = false;
 384
 385            if (IsFileProtocol)
 386            {
 387                IEnumerable<BaseItem> nonCachedChildren = [];
 388
 389                try
 390                {
 391                    nonCachedChildren = GetNonCachedChildren(directoryService);
 392                }
 393                catch (IOException ex)
 394                {
 395                    Logger.LogError(ex, "Error retrieving children from file system");
 396                }
 397                catch (SecurityException ex)
 398                {
 399                    Logger.LogError(ex, "Error retrieving children from file system");
 400                }
 401                catch (Exception ex)
 402                {
 403                    Logger.LogError(ex, "Error retrieving children");
 404                    return;
 405                }
 406
 407                progress.Report(ProgressHelpers.RetrievedChildren);
 408
 409                if (recursive)
 410                {
 411                    ProviderManager.OnRefreshProgress(this, ProgressHelpers.RetrievedChildren);
 412                }
 413
 414                // Build a dictionary of the current children we have now by Id so we can compare quickly and easily
 415                var currentChildren = GetActualChildrenDictionary();
 416
 417                // Create a list for our validated children
 418                var newItems = new List<BaseItem>();
 419
 420                cancellationToken.ThrowIfCancellationRequested();
 421
 422                foreach (var child in nonCachedChildren)
 423                {
 424                    if (!IsLibraryFolderAccessible(directoryService, child, allowRemoveRoot))
 425                    {
 426                        continue;
 427                    }
 428
 429                    if (currentChildren.TryGetValue(child.Id, out BaseItem currentChild))
 430                    {
 431                        validChildren.Add(currentChild);
 432
 433                        if (currentChild.UpdateFromResolvedItem(child) > ItemUpdateType.None)
 434                        {
 435                            await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken)
 436                        }
 437                        else
 438                        {
 439                            // metadata is up-to-date; make sure DB has correct images dimensions and hash
 440                            await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false);
 441                        }
 442
 443                        continue;
 444                    }
 445
 446                    // Brand new item - needs to be added
 447                    child.SetParent(this);
 448                    newItems.Add(child);
 449                    validChildren.Add(child);
 450                }
 451
 452                // That's all the new and changed ones - now see if any have been removed and need cleanup
 453                var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
 454                var shouldRemove = !IsRoot || allowRemoveRoot;
 455                // If it's an AggregateFolder, don't remove
 456                if (shouldRemove && itemsRemoved.Count > 0)
 457                {
 458                    foreach (var item in itemsRemoved)
 459                    {
 460                        if (!item.CanDelete())
 461                        {
 462                            Logger.LogDebug("Item marked as non-removable, skipping: {Path}", item.Path ?? item.Name);
 463                            continue;
 464                        }
 465
 466                        if (item.IsFileProtocol)
 467                        {
 468                            Logger.LogDebug("Removed item: {Path}", item.Path);
 469
 470                            item.SetParent(null);
 471                            LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, fals
 472                        }
 473                    }
 474                }
 475
 476                if (newItems.Count > 0)
 477                {
 478                    LibraryManager.CreateItems(newItems, this, cancellationToken);
 479                }
 480            }
 481            else
 482            {
 483                validChildrenNeedGeneration = true;
 484            }
 485
 486            progress.Report(ProgressHelpers.UpdatedChildItems);
 487
 488            if (recursive)
 489            {
 490                ProviderManager.OnRefreshProgress(this, ProgressHelpers.UpdatedChildItems);
 491            }
 492
 493            cancellationToken.ThrowIfCancellationRequested();
 494
 495            if (recursive)
 496            {
 497                var folder = this;
 498                var innerProgress = new Progress<double>(innerPercent =>
 499                {
 500                    var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.Scanned
 501
 502                    progress.Report(percent);
 503
 504                    ProviderManager.OnRefreshProgress(folder, percent);
 505                });
 506
 507                if (validChildrenNeedGeneration)
 508                {
 509                    validChildren = Children.ToList();
 510                    validChildrenNeedGeneration = false;
 511                }
 512
 513                await ValidateSubFolders(validChildren.OfType<Folder>().ToList(), directoryService, innerProgress, cance
 514            }
 515
 516            if (refreshChildMetadata)
 517            {
 518                progress.Report(ProgressHelpers.ScannedSubfolders);
 519
 520                if (recursive)
 521                {
 522                    ProviderManager.OnRefreshProgress(this, ProgressHelpers.ScannedSubfolders);
 523                }
 524
 525                var container = this as IMetadataContainer;
 526
 527                var folder = this;
 528                var innerProgress = new Progress<double>(innerPercent =>
 529                {
 530                    var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.Refresh
 531
 532                    progress.Report(percent);
 533
 534                    if (recursive)
 535                    {
 536                        ProviderManager.OnRefreshProgress(folder, percent);
 537                    }
 538                });
 539
 540                if (container is not null)
 541                {
 542                    await RefreshAllMetadataForContainer(container, refreshOptions, innerProgress, cancellationToken).Co
 543                }
 544                else
 545                {
 546                    if (validChildrenNeedGeneration)
 547                    {
 548                        Children = null; // invalidate cached children.
 549                        validChildren = Children.ToList();
 550                    }
 551
 552                    await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellation
 553                }
 554            }
 555        }
 556
 557        private async Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, boo
 558        {
 559            await RunTasks(
 560                (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFold
 561                children,
 562                progress,
 563                cancellationToken).ConfigureAwait(false);
 564        }
 565
 566        private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOp
 567        {
 568            if (container is Series series)
 569            {
 570                await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
 571            }
 572
 573            await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
 574        }
 575
 576        private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, I
 577        {
 578            if (child is IMetadataContainer container)
 579            {
 580                await RefreshAllMetadataForContainer(container, refreshOptions, progress, cancellationToken).ConfigureAw
 581            }
 582            else
 583            {
 584                if (refreshOptions.RefreshItem(child))
 585                {
 586                    await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
 587                }
 588
 589                if (recursive && child is Folder folder)
 590                {
 591                    folder.Children = null; // invalidate cached children.
 592                    await folder.RefreshMetadataRecursive(folder.Children.Except([this, child]).ToList(), refreshOptions
 593                }
 594            }
 595        }
 596
 597        /// <summary>
 598        /// Refreshes the children.
 599        /// </summary>
 600        /// <param name="children">The children.</param>
 601        /// <param name="directoryService">The directory service.</param>
 602        /// <param name="progress">The progress.</param>
 603        /// <param name="cancellationToken">The cancellation token.</param>
 604        /// <returns>Task.</returns>
 605        private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<doub
 606        {
 607            await RunTasks(
 608                (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, false, null, dire
 609                children,
 610                progress,
 611                cancellationToken).ConfigureAwait(false);
 612        }
 613
 614        /// <summary>
 615        /// Runs an action block on a list of children.
 616        /// </summary>
 617        /// <param name="task">The task to run for each child.</param>
 618        /// <param name="children">The list of children.</param>
 619        /// <param name="progress">The progress.</param>
 620        /// <param name="cancellationToken">The cancellation token.</param>
 621        /// <returns>Task.</returns>
 622        private async Task RunTasks<T>(Func<T, IProgress<double>, Task> task, IList<T> children, IProgress<double> progr
 623        {
 624            await LimitedConcurrencyLibraryScheduler
 625                .Enqueue(
 626                    children.ToArray(),
 627                    task,
 628                    progress,
 629                    cancellationToken)
 630                .ConfigureAwait(false);
 631        }
 632
 633        /// <summary>
 634        /// Get the children of this folder from the actual file system.
 635        /// </summary>
 636        /// <returns>IEnumerable{BaseItem}.</returns>
 637        /// <param name="directoryService">The directory service to use for operation.</param>
 638        /// <returns>Returns set of base items.</returns>
 639        protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
 640        {
 59641            var collectionType = LibraryManager.GetContentType(this);
 59642            var libraryOptions = LibraryManager.GetLibraryOptions(this);
 643
 59644            return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryO
 645        }
 646
 647        /// <summary>
 648        /// Get our children from the repo - stubbed for now.
 649        /// </summary>
 650        /// <returns>IEnumerable{BaseItem}.</returns>
 651        protected IReadOnlyList<BaseItem> GetCachedChildren()
 652        {
 124653            return ItemRepository.GetItemList(new InternalItemsQuery
 124654            {
 124655                Parent = this,
 124656                GroupByPresentationUniqueKey = false,
 124657                DtoOptions = new DtoOptions(true)
 124658            });
 659        }
 660
 661        public virtual int GetChildCount(User user)
 662        {
 0663            if (LinkedChildren.Length > 0)
 664            {
 0665                if (this is not ICollectionFolder)
 666                {
 0667                    return GetChildren(user, true).Count;
 668                }
 669            }
 670
 0671            var result = GetItems(new InternalItemsQuery(user)
 0672            {
 0673                Recursive = false,
 0674                Limit = 0,
 0675                Parent = this,
 0676                DtoOptions = new DtoOptions(false)
 0677                {
 0678                    EnableImages = false
 0679                }
 0680            });
 681
 0682            return result.TotalRecordCount;
 683        }
 684
 685        public virtual int GetRecursiveChildCount(User user)
 686        {
 0687            return GetItems(new InternalItemsQuery(user)
 0688            {
 0689                Recursive = true,
 0690                IsFolder = false,
 0691                IsVirtualItem = false,
 0692                EnableTotalRecordCount = true,
 0693                Limit = 0,
 0694                DtoOptions = new DtoOptions(false)
 0695                {
 0696                    EnableImages = false
 0697                }
 0698            }).TotalRecordCount;
 699        }
 700
 701        public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
 702        {
 12703            var user = query.User;
 704
 12705            if (!query.ForceDirect && RequiresPostFiltering(query))
 706            {
 707                IEnumerable<BaseItem> items;
 0708                Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManage
 709
 0710                var totalCount = 0;
 0711                if (query.User is null)
 712                {
 0713                    items = GetRecursiveChildren(filter);
 0714                    totalCount = items.Count();
 715                }
 716                else
 717                {
 718                    // Save pagination params before clearing them to prevent pagination from happening
 719                    // before sorting. PostFilterAndSort will apply pagination after sorting.
 0720                    var limit = query.Limit;
 0721                    var startIndex = query.StartIndex;
 0722                    query.Limit = null;
 0723                    query.StartIndex = null;
 724
 0725                    items = GetRecursiveChildren(user, query, out totalCount);
 726
 727                    // Restore pagination params so PostFilterAndSort can apply them after sorting
 0728                    query.Limit = limit;
 0729                    query.StartIndex = startIndex;
 730                }
 731
 0732                var result = PostFilterAndSort(items, query);
 0733                result.TotalRecordCount = totalCount;
 0734                return result;
 735            }
 736
 12737            if (this is not UserRootFolder
 12738                && this is not AggregateFolder
 12739                && query.ParentId.IsEmpty())
 740            {
 12741                query.Parent = this;
 742            }
 743
 12744            if (RequiresPostFiltering2(query))
 745            {
 0746                return QueryWithPostFiltering2(query);
 747            }
 748
 12749            return LibraryManager.GetItemsResult(query);
 750        }
 751
 752        protected QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
 753        {
 1754            var startIndex = query.StartIndex;
 1755            var limit = query.Limit;
 756
 1757            query.StartIndex = null;
 1758            query.Limit = null;
 759
 1760            IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
 1761            var user = query.User;
 762
 1763            if (user is not null)
 764            {
 765                // needed for boxsets
 1766                itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
 767            }
 768
 769            IEnumerable<BaseItem> returnItems;
 1770            int totalCount = 0;
 771
 1772            if (query.EnableTotalRecordCount)
 773            {
 0774                var itemArray = itemsList.ToArray();
 0775                totalCount = itemArray.Length;
 0776                returnItems = itemArray;
 777            }
 778            else
 779            {
 1780                returnItems = itemsList;
 781            }
 782
 1783            if (limit.HasValue)
 784            {
 0785                returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
 786            }
 1787            else if (startIndex.HasValue)
 788            {
 0789                returnItems = returnItems.Skip(startIndex.Value);
 790            }
 791
 1792            return new QueryResult<BaseItem>(
 1793                query.StartIndex,
 1794                totalCount,
 1795                returnItems.ToArray());
 796        }
 797
 798        private bool RequiresPostFiltering2(InternalItemsQuery query)
 799        {
 12800            if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
 801            {
 0802                Logger.LogDebug("Query requires post-filtering due to BoxSet query");
 0803                return true;
 804            }
 805
 12806            return false;
 807        }
 808
 809        private bool RequiresPostFiltering(InternalItemsQuery query)
 810        {
 12811            if (LinkedChildren.Length > 0)
 812            {
 0813                if (this is not ICollectionFolder)
 814                {
 0815                    Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
 0816                    return true;
 817                }
 818            }
 819
 820            // Filter by Video3DFormat
 12821            if (query.Is3D.HasValue)
 822            {
 0823                Logger.LogDebug("Query requires post-filtering due to Is3D");
 0824                return true;
 825            }
 826
 12827            if (query.HasOfficialRating.HasValue)
 828            {
 0829                Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
 0830                return true;
 831            }
 832
 12833            if (query.IsPlaceHolder.HasValue)
 834            {
 0835                Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
 0836                return true;
 837            }
 838
 12839            if (query.HasSpecialFeature.HasValue)
 840            {
 0841                Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
 0842                return true;
 843            }
 844
 12845            if (query.HasSubtitles.HasValue)
 846            {
 0847                Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
 0848                return true;
 849            }
 850
 12851            if (query.HasTrailer.HasValue)
 852            {
 0853                Logger.LogDebug("Query requires post-filtering due to HasTrailer");
 0854                return true;
 855            }
 856
 12857            if (query.HasThemeSong.HasValue)
 858            {
 0859                Logger.LogDebug("Query requires post-filtering due to HasThemeSong");
 0860                return true;
 861            }
 862
 12863            if (query.HasThemeVideo.HasValue)
 864            {
 0865                Logger.LogDebug("Query requires post-filtering due to HasThemeVideo");
 0866                return true;
 867            }
 868
 869            // Filter by VideoType
 12870            if (query.VideoTypes.Length > 0)
 871            {
 0872                Logger.LogDebug("Query requires post-filtering due to VideoTypes");
 0873                return true;
 874            }
 875
 12876            if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
 877            {
 0878                Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
 0879                return true;
 880            }
 881
 12882            if (!query.AdjacentTo.IsNullOrEmpty())
 883            {
 0884                Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
 0885                return true;
 886            }
 887
 12888            if (query.SeriesStatuses.Length > 0)
 889            {
 0890                Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
 0891                return true;
 892            }
 893
 12894            if (query.AiredDuringSeason.HasValue)
 895            {
 0896                Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
 0897                return true;
 898            }
 899
 12900            if (query.IsPlayed.HasValue)
 901            {
 0902                if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
 903                {
 0904                    Logger.LogDebug("Query requires post-filtering due to IsPlayed");
 0905                    return true;
 906                }
 907            }
 908
 12909            return false;
 910        }
 911
 912        private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
 913        {
 0914            return items.OrderBy(i => Array.IndexOf(query.ItemIds, i.Id)).ToArray();
 915        }
 916
 917        public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
 918        {
 0919            if (query.ItemIds.Length > 0)
 920            {
 0921                var result = LibraryManager.GetItemsResult(query);
 922
 0923                if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
 924                {
 0925                    result.Items = SortItemsByRequest(query, result.Items);
 926                }
 927
 0928                return result;
 929            }
 930
 0931            return GetItemsInternal(query);
 932        }
 933
 934        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 935        {
 13936            query.EnableTotalRecordCount = false;
 937
 13938            if (query.ItemIds.Length > 0)
 939            {
 0940                var result = LibraryManager.GetItemList(query);
 941
 0942                if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
 943                {
 0944                    return SortItemsByRequest(query, result);
 945                }
 946
 0947                return result;
 948            }
 949
 13950            return GetItemsInternal(query).Items;
 951        }
 952
 953        protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
 954        {
 12955            if (SourceType == SourceType.Channel)
 956            {
 957                try
 958                {
 0959                    query.Parent = this;
 0960                    query.ChannelIds = new[] { ChannelId };
 961
 962                    // Don't blow up here because it could cause parent screens with other content to fail
 0963                    return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None)
 964                }
 0965                catch
 966                {
 967                    // Already logged at lower levels
 0968                    return new QueryResult<BaseItem>();
 969                }
 970            }
 971
 12972            if (query.Recursive)
 973            {
 12974                return QueryRecursive(query);
 975            }
 976
 0977            var user = query.User;
 978
 0979            Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
 980
 981            IEnumerable<BaseItem> items;
 982
 0983            int totalItemCount = 0;
 0984            if (query.User is null)
 985            {
 0986                items = Children.Where(filter);
 0987                totalItemCount = items.Count();
 988            }
 989            else
 990            {
 991                // need to pass this param to the children.
 992                // Note: Don't pass Limit/StartIndex here as pagination should happen after sorting in PostFilterAndSort
 0993                var childQuery = new InternalItemsQuery
 0994                {
 0995                    DisplayAlbumFolders = query.DisplayAlbumFolders,
 0996                    NameStartsWith = query.NameStartsWith,
 0997                    NameStartsWithOrGreater = query.NameStartsWithOrGreater,
 0998                    NameLessThan = query.NameLessThan
 0999                };
 1000
 01001                items = GetChildren(user, true, out totalItemCount, childQuery).Where(filter);
 1002            }
 1003
 01004            var result = PostFilterAndSort(items, query);
 01005            result.TotalRecordCount = totalItemCount;
 01006            return result;
 01007        }
 1008
 1009        protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
 1010        {
 01011            var user = query.User;
 1012
 1013            // Check recursive - don't substitute in plain folder views
 01014            if (user is not null)
 1015            {
 01016                items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager);
 1017            }
 1018
 1019#pragma warning disable CA1309
 01020            if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
 1021            {
 01022                items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.Inva
 1023            }
 1024
 01025            if (!string.IsNullOrEmpty(query.NameStartsWith))
 1026            {
 01027                items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIg
 1028            }
 1029
 01030            if (!string.IsNullOrEmpty(query.NameLessThan))
 1031            {
 01032                items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultur
 1033            }
 1034#pragma warning restore CA1309
 1035
 1036            // This must be the last filter
 01037            if (!query.AdjacentTo.IsNullOrEmpty())
 1038            {
 01039                items = UserViewBuilder.FilterForAdjacency(items.ToList(), query.AdjacentTo.Value);
 1040            }
 1041
 01042            return UserViewBuilder.SortAndPage(items, null, query, LibraryManager);
 1043        }
 1044
 1045        private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
 1046            IEnumerable<BaseItem> items,
 1047            InternalItemsQuery query,
 1048            BaseItem queryParent,
 1049            User user,
 1050            IServerConfigurationManager configurationManager,
 1051            ICollectionManager collectionManager)
 1052        {
 01053            ArgumentNullException.ThrowIfNull(items);
 1054
 01055            if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
 1056            {
 01057                items = collectionManager.CollapseItemsWithinBoxSets(items, user);
 1058            }
 1059
 01060            return items;
 1061        }
 1062
 1063        private static bool CollapseBoxSetItems(
 1064            InternalItemsQuery query,
 1065            BaseItem queryParent,
 1066            User user,
 1067            IServerConfigurationManager configurationManager)
 1068        {
 1069            // Could end up stuck in a loop like this
 121070            if (queryParent is BoxSet)
 1071            {
 01072                return false;
 1073            }
 1074
 121075            if (queryParent is Season)
 1076            {
 01077                return false;
 1078            }
 1079
 121080            if (queryParent is MusicAlbum)
 1081            {
 01082                return false;
 1083            }
 1084
 121085            if (queryParent is MusicArtist)
 1086            {
 01087                return false;
 1088            }
 1089
 121090            var param = query.CollapseBoxSetItems;
 1091
 121092            if (!param.HasValue)
 1093            {
 01094                if (user is not null && query.IncludeItemTypes.Any(type =>
 01095                    (type == BaseItemKind.Movie && !configurationManager.Configuration.EnableGroupingMoviesIntoCollectio
 01096                    (type == BaseItemKind.Series && !configurationManager.Configuration.EnableGroupingShowsIntoCollectio
 1097                {
 01098                    return false;
 1099                }
 1100
 01101                if (query.IncludeItemTypes.Length == 0
 01102                    || query.IncludeItemTypes.Any(type => type == BaseItemKind.Movie || type == BaseItemKind.Series))
 1103                {
 01104                    param = true;
 1105                }
 1106            }
 1107
 121108            return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
 1109        }
 1110
 1111        private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
 1112        {
 01113            if (request.IsFavorite.HasValue)
 1114            {
 01115                return false;
 1116            }
 1117
 01118            if (request.IsFavoriteOrLiked.HasValue)
 1119            {
 01120                return false;
 1121            }
 1122
 01123            if (request.IsLiked.HasValue)
 1124            {
 01125                return false;
 1126            }
 1127
 01128            if (request.IsPlayed.HasValue)
 1129            {
 01130                return false;
 1131            }
 1132
 01133            if (request.IsResumable.HasValue)
 1134            {
 01135                return false;
 1136            }
 1137
 01138            if (request.IsFolder.HasValue)
 1139            {
 01140                return false;
 1141            }
 1142
 01143            if (request.Genres.Count > 0)
 1144            {
 01145                return false;
 1146            }
 1147
 01148            if (request.GenreIds.Count > 0)
 1149            {
 01150                return false;
 1151            }
 1152
 01153            if (request.HasImdbId.HasValue)
 1154            {
 01155                return false;
 1156            }
 1157
 01158            if (request.HasOfficialRating.HasValue)
 1159            {
 01160                return false;
 1161            }
 1162
 01163            if (request.HasOverview.HasValue)
 1164            {
 01165                return false;
 1166            }
 1167
 01168            if (request.HasParentalRating.HasValue)
 1169            {
 01170                return false;
 1171            }
 1172
 01173            if (request.HasSpecialFeature.HasValue)
 1174            {
 01175                return false;
 1176            }
 1177
 01178            if (request.HasSubtitles.HasValue)
 1179            {
 01180                return false;
 1181            }
 1182
 01183            if (request.HasThemeSong.HasValue)
 1184            {
 01185                return false;
 1186            }
 1187
 01188            if (request.HasThemeVideo.HasValue)
 1189            {
 01190                return false;
 1191            }
 1192
 01193            if (request.HasTmdbId.HasValue)
 1194            {
 01195                return false;
 1196            }
 1197
 01198            if (request.HasTrailer.HasValue)
 1199            {
 01200                return false;
 1201            }
 1202
 01203            if (request.ImageTypes.Length > 0)
 1204            {
 01205                return false;
 1206            }
 1207
 01208            if (request.Is3D.HasValue)
 1209            {
 01210                return false;
 1211            }
 1212
 01213            if (request.Is4K.HasValue)
 1214            {
 01215                return false;
 1216            }
 1217
 01218            if (request.IsHD.HasValue)
 1219            {
 01220                return false;
 1221            }
 1222
 01223            if (request.IsLocked.HasValue)
 1224            {
 01225                return false;
 1226            }
 1227
 01228            if (request.IsPlaceHolder.HasValue)
 1229            {
 01230                return false;
 1231            }
 1232
 01233            if (!string.IsNullOrWhiteSpace(request.Person))
 1234            {
 01235                return false;
 1236            }
 1237
 01238            if (request.PersonIds.Length > 0)
 1239            {
 01240                return false;
 1241            }
 1242
 01243            if (request.ItemIds.Length > 0)
 1244            {
 01245                return false;
 1246            }
 1247
 01248            if (request.StudioIds.Length > 0)
 1249            {
 01250                return false;
 1251            }
 1252
 01253            if (request.VideoTypes.Length > 0)
 1254            {
 01255                return false;
 1256            }
 1257
 01258            if (request.Years.Length > 0)
 1259            {
 01260                return false;
 1261            }
 1262
 01263            if (request.Tags.Length > 0)
 1264            {
 01265                return false;
 1266            }
 1267
 01268            if (request.OfficialRatings.Length > 0)
 1269            {
 01270                return false;
 1271            }
 1272
 01273            if (request.MinIndexNumber.HasValue)
 1274            {
 01275                return false;
 1276            }
 1277
 01278            if (request.OrderBy.Any(o =>
 01279                o.OrderBy == ItemSortBy.CommunityRating ||
 01280                o.OrderBy == ItemSortBy.CriticRating ||
 01281                o.OrderBy == ItemSortBy.Runtime))
 1282            {
 01283                return false;
 1284            }
 1285
 01286            return true;
 1287        }
 1288
 1289        public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, out int totalItemCount
 1290        {
 101291            ArgumentNullException.ThrowIfNull(user);
 101292            query ??= new InternalItemsQuery();
 101293            query.User = user;
 1294
 1295            // the true root should return our users root folder children
 101296            if (IsPhysicalRoot)
 1297            {
 01298                return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren, out totalItemCount);
 1299            }
 1300
 101301            var result = new Dictionary<Guid, BaseItem>();
 1302
 101303            totalItemCount = AddChildren(user, includeLinkedChildren, result, false, query);
 1304
 101305            return result.Values.ToArray();
 1306        }
 1307
 1308        public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery que
 1309        {
 101310            return GetChildren(user, includeLinkedChildren, out _, query);
 1311        }
 1312
 1313        protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
 1314        {
 101315            return Children;
 1316        }
 1317
 1318        /// <summary>
 1319        /// Adds the children to list.
 1320        /// </summary>
 1321        private int AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive
 1322        {
 1323            // Prevent infinite recursion of nested folders
 101324            visitedFolders ??= new HashSet<Folder>();
 101325            if (!visitedFolders.Add(this))
 1326            {
 01327                return 0;
 1328            }
 1329
 1330            // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in mus
 101331            IEnumerable<BaseItem> children = null;
 101332            if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
 1333            {
 01334                children = Children;
 01335                query = null;
 1336            }
 1337
 1338            // If there are not sub-folders, proceed as normal.
 101339            if (children is null)
 1340            {
 101341                children = GetEligibleChildrenForRecursiveChildren(user);
 1342            }
 1343
 101344            if (includeLinkedChildren)
 1345            {
 101346                children = children.Concat(GetLinkedChildren(user)).ToArray();
 1347            }
 1348
 101349            return AddChildrenFromCollection(children, user, includeLinkedChildren, result, recursive, query, visitedFol
 1350        }
 1351
 1352        private int AddChildrenFromCollection(IEnumerable<BaseItem> children, User user, bool includeLinkedChildren, Dic
 1353        {
 101354            query ??= new InternalItemsQuery();
 101355            var limit = query.Limit > 0 ? query.Limit : int.MaxValue;
 101356            query.Limit = 0;
 1357
 101358            var visibleChildren = children
 101359                .Where(e => e.IsVisible(user))
 101360                .ToArray();
 1361
 101362            var realChildren = visibleChildren
 101363                .Where(e => query is null || UserViewBuilder.FilterItem(e, query))
 101364                .ToArray();
 1365
 101366            if (this is BoxSet && (query.OrderBy is null || query.OrderBy.Count == 0))
 1367            {
 01368                realChildren = realChildren
 01369                    .OrderBy(e => e.ProductionYear ?? int.MaxValue)
 01370                    .ToArray();
 1371            }
 1372
 101373            var childCount = realChildren.Length;
 101374            if (result.Count < limit)
 1375            {
 101376                var remainingCount = (int)(limit - result.Count);
 401377                foreach (var child in realChildren
 101378                    .Skip(query.StartIndex ?? 0)
 101379                    .Take(remainingCount))
 1380                {
 101381                    result[child.Id] = child;
 1382                }
 1383            }
 1384
 101385            if (recursive)
 1386            {
 01387                foreach (var child in visibleChildren
 01388                    .Where(e => e.IsFolder)
 01389                    .OfType<Folder>())
 1390                {
 01391                    childCount += child.AddChildren(user, includeLinkedChildren, result, true, query, visitedFolders);
 1392                }
 1393            }
 1394
 101395            return childCount;
 1396        }
 1397
 1398        public virtual IReadOnlyList<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query, out int totalCo
 1399        {
 01400            ArgumentNullException.ThrowIfNull(user);
 1401
 01402            var result = new Dictionary<Guid, BaseItem>();
 1403
 01404            totalCount = AddChildren(user, true, result, true, query);
 1405
 01406            return result.Values.ToArray();
 1407        }
 1408
 1409        /// <summary>
 1410        /// Gets the recursive children.
 1411        /// </summary>
 1412        /// <returns>IList{BaseItem}.</returns>
 1413        public IReadOnlyList<BaseItem> GetRecursiveChildren()
 1414        {
 01415            return GetRecursiveChildren(true);
 1416        }
 1417
 1418        public IReadOnlyList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
 1419        {
 01420            return GetRecursiveChildren(i => true, includeLinkedChildren);
 1421        }
 1422
 1423        public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
 1424        {
 01425            return GetRecursiveChildren(filter, true);
 1426        }
 1427
 1428        public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
 1429        {
 01430            var result = new Dictionary<Guid, BaseItem>();
 1431
 01432            AddChildrenToList(result, includeLinkedChildren, true, filter);
 1433
 01434            return result.Values.ToArray();
 1435        }
 1436
 1437        /// <summary>
 1438        /// Adds the children to list.
 1439        /// </summary>
 1440        private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Fu
 1441        {
 01442            foreach (var child in Children)
 1443            {
 01444                if (filter is null || filter(child))
 1445                {
 01446                    result[child.Id] = child;
 1447                }
 1448
 01449                if (recursive && child.IsFolder)
 1450                {
 01451                    var folder = (Folder)child;
 1452
 1453                    // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loo
 01454                    folder.AddChildrenToList(result, false, true, filter);
 1455                }
 1456            }
 1457
 01458            if (includeLinkedChildren)
 1459            {
 01460                foreach (var child in GetLinkedChildren())
 1461                {
 01462                    if (filter is null || filter(child))
 1463                    {
 01464                        result[child.Id] = child;
 1465                    }
 1466                }
 1467            }
 01468        }
 1469
 1470        /// <summary>
 1471        /// Gets the linked children.
 1472        /// </summary>
 1473        /// <returns>IEnumerable{BaseItem}.</returns>
 1474        public List<BaseItem> GetLinkedChildren()
 1475        {
 101476            var linkedChildren = LinkedChildren;
 101477            var list = new List<BaseItem>(linkedChildren.Length);
 1478
 201479            foreach (var i in linkedChildren)
 1480            {
 01481                var child = GetLinkedChild(i);
 1482
 01483                if (child is not null)
 1484                {
 01485                    list.Add(child);
 1486                }
 1487            }
 1488
 101489            return list;
 1490        }
 1491
 1492        public bool ContainsLinkedChildByItemId(Guid itemId)
 1493        {
 01494            var linkedChildren = LinkedChildren;
 01495            foreach (var i in linkedChildren)
 1496            {
 01497                if (i.ItemId.HasValue)
 1498                {
 01499                    if (i.ItemId.Value.Equals(itemId))
 1500                    {
 01501                        return true;
 1502                    }
 1503
 1504                    continue;
 1505                }
 1506
 01507                var child = GetLinkedChild(i);
 1508
 01509                if (child is not null && child.Id.Equals(itemId))
 1510                {
 01511                    return true;
 1512                }
 1513            }
 1514
 01515            return false;
 1516        }
 1517
 1518        public List<BaseItem> GetLinkedChildren(User user)
 1519        {
 101520            if (!FilterLinkedChildrenPerUser || user is null)
 1521            {
 101522                return GetLinkedChildren();
 1523            }
 1524
 01525            var linkedChildren = LinkedChildren;
 01526            var list = new List<BaseItem>(linkedChildren.Length);
 1527
 01528            if (linkedChildren.Length == 0)
 1529            {
 01530                return list;
 1531            }
 1532
 01533            var allUserRootChildren = LibraryManager.GetUserRootFolder()
 01534                .GetChildren(user, true)
 01535                .OfType<Folder>()
 01536                .ToList();
 1537
 01538            var collectionFolderIds = allUserRootChildren
 01539                .Select(i => i.Id)
 01540                .ToList();
 1541
 01542            foreach (var i in linkedChildren)
 1543            {
 01544                var child = GetLinkedChild(i);
 1545
 01546                if (child is null)
 1547                {
 1548                    continue;
 1549                }
 1550
 01551                var childOwner = child.GetOwner() ?? child;
 1552
 01553                if (child is not IItemByName)
 1554                {
 01555                    var childProtocol = childOwner.PathProtocol;
 01556                    if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
 1557                    {
 01558                        if (!childOwner.IsVisibleStandalone(user))
 1559                        {
 01560                            continue;
 1561                        }
 1562                    }
 1563                    else
 1564                    {
 01565                        var itemCollectionFolderIds =
 01566                            LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
 1567
 01568                        if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
 1569                        {
 1570                            continue;
 1571                        }
 1572                    }
 1573                }
 1574
 01575                list.Add(child);
 1576            }
 1577
 01578            return list;
 1579        }
 1580
 1581        /// <summary>
 1582        /// Gets the linked children.
 1583        /// </summary>
 1584        /// <returns>IEnumerable{BaseItem}.</returns>
 1585        public IReadOnlyList<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
 1586        {
 01587            return LinkedChildren
 01588                .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
 01589                .Where(i => i.Item2 is not null)
 01590                .ToArray();
 1591        }
 1592
 1593        protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystem
 1594        {
 1595            var changesFound = false;
 1596
 1597            if (IsFileProtocol)
 1598            {
 1599                if (RefreshLinkedChildren(fileSystemChildren))
 1600                {
 1601                    changesFound = true;
 1602                }
 1603            }
 1604
 1605            var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).Configur
 1606
 1607            return baseHasChanges || changesFound;
 1608        }
 1609
 1610        /// <summary>
 1611        /// Refreshes the linked children.
 1612        /// </summary>
 1613        /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
 1614        /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
 1615        protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
 1616        {
 211617            if (SupportsShortcutChildren)
 1618            {
 211619                var newShortcutLinks = fileSystemChildren
 211620                    .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
 211621                    .Select(i =>
 211622                    {
 211623                        try
 211624                        {
 211625                            Logger.LogDebug("Found shortcut at {0}", i.FullName);
 211626
 211627                            var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShor
 211628
 211629                            if (!string.IsNullOrEmpty(resolvedPath))
 211630                            {
 211631                                return new LinkedChild
 211632                                {
 211633                                    Path = resolvedPath,
 211634                                    Type = LinkedChildType.Shortcut
 211635                                };
 211636                            }
 211637
 211638                            Logger.LogError("Error resolving shortcut {0}", i.FullName);
 211639
 211640                            return null;
 211641                        }
 211642                        catch (IOException ex)
 211643                        {
 211644                            Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
 211645                            return null;
 211646                        }
 211647                    })
 211648                    .Where(i => i is not null)
 211649                    .ToList();
 1650
 211651                var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
 1652
 211653                if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
 1654                {
 01655                    Logger.LogInformation("Shortcut links have changed for {0}", Path);
 1656
 01657                    newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
 01658                    LinkedChildren = newShortcutLinks.ToArray();
 01659                    return true;
 1660                }
 1661            }
 1662
 421663            foreach (var child in LinkedChildren)
 1664            {
 1665                // Reset the cached value
 01666                child.ItemId = null;
 1667            }
 1668
 211669            return false;
 1670        }
 1671
 1672        /// <summary>
 1673        /// Marks the played.
 1674        /// </summary>
 1675        /// <param name="user">The user.</param>
 1676        /// <param name="datePlayed">The date played.</param>
 1677        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 1678        public override void MarkPlayed(
 1679            User user,
 1680            DateTime? datePlayed,
 1681            bool resetPosition)
 1682        {
 01683            var query = new InternalItemsQuery
 01684            {
 01685                User = user,
 01686                Recursive = true,
 01687                IsFolder = false,
 01688                EnableTotalRecordCount = false
 01689            };
 1690
 01691            if (!user.DisplayMissingEpisodes)
 1692            {
 01693                query.IsVirtualItem = false;
 1694            }
 1695
 01696            var itemsResult = GetItemList(query);
 1697
 1698            // Sweep through recursively and update status
 01699            foreach (var item in itemsResult)
 1700            {
 01701                if (item.IsVirtualItem)
 1702                {
 1703                    // The querying doesn't support virtual unaired
 01704                    var episode = item as Episode;
 01705                    if (episode is not null && episode.IsUnaired)
 1706                    {
 1707                        continue;
 1708                    }
 1709                }
 1710
 01711                item.MarkPlayed(user, datePlayed, resetPosition);
 1712            }
 01713        }
 1714
 1715        /// <summary>
 1716        /// Marks the unplayed.
 1717        /// </summary>
 1718        /// <param name="user">The user.</param>
 1719        public override void MarkUnplayed(User user)
 1720        {
 01721            var itemsResult = GetItemList(new InternalItemsQuery
 01722            {
 01723                User = user,
 01724                Recursive = true,
 01725                IsFolder = false,
 01726                EnableTotalRecordCount = false
 01727            });
 1728
 1729            // Sweep through recursively and update status
 01730            foreach (var item in itemsResult)
 1731            {
 01732                item.MarkUnplayed(user);
 1733            }
 01734        }
 1735
 1736        public override bool IsPlayed(User user, UserItemData userItemData)
 1737        {
 01738            return ItemRepository.GetIsPlayed(user, Id, true);
 1739        }
 1740
 1741        public override bool IsUnplayed(User user, UserItemData userItemData)
 1742        {
 01743            return !IsPlayed(user, userItemData);
 1744        }
 1745
 1746        public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User
 1747        {
 91748            if (!SupportsUserDataFromChildren)
 1749            {
 91750                return;
 1751            }
 1752
 01753            if (itemDto is not null && fields.ContainsField(ItemFields.RecursiveItemCount))
 1754            {
 01755                itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
 1756            }
 1757
 01758            if (SupportsPlayedStatus)
 1759            {
 01760                var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
 01761                {
 01762                    Recursive = true,
 01763                    IsFolder = false,
 01764                    IsVirtualItem = false,
 01765                    EnableTotalRecordCount = true,
 01766                    Limit = 0,
 01767                    IsPlayed = false,
 01768                    DtoOptions = new DtoOptions(false)
 01769                    {
 01770                        EnableImages = false
 01771                    }
 01772                }).TotalRecordCount;
 1773
 01774                dto.UnplayedItemCount = unplayedQueryResult;
 1775
 01776                if (itemDto?.RecursiveItemCount > 0)
 1777                {
 01778                    var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
 01779                    dto.PlayedPercentage = 100 - unplayedPercentage;
 01780                    dto.Played = dto.PlayedPercentage.Value >= 100;
 1781                }
 1782                else
 1783                {
 01784                    dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
 1785                }
 1786            }
 01787        }
 1788
 1789        /// <summary>
 1790        /// Contains constants used when reporting scan progress.
 1791        /// </summary>
 1792        private static class ProgressHelpers
 1793        {
 1794            /// <summary>
 1795            /// Reported after the folders immediate children are retrieved.
 1796            /// </summary>
 1797            public const int RetrievedChildren = 5;
 1798
 1799            /// <summary>
 1800            /// Reported after add, updating, or deleting child items from the LibraryManager.
 1801            /// </summary>
 1802            public const int UpdatedChildItems = 10;
 1803
 1804            /// <summary>
 1805            /// Reported once subfolders are scanned.
 1806            /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
 1807            /// </summary>
 1808            public const int ScannedSubfolders = 50;
 1809
 1810            /// <summary>
 1811            /// Reported once metadata is refreshed.
 1812            /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
 1813            /// </summary>
 1814            public const int RefreshedMetadata = 100;
 1815
 1816            /// <summary>
 1817            /// Gets the current progress given the previous step, next step, and progress in between.
 1818            /// </summary>
 1819            /// <param name="previousProgressStep">The previous progress step.</param>
 1820            /// <param name="nextProgressStep">The next progress step.</param>
 1821            /// <param name="currentProgress">The current progress step.</param>
 1822            /// <returns>The progress.</returns>
 1823            public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
 1824            {
 781825                return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
 1826            }
 1827        }
 1828    }
 1829}

Methods/Properties

.ctor()
get_SupportsThemeMedia()
get_IsPreSorted()
get_IsPhysicalRoot()
get_SupportsInheritedParentImages()
get_SupportsPlayedStatus()
get_IsFolder()
get_IsDisplayedAsFolder()
get_SupportsCumulativeRunTimeTicks()
get_SupportsDateLastMediaAdded()
get_FileNameWithoutExtension()
get_Children()
set_Children(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>)
get_RecursiveChildren()
get_SupportsShortcutChildren()
get_FilterLinkedChildrenPerUser()
get_SupportsOwnedItems()
get_SupportsUserDataFromChildren()
CanDelete()
RequiresRefresh()
AddChild(MediaBrowser.Controller.Entities.BaseItem)
IsVisible(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
LoadChildren()
GetRefreshProgress()
ValidateChildren(System.IProgress`1<System.Double>,System.Threading.CancellationToken)
ValidateChildren(System.IProgress`1<System.Double>,MediaBrowser.Controller.Providers.MetadataRefreshOptions,System.Boolean,System.Boolean,System.Threading.CancellationToken)
GetActualChildrenDictionary()
IsLibraryFolderAccessible(MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Entities.BaseItem,System.Boolean)
GetNonCachedChildren(MediaBrowser.Controller.Providers.IDirectoryService)
GetCachedChildren()
GetChildCount(Jellyfin.Database.Implementations.Entities.User)
GetRecursiveChildCount(Jellyfin.Database.Implementations.Entities.User)
QueryRecursive(MediaBrowser.Controller.Entities.InternalItemsQuery)
QueryWithPostFiltering2(MediaBrowser.Controller.Entities.InternalItemsQuery)
RequiresPostFiltering2(MediaBrowser.Controller.Entities.InternalItemsQuery)
RequiresPostFiltering(MediaBrowser.Controller.Entities.InternalItemsQuery)
SortItemsByRequest(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Controller.Entities.BaseItem>)
GetItems(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemsInternal(MediaBrowser.Controller.Entities.InternalItemsQuery)
PostFilterAndSort(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,MediaBrowser.Controller.Entities.InternalItemsQuery)
CollapseBoxSetItemsIfNeeded(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,MediaBrowser.Controller.Entities.InternalItemsQuery,MediaBrowser.Controller.Entities.BaseItem,Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Configuration.IServerConfigurationManager,MediaBrowser.Controller.Collections.ICollectionManager)
CollapseBoxSetItems(MediaBrowser.Controller.Entities.InternalItemsQuery,MediaBrowser.Controller.Entities.BaseItem,Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Configuration.IServerConfigurationManager)
AllowBoxSetCollapsing(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetChildren(Jellyfin.Database.Implementations.Entities.User,System.Boolean,System.Int32&,MediaBrowser.Controller.Entities.InternalItemsQuery)
GetChildren(Jellyfin.Database.Implementations.Entities.User,System.Boolean,MediaBrowser.Controller.Entities.InternalItemsQuery)
GetEligibleChildrenForRecursiveChildren(Jellyfin.Database.Implementations.Entities.User)
AddChildren(Jellyfin.Database.Implementations.Entities.User,System.Boolean,System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Controller.Entities.BaseItem>,System.Boolean,MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.HashSet`1<MediaBrowser.Controller.Entities.Folder>)
AddChildrenFromCollection(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,Jellyfin.Database.Implementations.Entities.User,System.Boolean,System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Controller.Entities.BaseItem>,System.Boolean,MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.HashSet`1<MediaBrowser.Controller.Entities.Folder>)
GetRecursiveChildren(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.InternalItemsQuery,System.Int32&)
GetRecursiveChildren()
GetRecursiveChildren(System.Boolean)
GetRecursiveChildren(System.Func`2<MediaBrowser.Controller.Entities.BaseItem,System.Boolean>)
GetRecursiveChildren(System.Func`2<MediaBrowser.Controller.Entities.BaseItem,System.Boolean>,System.Boolean)
AddChildrenToList(System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Controller.Entities.BaseItem>,System.Boolean,System.Boolean,System.Func`2<MediaBrowser.Controller.Entities.BaseItem,System.Boolean>)
GetLinkedChildren()
ContainsLinkedChildByItemId(System.Guid)
GetLinkedChildren(Jellyfin.Database.Implementations.Entities.User)
GetLinkedChildrenInfos()
RefreshLinkedChildren(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>)
MarkPlayed(Jellyfin.Database.Implementations.Entities.User,System.Nullable`1<System.DateTime>,System.Boolean)
MarkUnplayed(Jellyfin.Database.Implementations.Entities.User)
IsPlayed(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.UserItemData)
IsUnplayed(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.UserItemData)
FillUserDataDtoValues(MediaBrowser.Model.Dto.UserItemDataDto,MediaBrowser.Controller.Entities.UserItemData,MediaBrowser.Model.Dto.BaseItemDto,Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Dto.DtoOptions)
GetProgress(System.Int32,System.Int32,System.Double)