< 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: 1824
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

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%561440%
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%32610%
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]
 90587        public override bool IsFolder => true;
 88
 89        [JsonIgnore]
 090        public override bool IsDisplayedAsFolder => true;
 91
 92        [JsonIgnore]
 9193        public virtual bool SupportsCumulativeRunTimeTicks => false;
 94
 95        [JsonIgnore]
 3596        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        {
 1125119            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                {
 0718                    items = GetRecursiveChildren(user, query, out totalCount);
 0719                    query.Limit = null;
 0720                    query.StartIndex = null; // override these here as they have already been applied
 721                }
 722
 0723                var result = PostFilterAndSort(items, query);
 0724                result.TotalRecordCount = totalCount;
 0725                return result;
 726            }
 727
 12728            if (this is not UserRootFolder
 12729                && this is not AggregateFolder
 12730                && query.ParentId.IsEmpty())
 731            {
 12732                query.Parent = this;
 733            }
 734
 12735            if (RequiresPostFiltering2(query))
 736            {
 0737                return QueryWithPostFiltering2(query);
 738            }
 739
 12740            return LibraryManager.GetItemsResult(query);
 741        }
 742
 743        protected QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
 744        {
 1745            var startIndex = query.StartIndex;
 1746            var limit = query.Limit;
 747
 1748            query.StartIndex = null;
 1749            query.Limit = null;
 750
 1751            IEnumerable<BaseItem> itemsList = LibraryManager.GetItemList(query);
 1752            var user = query.User;
 753
 1754            if (user is not null)
 755            {
 756                // needed for boxsets
 1757                itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
 758            }
 759
 760            IEnumerable<BaseItem> returnItems;
 1761            int totalCount = 0;
 762
 1763            if (query.EnableTotalRecordCount)
 764            {
 0765                var itemArray = itemsList.ToArray();
 0766                totalCount = itemArray.Length;
 0767                returnItems = itemArray;
 768            }
 769            else
 770            {
 1771                returnItems = itemsList;
 772            }
 773
 1774            if (limit.HasValue)
 775            {
 0776                returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
 777            }
 1778            else if (startIndex.HasValue)
 779            {
 0780                returnItems = returnItems.Skip(startIndex.Value);
 781            }
 782
 1783            return new QueryResult<BaseItem>(
 1784                query.StartIndex,
 1785                totalCount,
 1786                returnItems.ToArray());
 787        }
 788
 789        private bool RequiresPostFiltering2(InternalItemsQuery query)
 790        {
 12791            if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.BoxSet)
 792            {
 0793                Logger.LogDebug("Query requires post-filtering due to BoxSet query");
 0794                return true;
 795            }
 796
 12797            return false;
 798        }
 799
 800        private bool RequiresPostFiltering(InternalItemsQuery query)
 801        {
 12802            if (LinkedChildren.Length > 0)
 803            {
 0804                if (this is not ICollectionFolder)
 805                {
 0806                    Logger.LogDebug("{Type}: Query requires post-filtering due to LinkedChildren.", GetType().Name);
 0807                    return true;
 808                }
 809            }
 810
 811            // Filter by Video3DFormat
 12812            if (query.Is3D.HasValue)
 813            {
 0814                Logger.LogDebug("Query requires post-filtering due to Is3D");
 0815                return true;
 816            }
 817
 12818            if (query.HasOfficialRating.HasValue)
 819            {
 0820                Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
 0821                return true;
 822            }
 823
 12824            if (query.IsPlaceHolder.HasValue)
 825            {
 0826                Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
 0827                return true;
 828            }
 829
 12830            if (query.HasSpecialFeature.HasValue)
 831            {
 0832                Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
 0833                return true;
 834            }
 835
 12836            if (query.HasSubtitles.HasValue)
 837            {
 0838                Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
 0839                return true;
 840            }
 841
 12842            if (query.HasTrailer.HasValue)
 843            {
 0844                Logger.LogDebug("Query requires post-filtering due to HasTrailer");
 0845                return true;
 846            }
 847
 12848            if (query.HasThemeSong.HasValue)
 849            {
 0850                Logger.LogDebug("Query requires post-filtering due to HasThemeSong");
 0851                return true;
 852            }
 853
 12854            if (query.HasThemeVideo.HasValue)
 855            {
 0856                Logger.LogDebug("Query requires post-filtering due to HasThemeVideo");
 0857                return true;
 858            }
 859
 860            // Filter by VideoType
 12861            if (query.VideoTypes.Length > 0)
 862            {
 0863                Logger.LogDebug("Query requires post-filtering due to VideoTypes");
 0864                return true;
 865            }
 866
 12867            if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
 868            {
 0869                Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
 0870                return true;
 871            }
 872
 12873            if (!query.AdjacentTo.IsNullOrEmpty())
 874            {
 0875                Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
 0876                return true;
 877            }
 878
 12879            if (query.SeriesStatuses.Length > 0)
 880            {
 0881                Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
 0882                return true;
 883            }
 884
 12885            if (query.AiredDuringSeason.HasValue)
 886            {
 0887                Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
 0888                return true;
 889            }
 890
 12891            if (query.IsPlayed.HasValue)
 892            {
 0893                if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(BaseItemKind.Series))
 894                {
 0895                    Logger.LogDebug("Query requires post-filtering due to IsPlayed");
 0896                    return true;
 897                }
 898            }
 899
 12900            return false;
 901        }
 902
 903        private static BaseItem[] SortItemsByRequest(InternalItemsQuery query, IReadOnlyList<BaseItem> items)
 904        {
 0905            return items.OrderBy(i => Array.IndexOf(query.ItemIds, i.Id)).ToArray();
 906        }
 907
 908        public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
 909        {
 0910            if (query.ItemIds.Length > 0)
 911            {
 0912                var result = LibraryManager.GetItemsResult(query);
 913
 0914                if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
 915                {
 0916                    result.Items = SortItemsByRequest(query, result.Items);
 917                }
 918
 0919                return result;
 920            }
 921
 0922            return GetItemsInternal(query);
 923        }
 924
 925        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 926        {
 13927            query.EnableTotalRecordCount = false;
 928
 13929            if (query.ItemIds.Length > 0)
 930            {
 0931                var result = LibraryManager.GetItemList(query);
 932
 0933                if (query.OrderBy.Count == 0 && query.ItemIds.Length > 1)
 934                {
 0935                    return SortItemsByRequest(query, result);
 936                }
 937
 0938                return result;
 939            }
 940
 13941            return GetItemsInternal(query).Items;
 942        }
 943
 944        protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
 945        {
 12946            if (SourceType == SourceType.Channel)
 947            {
 948                try
 949                {
 0950                    query.Parent = this;
 0951                    query.ChannelIds = new[] { ChannelId };
 952
 953                    // Don't blow up here because it could cause parent screens with other content to fail
 0954                    return ChannelManager.GetChannelItemsInternal(query, new Progress<double>(), CancellationToken.None)
 955                }
 0956                catch
 957                {
 958                    // Already logged at lower levels
 0959                    return new QueryResult<BaseItem>();
 960                }
 961            }
 962
 12963            if (query.Recursive)
 964            {
 12965                return QueryRecursive(query);
 966            }
 967
 0968            var user = query.User;
 969
 0970            Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
 971
 972            IEnumerable<BaseItem> items;
 973
 0974            int totalItemCount = 0;
 0975            if (query.User is null)
 976            {
 0977                items = Children.Where(filter);
 0978                totalItemCount = items.Count();
 979            }
 980            else
 981            {
 982                // need to pass this param to the children.
 0983                var childQuery = new InternalItemsQuery
 0984                {
 0985                    DisplayAlbumFolders = query.DisplayAlbumFolders,
 0986                    Limit = query.Limit,
 0987                    StartIndex = query.StartIndex,
 0988                    NameStartsWith = query.NameStartsWith,
 0989                    NameStartsWithOrGreater = query.NameStartsWithOrGreater,
 0990                    NameLessThan = query.NameLessThan
 0991                };
 992
 0993                items = GetChildren(user, true, out totalItemCount, childQuery).Where(filter);
 994
 0995                query.Limit = null;
 0996                query.StartIndex = null;
 997            }
 998
 0999            var result = PostFilterAndSort(items, query);
 01000            result.TotalRecordCount = totalItemCount;
 01001            return result;
 01002        }
 1003
 1004        protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
 1005        {
 01006            var user = query.User;
 1007
 1008            // Check recursive - don't substitute in plain folder views
 01009            if (user is not null)
 1010            {
 01011                items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager);
 1012            }
 1013
 1014#pragma warning disable CA1309
 01015            if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
 1016            {
 01017                items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.Inva
 1018            }
 1019
 01020            if (!string.IsNullOrEmpty(query.NameStartsWith))
 1021            {
 01022                items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIg
 1023            }
 1024
 01025            if (!string.IsNullOrEmpty(query.NameLessThan))
 1026            {
 01027                items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.InvariantCultur
 1028            }
 1029#pragma warning restore CA1309
 1030
 1031            // This must be the last filter
 01032            if (!query.AdjacentTo.IsNullOrEmpty())
 1033            {
 01034                items = UserViewBuilder.FilterForAdjacency(items.ToList(), query.AdjacentTo.Value);
 1035            }
 1036
 01037            return UserViewBuilder.SortAndPage(items, null, query, LibraryManager);
 1038        }
 1039
 1040        private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(
 1041            IEnumerable<BaseItem> items,
 1042            InternalItemsQuery query,
 1043            BaseItem queryParent,
 1044            User user,
 1045            IServerConfigurationManager configurationManager,
 1046            ICollectionManager collectionManager)
 1047        {
 01048            ArgumentNullException.ThrowIfNull(items);
 1049
 01050            if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
 1051            {
 01052                items = collectionManager.CollapseItemsWithinBoxSets(items, user);
 1053            }
 1054
 01055            return items;
 1056        }
 1057
 1058        private static bool CollapseBoxSetItems(
 1059            InternalItemsQuery query,
 1060            BaseItem queryParent,
 1061            User user,
 1062            IServerConfigurationManager configurationManager)
 1063        {
 1064            // Could end up stuck in a loop like this
 121065            if (queryParent is BoxSet)
 1066            {
 01067                return false;
 1068            }
 1069
 121070            if (queryParent is Season)
 1071            {
 01072                return false;
 1073            }
 1074
 121075            if (queryParent is MusicAlbum)
 1076            {
 01077                return false;
 1078            }
 1079
 121080            if (queryParent is MusicArtist)
 1081            {
 01082                return false;
 1083            }
 1084
 121085            var param = query.CollapseBoxSetItems;
 1086
 121087            if (!param.HasValue)
 1088            {
 01089                if (user is not null && query.IncludeItemTypes.Any(type =>
 01090                    (type == BaseItemKind.Movie && !configurationManager.Configuration.EnableGroupingMoviesIntoCollectio
 01091                    (type == BaseItemKind.Series && !configurationManager.Configuration.EnableGroupingShowsIntoCollectio
 1092                {
 01093                    return false;
 1094                }
 1095
 01096                if (query.IncludeItemTypes.Length == 0
 01097                    || query.IncludeItemTypes.Any(type => type == BaseItemKind.Movie || type == BaseItemKind.Series))
 1098                {
 01099                    param = true;
 1100                }
 1101            }
 1102
 121103            return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
 1104        }
 1105
 1106        private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
 1107        {
 01108            if (request.IsFavorite.HasValue)
 1109            {
 01110                return false;
 1111            }
 1112
 01113            if (request.IsFavoriteOrLiked.HasValue)
 1114            {
 01115                return false;
 1116            }
 1117
 01118            if (request.IsLiked.HasValue)
 1119            {
 01120                return false;
 1121            }
 1122
 01123            if (request.IsPlayed.HasValue)
 1124            {
 01125                return false;
 1126            }
 1127
 01128            if (request.IsResumable.HasValue)
 1129            {
 01130                return false;
 1131            }
 1132
 01133            if (request.IsFolder.HasValue)
 1134            {
 01135                return false;
 1136            }
 1137
 01138            if (request.Genres.Count > 0)
 1139            {
 01140                return false;
 1141            }
 1142
 01143            if (request.GenreIds.Count > 0)
 1144            {
 01145                return false;
 1146            }
 1147
 01148            if (request.HasImdbId.HasValue)
 1149            {
 01150                return false;
 1151            }
 1152
 01153            if (request.HasOfficialRating.HasValue)
 1154            {
 01155                return false;
 1156            }
 1157
 01158            if (request.HasOverview.HasValue)
 1159            {
 01160                return false;
 1161            }
 1162
 01163            if (request.HasParentalRating.HasValue)
 1164            {
 01165                return false;
 1166            }
 1167
 01168            if (request.HasSpecialFeature.HasValue)
 1169            {
 01170                return false;
 1171            }
 1172
 01173            if (request.HasSubtitles.HasValue)
 1174            {
 01175                return false;
 1176            }
 1177
 01178            if (request.HasThemeSong.HasValue)
 1179            {
 01180                return false;
 1181            }
 1182
 01183            if (request.HasThemeVideo.HasValue)
 1184            {
 01185                return false;
 1186            }
 1187
 01188            if (request.HasTmdbId.HasValue)
 1189            {
 01190                return false;
 1191            }
 1192
 01193            if (request.HasTrailer.HasValue)
 1194            {
 01195                return false;
 1196            }
 1197
 01198            if (request.ImageTypes.Length > 0)
 1199            {
 01200                return false;
 1201            }
 1202
 01203            if (request.Is3D.HasValue)
 1204            {
 01205                return false;
 1206            }
 1207
 01208            if (request.Is4K.HasValue)
 1209            {
 01210                return false;
 1211            }
 1212
 01213            if (request.IsHD.HasValue)
 1214            {
 01215                return false;
 1216            }
 1217
 01218            if (request.IsLocked.HasValue)
 1219            {
 01220                return false;
 1221            }
 1222
 01223            if (request.IsPlaceHolder.HasValue)
 1224            {
 01225                return false;
 1226            }
 1227
 01228            if (!string.IsNullOrWhiteSpace(request.Person))
 1229            {
 01230                return false;
 1231            }
 1232
 01233            if (request.PersonIds.Length > 0)
 1234            {
 01235                return false;
 1236            }
 1237
 01238            if (request.ItemIds.Length > 0)
 1239            {
 01240                return false;
 1241            }
 1242
 01243            if (request.StudioIds.Length > 0)
 1244            {
 01245                return false;
 1246            }
 1247
 01248            if (request.VideoTypes.Length > 0)
 1249            {
 01250                return false;
 1251            }
 1252
 01253            if (request.Years.Length > 0)
 1254            {
 01255                return false;
 1256            }
 1257
 01258            if (request.Tags.Length > 0)
 1259            {
 01260                return false;
 1261            }
 1262
 01263            if (request.OfficialRatings.Length > 0)
 1264            {
 01265                return false;
 1266            }
 1267
 01268            if (request.MinIndexNumber.HasValue)
 1269            {
 01270                return false;
 1271            }
 1272
 01273            if (request.OrderBy.Any(o =>
 01274                o.OrderBy == ItemSortBy.CommunityRating ||
 01275                o.OrderBy == ItemSortBy.CriticRating ||
 01276                o.OrderBy == ItemSortBy.Runtime))
 1277            {
 01278                return false;
 1279            }
 1280
 01281            return true;
 1282        }
 1283
 1284        public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, out int totalItemCount
 1285        {
 101286            ArgumentNullException.ThrowIfNull(user);
 101287            query ??= new InternalItemsQuery();
 101288            query.User = user;
 1289
 1290            // the true root should return our users root folder children
 101291            if (IsPhysicalRoot)
 1292            {
 01293                return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren, out totalItemCount);
 1294            }
 1295
 101296            var result = new Dictionary<Guid, BaseItem>();
 1297
 101298            totalItemCount = AddChildren(user, includeLinkedChildren, result, false, query);
 1299
 101300            return result.Values.ToArray();
 1301        }
 1302
 1303        public virtual IReadOnlyList<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery que
 1304        {
 101305            return GetChildren(user, includeLinkedChildren, out _, query);
 1306        }
 1307
 1308        protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
 1309        {
 101310            return Children;
 1311        }
 1312
 1313        /// <summary>
 1314        /// Adds the children to list.
 1315        /// </summary>
 1316        private int AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive
 1317        {
 1318            // Prevent infinite recursion of nested folders
 101319            visitedFolders ??= new HashSet<Folder>();
 101320            if (!visitedFolders.Add(this))
 1321            {
 01322                return 0;
 1323            }
 1324
 1325            // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in mus
 101326            IEnumerable<BaseItem> children = null;
 101327            if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum))
 1328            {
 01329                children = Children;
 01330                query = null;
 1331            }
 1332
 1333            // If there are not sub-folders, proceed as normal.
 101334            if (children is null)
 1335            {
 101336                children = GetEligibleChildrenForRecursiveChildren(user);
 1337            }
 1338
 101339            if (includeLinkedChildren)
 1340            {
 101341                children = children.Concat(GetLinkedChildren(user)).ToArray();
 1342            }
 1343
 101344            return AddChildrenFromCollection(children, user, includeLinkedChildren, result, recursive, query, visitedFol
 1345        }
 1346
 1347        private int AddChildrenFromCollection(IEnumerable<BaseItem> children, User user, bool includeLinkedChildren, Dic
 1348        {
 101349            query ??= new InternalItemsQuery();
 101350            var limit = query.Limit > 0 ? query.Limit : int.MaxValue;
 101351            query.Limit = 0;
 1352
 101353            var visibleChildren = children
 101354                .Where(e => e.IsVisible(user))
 101355                .ToArray();
 1356
 101357            var realChildren = visibleChildren
 101358                .Where(e => query is null || UserViewBuilder.FilterItem(e, query))
 101359                .ToArray();
 1360
 101361            if (this is BoxSet && (query.OrderBy is null || query.OrderBy.Count == 0))
 1362            {
 01363                realChildren = realChildren
 01364                    .OrderBy(e => e.ProductionYear ?? int.MaxValue)
 01365                    .ToArray();
 1366            }
 1367
 101368            var childCount = realChildren.Length;
 101369            if (result.Count < limit)
 1370            {
 101371                var remainingCount = (int)(limit - result.Count);
 401372                foreach (var child in realChildren
 101373                    .Skip(query.StartIndex ?? 0)
 101374                    .Take(remainingCount))
 1375                {
 101376                    result[child.Id] = child;
 1377                }
 1378            }
 1379
 101380            if (recursive)
 1381            {
 01382                foreach (var child in visibleChildren
 01383                    .Where(e => e.IsFolder)
 01384                    .OfType<Folder>())
 1385                {
 01386                    childCount += child.AddChildren(user, includeLinkedChildren, result, true, query, visitedFolders);
 1387                }
 1388            }
 1389
 101390            return childCount;
 1391        }
 1392
 1393        public virtual IReadOnlyList<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query, out int totalCo
 1394        {
 01395            ArgumentNullException.ThrowIfNull(user);
 1396
 01397            var result = new Dictionary<Guid, BaseItem>();
 1398
 01399            totalCount = AddChildren(user, true, result, true, query);
 1400
 01401            return result.Values.ToArray();
 1402        }
 1403
 1404        /// <summary>
 1405        /// Gets the recursive children.
 1406        /// </summary>
 1407        /// <returns>IList{BaseItem}.</returns>
 1408        public IReadOnlyList<BaseItem> GetRecursiveChildren()
 1409        {
 01410            return GetRecursiveChildren(true);
 1411        }
 1412
 1413        public IReadOnlyList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
 1414        {
 01415            return GetRecursiveChildren(i => true, includeLinkedChildren);
 1416        }
 1417
 1418        public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
 1419        {
 01420            return GetRecursiveChildren(filter, true);
 1421        }
 1422
 1423        public IReadOnlyList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
 1424        {
 01425            var result = new Dictionary<Guid, BaseItem>();
 1426
 01427            AddChildrenToList(result, includeLinkedChildren, true, filter);
 1428
 01429            return result.Values.ToArray();
 1430        }
 1431
 1432        /// <summary>
 1433        /// Adds the children to list.
 1434        /// </summary>
 1435        private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Fu
 1436        {
 01437            foreach (var child in Children)
 1438            {
 01439                if (filter is null || filter(child))
 1440                {
 01441                    result[child.Id] = child;
 1442                }
 1443
 01444                if (recursive && child.IsFolder)
 1445                {
 01446                    var folder = (Folder)child;
 1447
 1448                    // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loo
 01449                    folder.AddChildrenToList(result, false, true, filter);
 1450                }
 1451            }
 1452
 01453            if (includeLinkedChildren)
 1454            {
 01455                foreach (var child in GetLinkedChildren())
 1456                {
 01457                    if (filter is null || filter(child))
 1458                    {
 01459                        result[child.Id] = child;
 1460                    }
 1461                }
 1462            }
 01463        }
 1464
 1465        /// <summary>
 1466        /// Gets the linked children.
 1467        /// </summary>
 1468        /// <returns>IEnumerable{BaseItem}.</returns>
 1469        public List<BaseItem> GetLinkedChildren()
 1470        {
 101471            var linkedChildren = LinkedChildren;
 101472            var list = new List<BaseItem>(linkedChildren.Length);
 1473
 201474            foreach (var i in linkedChildren)
 1475            {
 01476                var child = GetLinkedChild(i);
 1477
 01478                if (child is not null)
 1479                {
 01480                    list.Add(child);
 1481                }
 1482            }
 1483
 101484            return list;
 1485        }
 1486
 1487        public bool ContainsLinkedChildByItemId(Guid itemId)
 1488        {
 01489            var linkedChildren = LinkedChildren;
 01490            foreach (var i in linkedChildren)
 1491            {
 01492                if (i.ItemId.HasValue)
 1493                {
 01494                    if (i.ItemId.Value.Equals(itemId))
 1495                    {
 01496                        return true;
 1497                    }
 1498
 1499                    continue;
 1500                }
 1501
 01502                var child = GetLinkedChild(i);
 1503
 01504                if (child is not null && child.Id.Equals(itemId))
 1505                {
 01506                    return true;
 1507                }
 1508            }
 1509
 01510            return false;
 1511        }
 1512
 1513        public List<BaseItem> GetLinkedChildren(User user)
 1514        {
 101515            if (!FilterLinkedChildrenPerUser || user is null)
 1516            {
 101517                return GetLinkedChildren();
 1518            }
 1519
 01520            var linkedChildren = LinkedChildren;
 01521            var list = new List<BaseItem>(linkedChildren.Length);
 1522
 01523            if (linkedChildren.Length == 0)
 1524            {
 01525                return list;
 1526            }
 1527
 01528            var allUserRootChildren = LibraryManager.GetUserRootFolder()
 01529                .GetChildren(user, true)
 01530                .OfType<Folder>()
 01531                .ToList();
 1532
 01533            var collectionFolderIds = allUserRootChildren
 01534                .Select(i => i.Id)
 01535                .ToList();
 1536
 01537            foreach (var i in linkedChildren)
 1538            {
 01539                var child = GetLinkedChild(i);
 1540
 01541                if (child is null)
 1542                {
 1543                    continue;
 1544                }
 1545
 01546                var childOwner = child.GetOwner() ?? child;
 1547
 01548                if (child is not IItemByName)
 1549                {
 01550                    var childProtocol = childOwner.PathProtocol;
 01551                    if (!childProtocol.HasValue || childProtocol.Value != Model.MediaInfo.MediaProtocol.File)
 1552                    {
 01553                        if (!childOwner.IsVisibleStandalone(user))
 1554                        {
 01555                            continue;
 1556                        }
 1557                    }
 1558                    else
 1559                    {
 01560                        var itemCollectionFolderIds =
 01561                            LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id);
 1562
 01563                        if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
 1564                        {
 1565                            continue;
 1566                        }
 1567                    }
 1568                }
 1569
 01570                list.Add(child);
 1571            }
 1572
 01573            return list;
 1574        }
 1575
 1576        /// <summary>
 1577        /// Gets the linked children.
 1578        /// </summary>
 1579        /// <returns>IEnumerable{BaseItem}.</returns>
 1580        public IReadOnlyList<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
 1581        {
 01582            return LinkedChildren
 01583                .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
 01584                .Where(i => i.Item2 is not null)
 01585                .ToArray();
 1586        }
 1587
 1588        protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystem
 1589        {
 1590            var changesFound = false;
 1591
 1592            if (IsFileProtocol)
 1593            {
 1594                if (RefreshLinkedChildren(fileSystemChildren))
 1595                {
 1596                    changesFound = true;
 1597                }
 1598            }
 1599
 1600            var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).Configur
 1601
 1602            return baseHasChanges || changesFound;
 1603        }
 1604
 1605        /// <summary>
 1606        /// Refreshes the linked children.
 1607        /// </summary>
 1608        /// <param name="fileSystemChildren">The enumerable of file system metadata.</param>
 1609        /// <returns><c>true</c> if the linked children were updated, <c>false</c> otherwise.</returns>
 1610        protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
 1611        {
 211612            if (SupportsShortcutChildren)
 1613            {
 211614                var newShortcutLinks = fileSystemChildren
 211615                    .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
 211616                    .Select(i =>
 211617                    {
 211618                        try
 211619                        {
 211620                            Logger.LogDebug("Found shortcut at {0}", i.FullName);
 211621
 211622                            var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShor
 211623
 211624                            if (!string.IsNullOrEmpty(resolvedPath))
 211625                            {
 211626                                return new LinkedChild
 211627                                {
 211628                                    Path = resolvedPath,
 211629                                    Type = LinkedChildType.Shortcut
 211630                                };
 211631                            }
 211632
 211633                            Logger.LogError("Error resolving shortcut {0}", i.FullName);
 211634
 211635                            return null;
 211636                        }
 211637                        catch (IOException ex)
 211638                        {
 211639                            Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName);
 211640                            return null;
 211641                        }
 211642                    })
 211643                    .Where(i => i is not null)
 211644                    .ToList();
 1645
 211646                var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
 1647
 211648                if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
 1649                {
 01650                    Logger.LogInformation("Shortcut links have changed for {0}", Path);
 1651
 01652                    newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual));
 01653                    LinkedChildren = newShortcutLinks.ToArray();
 01654                    return true;
 1655                }
 1656            }
 1657
 421658            foreach (var child in LinkedChildren)
 1659            {
 1660                // Reset the cached value
 01661                child.ItemId = null;
 1662            }
 1663
 211664            return false;
 1665        }
 1666
 1667        /// <summary>
 1668        /// Marks the played.
 1669        /// </summary>
 1670        /// <param name="user">The user.</param>
 1671        /// <param name="datePlayed">The date played.</param>
 1672        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 1673        public override void MarkPlayed(
 1674            User user,
 1675            DateTime? datePlayed,
 1676            bool resetPosition)
 1677        {
 01678            var query = new InternalItemsQuery
 01679            {
 01680                User = user,
 01681                Recursive = true,
 01682                IsFolder = false,
 01683                EnableTotalRecordCount = false
 01684            };
 1685
 01686            if (!user.DisplayMissingEpisodes)
 1687            {
 01688                query.IsVirtualItem = false;
 1689            }
 1690
 01691            var itemsResult = GetItemList(query);
 1692
 1693            // Sweep through recursively and update status
 01694            foreach (var item in itemsResult)
 1695            {
 01696                if (item.IsVirtualItem)
 1697                {
 1698                    // The querying doesn't support virtual unaired
 01699                    var episode = item as Episode;
 01700                    if (episode is not null && episode.IsUnaired)
 1701                    {
 1702                        continue;
 1703                    }
 1704                }
 1705
 01706                item.MarkPlayed(user, datePlayed, resetPosition);
 1707            }
 01708        }
 1709
 1710        /// <summary>
 1711        /// Marks the unplayed.
 1712        /// </summary>
 1713        /// <param name="user">The user.</param>
 1714        public override void MarkUnplayed(User user)
 1715        {
 01716            var itemsResult = GetItemList(new InternalItemsQuery
 01717            {
 01718                User = user,
 01719                Recursive = true,
 01720                IsFolder = false,
 01721                EnableTotalRecordCount = false
 01722            });
 1723
 1724            // Sweep through recursively and update status
 01725            foreach (var item in itemsResult)
 1726            {
 01727                item.MarkUnplayed(user);
 1728            }
 01729        }
 1730
 1731        public override bool IsPlayed(User user, UserItemData userItemData)
 1732        {
 01733            return ItemRepository.GetIsPlayed(user, Id, true);
 1734        }
 1735
 1736        public override bool IsUnplayed(User user, UserItemData userItemData)
 1737        {
 01738            return !IsPlayed(user, userItemData);
 1739        }
 1740
 1741        public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User
 1742        {
 91743            if (!SupportsUserDataFromChildren)
 1744            {
 91745                return;
 1746            }
 1747
 01748            if (itemDto is not null && fields.ContainsField(ItemFields.RecursiveItemCount))
 1749            {
 01750                itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
 1751            }
 1752
 01753            if (SupportsPlayedStatus)
 1754            {
 01755                var unplayedQueryResult = GetItems(new InternalItemsQuery(user)
 01756                {
 01757                    Recursive = true,
 01758                    IsFolder = false,
 01759                    IsVirtualItem = false,
 01760                    EnableTotalRecordCount = true,
 01761                    Limit = 0,
 01762                    IsPlayed = false,
 01763                    DtoOptions = new DtoOptions(false)
 01764                    {
 01765                        EnableImages = false
 01766                    }
 01767                }).TotalRecordCount;
 1768
 01769                dto.UnplayedItemCount = unplayedQueryResult;
 1770
 01771                if (itemDto?.RecursiveItemCount > 0)
 1772                {
 01773                    var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100;
 01774                    dto.PlayedPercentage = 100 - unplayedPercentage;
 01775                    dto.Played = dto.PlayedPercentage.Value >= 100;
 1776                }
 1777                else
 1778                {
 01779                    dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
 1780                }
 1781            }
 01782        }
 1783
 1784        /// <summary>
 1785        /// Contains constants used when reporting scan progress.
 1786        /// </summary>
 1787        private static class ProgressHelpers
 1788        {
 1789            /// <summary>
 1790            /// Reported after the folders immediate children are retrieved.
 1791            /// </summary>
 1792            public const int RetrievedChildren = 5;
 1793
 1794            /// <summary>
 1795            /// Reported after add, updating, or deleting child items from the LibraryManager.
 1796            /// </summary>
 1797            public const int UpdatedChildItems = 10;
 1798
 1799            /// <summary>
 1800            /// Reported once subfolders are scanned.
 1801            /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders].
 1802            /// </summary>
 1803            public const int ScannedSubfolders = 50;
 1804
 1805            /// <summary>
 1806            /// Reported once metadata is refreshed.
 1807            /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed].
 1808            /// </summary>
 1809            public const int RefreshedMetadata = 100;
 1810
 1811            /// <summary>
 1812            /// Gets the current progress given the previous step, next step, and progress in between.
 1813            /// </summary>
 1814            /// <param name="previousProgressStep">The previous progress step.</param>
 1815            /// <param name="nextProgressStep">The next progress step.</param>
 1816            /// <param name="currentProgress">The current progress step.</param>
 1817            /// <returns>The progress.</returns>
 1818            public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress)
 1819            {
 781820                return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100));
 1821            }
 1822        }
 1823    }
 1824}

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)