< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Library.LibraryManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Library/LibraryManager.cs
Line coverage
39%
Covered lines: 427
Uncovered lines: 648
Coverable lines: 1075
Total lines: 3254
Line coverage: 39.7%
Branch coverage
32%
Covered branches: 200
Total branches: 608
Branch coverage: 32.8%
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_RootFolder()100%44100%
get_LibraryMonitor()100%11100%
get_ProviderManager()100%11100%
get_UserViewManager()100%11100%
AddParts(...)100%11100%
RecordConfigurationValues(...)100%11100%
ConfigurationUpdated(...)100%22100%
RegisterItem(...)50%191055.55%
DeleteItem(...)100%210%
DeleteItem(...)0%620%
DeleteItem(...)25%10204825%
IsInternalItem(...)50%741844.44%
GetMetadataPaths(...)50%2275%
GetInternalMetadataPaths(...)12.5%20842.85%
ResolveItem(...)100%44100%
Resolve(...)100%1140%
GetNewItemId(...)100%11100%
GetNewItemIdInternal(...)100%66100%
ResolvePath(...)100%22100%
ResolvePath(...)70%242078.12%
IgnoreFile(...)100%11100%
NormalizeRootPathList(...)50%2291.66%
ResolvePaths(...)100%11100%
ResolvePaths(...)58.33%221258.33%
CreateRootFolder()71.42%141488.46%
GetUserRootFolder()80%111079.16%
FindByPath(...)100%210%
GetPerson(...)50%2280%
GetStudio(...)100%210%
GetStudioId(...)100%210%
GetGenreId(...)100%210%
GetMusicGenreId(...)100%210%
GetGenre(...)100%210%
GetMusicGenre(...)100%210%
GetYear(...)0%620%
GetArtist(...)100%210%
GetArtist(...)100%210%
CreateItemByName(...)0%7280%
GetItemByNameId(...)100%11100%
ValidatePeopleAsync(...)100%210%
ValidateMediaLibrary(...)100%11100%
GetVirtualFolders()100%11100%
GetVirtualFolders(...)100%22100%
GetVirtualFolderInfo(...)70%101097.14%
GetCollectionType(...)50%6450%
GetItemById(...)66.66%7675%
GetItemById(...)100%22100%
GetItemById(...)50%22100%
GetItemById(...)50%22100%
GetItemList(...)100%1010100%
GetItemList(...)100%11100%
GetCount(...)0%7280%
GetItemList(...)0%4260%
GetLatestItemList(...)0%4260%
GetNextUpSeriesKeys(...)0%4260%
QueryItems(...)0%2040%
GetItemIds(...)50%2266.66%
GetStudios(...)0%620%
GetGenres(...)0%620%
GetMusicGenres(...)0%620%
GetAllArtists(...)0%620%
GetArtists(...)0%620%
SetTopParentOrAncestorIds(...)0%210140%
GetAlbumArtists(...)0%620%
GetItemsResult(...)100%1010100%
SetTopParentIdsOrAncestors(...)83.33%6688.88%
AddUserToQuery(...)100%1616100%
GetTopParentIdsForQuery(...)8.33%4342410.71%
ResolveIntro(...)0%110100%
Sort(...)57.14%341453.33%
Sort(...)0%210140%
GetComparer(...)50%3237.5%
CreateItem(...)100%210%
CreateItems(...)90%101083.33%
ImageNeedsRefresh(...)0%156120%
UpdateItemAsync(...)100%11100%
ReportItemRemoved(...)100%2276.92%
RetrieveItem(...)100%11100%
GetCollectionFolders(...)100%11100%
GetCollectionFolders(...)80%111081.81%
GetCollectionFoldersInternal(...)100%11100%
GetLibraryOptions(...)75%44100%
GetContentType(...)50%4471.42%
GetInheritedContentType(...)50%2283.33%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)50%2266.66%
GetContentTypeOverride(...)50%4485.71%
GetTopFolderContentType(...)50%11863.63%
GetNamedView(...)100%210%
GetNamedView(...)0%4260%
GetNamedView(...)0%420200%
GetShadowView(...)0%272160%
GetNamedView(...)0%600240%
GetParentItem(...)33.33%8660%
QueueLibraryScan()100%210%
GetSeasonNumberFromPath(...)0%2040%
FillMissingEpisodeNumbersFromPath(...)0%3192560%
ParseName(...)0%620%
GetPathAfterNetworkSubstitution(...)25%6450%
GetPeople(...)100%210%
GetPeople(...)50%11425%
GetPeopleItems(...)100%210%
GetPeopleNames(...)100%210%
UpdatePeople(...)100%210%
StartScanInBackground()100%11100%
AddMediaPath(...)100%1150%
AddMediaPathInternal(...)25%36823.8%
UpdateMediaPath(...)100%210%
SyncLibraryOptionsToLocations(...)0%7280%
RemoveContentTypeOverrides(...)0%210140%
RemoveMediaPath(...)25%9433.33%
ItemIsVisible(...)16.66%14640%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/Library/LibraryManager.cs

#LineLine coverage
 1#pragma warning disable CS1591
 2#pragma warning disable CA5394
 3
 4using System;
 5using System.Collections.Generic;
 6using System.Globalization;
 7using System.IO;
 8using System.Linq;
 9using System.Net;
 10using System.Net.Http;
 11using System.Threading;
 12using System.Threading.Tasks;
 13using BitFaster.Caching.Lru;
 14using Emby.Naming.Common;
 15using Emby.Naming.TV;
 16using Emby.Server.Implementations.Library.Resolvers;
 17using Emby.Server.Implementations.Library.Validators;
 18using Emby.Server.Implementations.Playlists;
 19using Emby.Server.Implementations.ScheduledTasks.Tasks;
 20using Emby.Server.Implementations.Sorting;
 21using Jellyfin.Data;
 22using Jellyfin.Data.Enums;
 23using Jellyfin.Database.Implementations.Entities;
 24using Jellyfin.Database.Implementations.Enums;
 25using Jellyfin.Extensions;
 26using MediaBrowser.Common.Extensions;
 27using MediaBrowser.Controller;
 28using MediaBrowser.Controller.Configuration;
 29using MediaBrowser.Controller.Drawing;
 30using MediaBrowser.Controller.Dto;
 31using MediaBrowser.Controller.Entities;
 32using MediaBrowser.Controller.Entities.Audio;
 33using MediaBrowser.Controller.IO;
 34using MediaBrowser.Controller.Library;
 35using MediaBrowser.Controller.LiveTv;
 36using MediaBrowser.Controller.MediaEncoding;
 37using MediaBrowser.Controller.MediaSegments;
 38using MediaBrowser.Controller.Persistence;
 39using MediaBrowser.Controller.Providers;
 40using MediaBrowser.Controller.Resolvers;
 41using MediaBrowser.Controller.Sorting;
 42using MediaBrowser.Controller.Trickplay;
 43using MediaBrowser.Model.Configuration;
 44using MediaBrowser.Model.Dlna;
 45using MediaBrowser.Model.Drawing;
 46using MediaBrowser.Model.Dto;
 47using MediaBrowser.Model.Entities;
 48using MediaBrowser.Model.IO;
 49using MediaBrowser.Model.Library;
 50using MediaBrowser.Model.Querying;
 51using MediaBrowser.Model.Tasks;
 52using Microsoft.Extensions.Logging;
 53using Episode = MediaBrowser.Controller.Entities.TV.Episode;
 54using EpisodeInfo = Emby.Naming.TV.EpisodeInfo;
 55using Genre = MediaBrowser.Controller.Entities.Genre;
 56using Person = MediaBrowser.Controller.Entities.Person;
 57using VideoResolver = Emby.Naming.Video.VideoResolver;
 58
 59namespace Emby.Server.Implementations.Library
 60{
 61    /// <summary>
 62    /// Class LibraryManager.
 63    /// </summary>
 64    public class LibraryManager : ILibraryManager
 65    {
 66        private const string ShortcutFileExtension = ".mblink";
 67
 68        private readonly ILogger<LibraryManager> _logger;
 69        private readonly ITaskManager _taskManager;
 70        private readonly IUserManager _userManager;
 71        private readonly IUserDataManager _userDataManager;
 72        private readonly IServerConfigurationManager _configurationManager;
 73        private readonly Lazy<ILibraryMonitor> _libraryMonitorFactory;
 74        private readonly Lazy<IProviderManager> _providerManagerFactory;
 75        private readonly Lazy<IUserViewManager> _userViewManagerFactory;
 76        private readonly IServerApplicationHost _appHost;
 77        private readonly IMediaEncoder _mediaEncoder;
 78        private readonly IFileSystem _fileSystem;
 79        private readonly IItemRepository _itemRepository;
 80        private readonly IImageProcessor _imageProcessor;
 81        private readonly NamingOptions _namingOptions;
 82        private readonly IPeopleRepository _peopleRepository;
 83        private readonly ExtraResolver _extraResolver;
 84        private readonly IPathManager _pathManager;
 85        private readonly FastConcurrentLru<Guid, BaseItem> _cache;
 86
 87        /// <summary>
 88        /// The _root folder sync lock.
 89        /// </summary>
 2890        private readonly Lock _rootFolderSyncLock = new();
 2891        private readonly Lock _userRootFolderSyncLock = new();
 92
 2893        private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
 94
 95        /// <summary>
 96        /// The _root folder.
 97        /// </summary>
 98        private volatile AggregateFolder? _rootFolder;
 99        private volatile UserRootFolder? _userRootFolder;
 100
 101        private bool _wizardCompleted;
 102
 103        /// <summary>
 104        /// Initializes a new instance of the <see cref="LibraryManager" /> class.
 105        /// </summary>
 106        /// <param name="appHost">The application host.</param>
 107        /// <param name="loggerFactory">The logger factory.</param>
 108        /// <param name="taskManager">The task manager.</param>
 109        /// <param name="userManager">The user manager.</param>
 110        /// <param name="configurationManager">The configuration manager.</param>
 111        /// <param name="userDataManager">The user data manager.</param>
 112        /// <param name="libraryMonitorFactory">The library monitor.</param>
 113        /// <param name="fileSystem">The file system.</param>
 114        /// <param name="providerManagerFactory">The provider manager.</param>
 115        /// <param name="userViewManagerFactory">The user view manager.</param>
 116        /// <param name="mediaEncoder">The media encoder.</param>
 117        /// <param name="itemRepository">The item repository.</param>
 118        /// <param name="imageProcessor">The image processor.</param>
 119        /// <param name="namingOptions">The naming options.</param>
 120        /// <param name="directoryService">The directory service.</param>
 121        /// <param name="peopleRepository">The people repository.</param>
 122        /// <param name="pathManager">The path manager.</param>
 123        public LibraryManager(
 124            IServerApplicationHost appHost,
 125            ILoggerFactory loggerFactory,
 126            ITaskManager taskManager,
 127            IUserManager userManager,
 128            IServerConfigurationManager configurationManager,
 129            IUserDataManager userDataManager,
 130            Lazy<ILibraryMonitor> libraryMonitorFactory,
 131            IFileSystem fileSystem,
 132            Lazy<IProviderManager> providerManagerFactory,
 133            Lazy<IUserViewManager> userViewManagerFactory,
 134            IMediaEncoder mediaEncoder,
 135            IItemRepository itemRepository,
 136            IImageProcessor imageProcessor,
 137            NamingOptions namingOptions,
 138            IDirectoryService directoryService,
 139            IPeopleRepository peopleRepository,
 140            IPathManager pathManager)
 141        {
 28142            _appHost = appHost;
 28143            _logger = loggerFactory.CreateLogger<LibraryManager>();
 28144            _taskManager = taskManager;
 28145            _userManager = userManager;
 28146            _configurationManager = configurationManager;
 28147            _userDataManager = userDataManager;
 28148            _libraryMonitorFactory = libraryMonitorFactory;
 28149            _fileSystem = fileSystem;
 28150            _providerManagerFactory = providerManagerFactory;
 28151            _userViewManagerFactory = userViewManagerFactory;
 28152            _mediaEncoder = mediaEncoder;
 28153            _itemRepository = itemRepository;
 28154            _imageProcessor = imageProcessor;
 155
 28156            _cache = new FastConcurrentLru<Guid, BaseItem>(_configurationManager.Configuration.CacheSize);
 157
 28158            _namingOptions = namingOptions;
 28159            _peopleRepository = peopleRepository;
 28160            _pathManager = pathManager;
 28161            _extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryServ
 162
 28163            _configurationManager.ConfigurationUpdated += ConfigurationUpdated;
 164
 28165            RecordConfigurationValues(_configurationManager.Configuration);
 28166        }
 167
 168        /// <summary>
 169        /// Occurs when [item added].
 170        /// </summary>
 171        public event EventHandler<ItemChangeEventArgs>? ItemAdded;
 172
 173        /// <summary>
 174        /// Occurs when [item updated].
 175        /// </summary>
 176        public event EventHandler<ItemChangeEventArgs>? ItemUpdated;
 177
 178        /// <summary>
 179        /// Occurs when [item removed].
 180        /// </summary>
 181        public event EventHandler<ItemChangeEventArgs>? ItemRemoved;
 182
 183        /// <summary>
 184        /// Gets the root folder.
 185        /// </summary>
 186        /// <value>The root folder.</value>
 187        public AggregateFolder RootFolder
 188        {
 189            get
 190            {
 146191                if (_rootFolder is null)
 21192                {
 193                    lock (_rootFolderSyncLock)
 194                    {
 21195                        _rootFolder ??= CreateRootFolder();
 21196                    }
 197                }
 198
 146199                return _rootFolder;
 200            }
 201        }
 202
 39203        private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
 204
 88205        private IProviderManager ProviderManager => _providerManagerFactory.Value;
 206
 1207        private IUserViewManager UserViewManager => _userViewManagerFactory.Value;
 208
 209        /// <summary>
 210        /// Gets or sets the postscan tasks.
 211        /// </summary>
 212        /// <value>The postscan tasks.</value>
 213        private ILibraryPostScanTask[] PostScanTasks { get; set; } = [];
 214
 215        /// <summary>
 216        /// Gets or sets the intro providers.
 217        /// </summary>
 218        /// <value>The intro providers.</value>
 219        private IIntroProvider[] IntroProviders { get; set; } = [];
 220
 221        /// <summary>
 222        /// Gets or sets the list of entity resolution ignore rules.
 223        /// </summary>
 224        /// <value>The entity resolution ignore rules.</value>
 225        private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; } = [];
 226
 227        /// <summary>
 228        /// Gets or sets the list of currently registered entity resolvers.
 229        /// </summary>
 230        /// <value>The entity resolvers enumerable.</value>
 231        private IItemResolver[] EntityResolvers { get; set; } = [];
 232
 233        private IMultiItemResolver[] MultiItemResolvers { get; set; } = [];
 234
 235        /// <summary>
 236        /// Gets or sets the comparers.
 237        /// </summary>
 238        /// <value>The comparers.</value>
 239        private IBaseItemComparer[] Comparers { get; set; } = [];
 240
 241        public bool IsScanRunning { get; private set; }
 242
 243        /// <summary>
 244        /// Adds the parts.
 245        /// </summary>
 246        /// <param name="rules">The rules.</param>
 247        /// <param name="resolvers">The resolvers.</param>
 248        /// <param name="introProviders">The intro providers.</param>
 249        /// <param name="itemComparers">The item comparers.</param>
 250        /// <param name="postScanTasks">The post scan tasks.</param>
 251        public void AddParts(
 252            IEnumerable<IResolverIgnoreRule> rules,
 253            IEnumerable<IItemResolver> resolvers,
 254            IEnumerable<IIntroProvider> introProviders,
 255            IEnumerable<IBaseItemComparer> itemComparers,
 256            IEnumerable<ILibraryPostScanTask> postScanTasks)
 257        {
 28258            EntityResolutionIgnoreRules = rules.ToArray();
 28259            EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
 28260            MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
 28261            IntroProviders = introProviders.ToArray();
 28262            Comparers = itemComparers.ToArray();
 28263            PostScanTasks = postScanTasks.ToArray();
 28264        }
 265
 266        /// <summary>
 267        /// Records the configuration values.
 268        /// </summary>
 269        /// <param name="configuration">The configuration.</param>
 270        private void RecordConfigurationValues(ServerConfiguration configuration)
 271        {
 129272            _wizardCompleted = configuration.IsStartupWizardCompleted;
 129273        }
 274
 275        /// <summary>
 276        /// Configurations the updated.
 277        /// </summary>
 278        /// <param name="sender">The sender.</param>
 279        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
 280        private void ConfigurationUpdated(object? sender, EventArgs e)
 281        {
 101282            var config = _configurationManager.Configuration;
 283
 101284            var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
 285
 101286            RecordConfigurationValues(config);
 287
 101288            if (wizardChanged)
 289            {
 16290                _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
 291            }
 101292        }
 293
 294        public void RegisterItem(BaseItem item)
 295        {
 149296            ArgumentNullException.ThrowIfNull(item);
 297
 149298            if (item is IItemByName)
 299            {
 0300                if (item is not MusicArtist)
 301                {
 0302                    return;
 303                }
 304            }
 149305            else if (!item.IsFolder)
 306            {
 0307                if (item is not Video && item is not LiveTvChannel)
 308                {
 0309                    return;
 310                }
 311            }
 312
 149313            _cache.AddOrUpdate(item.Id, item);
 149314        }
 315
 316        public void DeleteItem(BaseItem item, DeleteOptions options)
 317        {
 0318            DeleteItem(item, options, false);
 0319        }
 320
 321        public void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem)
 322        {
 0323            ArgumentNullException.ThrowIfNull(item);
 324
 0325            var parent = item.GetOwner() ?? item.GetParent();
 326
 0327            DeleteItem(item, options, parent, notifyParentItem);
 0328        }
 329
 330        public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem)
 331        {
 2332            ArgumentNullException.ThrowIfNull(item);
 333
 2334            if (item.SourceType == SourceType.Channel)
 335            {
 0336                if (options.DeleteFromExternalProvider)
 337                {
 338                    try
 339                    {
 0340                        BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult();
 0341                    }
 0342                    catch (ArgumentException)
 343                    {
 344                        // channel no longer installed
 0345                    }
 346                }
 347
 0348                options.DeleteFileLocation = false;
 349            }
 350
 2351            if (item is LiveTvProgram)
 352            {
 0353                _logger.LogDebug(
 0354                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0355                    item.GetType().Name,
 0356                    item.Name ?? "Unknown name",
 0357                    item.Path ?? string.Empty,
 0358                    item.Id);
 359            }
 360            else
 361            {
 2362                _logger.LogInformation(
 2363                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 2364                    item.GetType().Name,
 2365                    item.Name ?? "Unknown name",
 2366                    item.Path ?? string.Empty,
 2367                    item.Id);
 368            }
 369
 2370            var children = item.IsFolder
 2371                ? ((Folder)item).GetRecursiveChildren(false)
 2372                : [];
 373
 8374            foreach (var metadataPath in GetMetadataPaths(item, children))
 375            {
 2376                if (!Directory.Exists(metadataPath))
 377                {
 378                    continue;
 379                }
 380
 0381                _logger.LogDebug(
 0382                    "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0383                    item.GetType().Name,
 0384                    item.Name ?? "Unknown name",
 0385                    metadataPath,
 0386                    item.Id);
 387
 388                try
 389                {
 0390                    Directory.Delete(metadataPath, true);
 0391                }
 0392                catch (Exception ex)
 393                {
 0394                    _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0395                }
 396            }
 397
 2398            if ((options.DeleteFileLocation && item.IsFileProtocol) || IsInternalItem(item))
 399            {
 400                // Assume only the first is required
 401                // Add this flag to GetDeletePaths if required in the future
 0402                var isRequiredForDelete = true;
 403
 0404                foreach (var fileSystemInfo in item.GetDeletePaths())
 405                {
 0406                    if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
 407                    {
 408                        try
 409                        {
 0410                            _logger.LogInformation(
 0411                                "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0412                                item.GetType().Name,
 0413                                item.Name ?? "Unknown name",
 0414                                fileSystemInfo.FullName,
 0415                                item.Id);
 416
 0417                            if (fileSystemInfo.IsDirectory)
 418                            {
 0419                                Directory.Delete(fileSystemInfo.FullName, true);
 420                            }
 421                            else
 422                            {
 0423                                File.Delete(fileSystemInfo.FullName);
 424                            }
 0425                        }
 0426                        catch (DirectoryNotFoundException)
 427                        {
 0428                            _logger.LogInformation(
 0429                                "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Pa
 0430                                item.GetType().Name,
 0431                                item.Name ?? "Unknown name",
 0432                                fileSystemInfo.FullName,
 0433                                item.Id);
 0434                        }
 0435                        catch (FileNotFoundException)
 436                        {
 0437                            _logger.LogInformation(
 0438                                "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, 
 0439                                item.GetType().Name,
 0440                                item.Name ?? "Unknown name",
 0441                                fileSystemInfo.FullName,
 0442                                item.Id);
 0443                        }
 0444                        catch (IOException)
 445                        {
 0446                            if (isRequiredForDelete)
 447                            {
 0448                                throw;
 449                            }
 0450                        }
 0451                        catch (UnauthorizedAccessException)
 452                        {
 0453                            if (isRequiredForDelete)
 454                            {
 0455                                throw;
 456                            }
 0457                        }
 458                    }
 459
 0460                    isRequiredForDelete = false;
 461                }
 462            }
 463
 2464            item.SetParent(null);
 465
 2466            _itemRepository.DeleteItem(item.Id);
 2467            _cache.TryRemove(item.Id, out _);
 4468            foreach (var child in children)
 469            {
 0470                _itemRepository.DeleteItem(child.Id);
 0471                _cache.TryRemove(child.Id, out _);
 472            }
 473
 2474            ReportItemRemoved(item, parent);
 2475        }
 476
 477        private bool IsInternalItem(BaseItem item)
 478        {
 2479            if (!item.IsFileProtocol)
 480            {
 0481                return false;
 482            }
 483
 2484            var pathToCheck = item switch
 2485            {
 0486                Genre => _configurationManager.ApplicationPaths.GenrePath,
 0487                MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath,
 0488                MusicGenre => _configurationManager.ApplicationPaths.GenrePath,
 0489                Person => _configurationManager.ApplicationPaths.PeoplePath,
 0490                Studio => _configurationManager.ApplicationPaths.StudioPath,
 0491                Year => _configurationManager.ApplicationPaths.YearPath,
 2492                _ => null
 2493            };
 494
 2495            var itemPath = item.Path;
 2496            if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath))
 497            {
 0498                var cleanPath = _fileSystem.GetValidFilename(itemPath);
 0499                var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck);
 500
 0501                return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal);
 502            }
 503
 2504            return false;
 505        }
 506
 507        private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
 508        {
 2509            var list = GetInternalMetadataPaths(item);
 4510            foreach (var child in children)
 511            {
 0512                list.AddRange(GetInternalMetadataPaths(child));
 513            }
 514
 2515            return list;
 516        }
 517
 518        private List<string> GetInternalMetadataPaths(BaseItem item)
 519        {
 2520            var list = new List<string>
 2521            {
 2522                item.GetInternalMetadataPath()
 2523            };
 524
 2525            if (item is Video video)
 526            {
 527                // Trickplay
 0528                list.Add(_pathManager.GetTrickplayDirectory(video));
 529
 530                // Subtitles and attachments
 0531                foreach (var mediaSource in item.GetMediaSources(false))
 532                {
 0533                    var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id);
 0534                    if (subtitleFolder is not null)
 535                    {
 0536                        list.Add(subtitleFolder);
 537                    }
 538
 0539                    var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0540                    if (attachmentFolder is not null)
 541                    {
 0542                        list.Add(attachmentFolder);
 543                    }
 544                }
 545            }
 546
 2547            return list;
 548        }
 549
 550        /// <summary>
 551        /// Resolves the item.
 552        /// </summary>
 553        /// <param name="args">The args.</param>
 554        /// <param name="resolvers">The resolvers.</param>
 555        /// <returns>BaseItem.</returns>
 556        private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers)
 557        {
 74558            var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r))
 74559                .FirstOrDefault(i => i is not null);
 560
 74561            if (item is not null)
 562            {
 65563                ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
 564            }
 565
 74566            return item;
 567        }
 568
 569        private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver)
 570        {
 571            try
 572            {
 287573                return resolver.ResolvePath(args);
 574            }
 0575            catch (Exception ex)
 576            {
 0577                _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path);
 0578                return null;
 579            }
 287580        }
 581
 582        public Guid GetNewItemId(string key, Type type)
 583        {
 128584            return GetNewItemIdInternal(key, type, false);
 585        }
 586
 587        private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
 588        {
 129589            ArgumentException.ThrowIfNullOrEmpty(key);
 129590            ArgumentNullException.ThrowIfNull(type);
 591
 129592            string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
 129593            if (key.StartsWith(programDataPath, StringComparison.Ordinal))
 594            {
 595                // Try to normalize paths located underneath program-data in an attempt to make them more portable
 112596                key = key.Substring(programDataPath.Length)
 112597                    .TrimStart('/', '\\')
 112598                    .Replace('/', '\\');
 599            }
 600
 129601            if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
 602            {
 1603                key = key.ToLowerInvariant();
 604            }
 605
 129606            key = type.FullName + key;
 607
 129608            return key.GetMD5();
 609        }
 610
 611        public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directorySer
 42612            => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent);
 613
 614        private BaseItem? ResolvePath(
 615            FileSystemMetadata fileInfo,
 616            IDirectoryService directoryService,
 617            IItemResolver[]? resolvers,
 618            Folder? parent = null,
 619            CollectionType? collectionType = null,
 620            LibraryOptions? libraryOptions = null)
 621        {
 74622            ArgumentNullException.ThrowIfNull(fileInfo);
 623
 74624            var fullPath = fileInfo.FullName;
 625
 74626            if (collectionType is null && parent is not null)
 627            {
 15628                collectionType = GetContentTypeOverride(fullPath, true);
 629            }
 630
 74631            var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this)
 74632            {
 74633                Parent = parent,
 74634                FileInfo = fileInfo,
 74635                CollectionType = collectionType,
 74636                LibraryOptions = libraryOptions
 74637            };
 638
 639            // Return null if ignore rules deem that we should do so
 74640            if (IgnoreFile(args.FileInfo, args.Parent))
 641            {
 0642                return null;
 643            }
 644
 645            // Gather child folder and files
 74646            if (args.IsDirectory)
 647            {
 48648                var isPhysicalRoot = args.IsPhysicalRoot;
 649
 650                // When resolving the root, we need it's grandchildren (children of user views)
 48651                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
 652
 653                FileSystemMetadata[] files;
 48654                var isVf = args.IsVf;
 655
 656                try
 657                {
 48658                    files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l
 48659                }
 0660                catch (Exception ex)
 661                {
 0662                    if (parent is not null && parent.IsPhysicalRoot)
 663                    {
 0664                        _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPh
 665
 0666                        files = [];
 667                    }
 668                    else
 669                    {
 0670                        throw;
 671                    }
 0672                }
 673
 674                // Need to remove sub-paths that may have been resolved from shortcuts
 675                // Example: if \\server\movies exists, then strip out \\server\movies\action
 48676                if (isPhysicalRoot)
 677                {
 21678                    files = NormalizeRootPathList(files).ToArray();
 679                }
 680
 48681                args.FileSystemChildren = files;
 682            }
 683
 684            // Filter content based on ignore rules
 74685            if (args.IsDirectory)
 686            {
 48687                var filtered = args.GetActualFileSystemChildren().ToArray();
 48688                args.FileSystemChildren = filtered ?? [];
 689            }
 690
 74691            return ResolveItem(args, resolvers);
 692        }
 693
 694        public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
 95695            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 696
 697        public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
 698        {
 67699            var originalList = paths.ToList();
 700
 67701            var list = originalList.Where(i => i.IsDirectory)
 67702                .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
 67703                .Distinct()
 67704                .ToList();
 705
 67706            var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS
 67707                .ToList();
 708
 134709            foreach (var dupe in dupes)
 710            {
 0711                _logger.LogInformation("Found duplicate path: {0}", dupe);
 712            }
 713
 67714            var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
 67715            newList.AddRange(originalList.Where(i => !i.IsDirectory));
 67716            return newList;
 717        }
 718
 719        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ
 720        {
 41721            return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
 722        }
 723
 724        public IEnumerable<BaseItem> ResolvePaths(
 725            IEnumerable<FileSystemMetadata> files,
 726            IDirectoryService directoryService,
 727            Folder parent,
 728            LibraryOptions libraryOptions,
 729            CollectionType? collectionType,
 730            IItemResolver[] resolvers)
 731        {
 41732            var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
 733
 41734            if (parent is not null)
 735            {
 41736                var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>()
 737
 246738                foreach (var resolver in multiItemResolvers)
 739                {
 82740                    var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
 741
 82742                    if (result?.Items.Count > 0)
 743                    {
 0744                        var items = result.Items;
 0745                        items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryServic
 0746                        items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, reso
 0747                        return items;
 748                    }
 749                }
 750            }
 751
 41752            return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
 0753        }
 754
 755        private IEnumerable<BaseItem> ResolveFileList(
 756            IReadOnlyList<FileSystemMetadata> fileList,
 757            IDirectoryService directoryService,
 758            Folder? parent,
 759            CollectionType? collectionType,
 760            IItemResolver[]? resolvers,
 761            LibraryOptions libraryOptions)
 762        {
 763            // Given that fileList is a list we can save enumerator allocations by indexing
 764            for (var i = 0; i < fileList.Count; i++)
 765            {
 766                var file = fileList[i];
 767                BaseItem? result = null;
 768                try
 769                {
 770                    result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
 771                }
 772                catch (Exception ex)
 773                {
 774                    _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
 775                }
 776
 777                if (result is not null)
 778                {
 779                    yield return result;
 780                }
 781            }
 782        }
 783
 784        /// <summary>
 785        /// Creates the root media folder.
 786        /// </summary>
 787        /// <returns>AggregateFolder.</returns>
 788        /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</except
 789        public AggregateFolder CreateRootFolder()
 790        {
 21791            var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
 792
 21793            var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
 21794                             (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOp
 21795                             .DeepCopy<Folder, AggregateFolder>();
 796
 797            // In case program data folder was moved
 21798            if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
 799            {
 0800                _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
 0801                rootFolder.Path = rootFolderPath;
 802            }
 803
 804            // Add in the plug-in folders
 21805            var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
 806
 21807            var info = Directory.CreateDirectory(path);
 21808            Folder folder = new PlaylistsFolder
 21809            {
 21810                Path = path,
 21811                DateCreated = info.CreationTimeUtc,
 21812                DateModified = info.LastWriteTimeUtc,
 21813            };
 814
 21815            if (folder.Id.IsEmpty())
 816            {
 21817                folder.Id = GetNewItemId(folder.Path, folder.GetType());
 818            }
 819
 21820            var dbItem = GetItemById(folder.Id) as BasePluginFolder;
 821
 21822            if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
 823            {
 0824                folder = dbItem;
 825            }
 826
 21827            if (!folder.ParentId.Equals(rootFolder.Id))
 828            {
 21829                folder.ParentId = rootFolder.Id;
 21830                folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetRe
 831            }
 832
 21833            rootFolder.AddVirtualChild(folder);
 834
 21835            RegisterItem(folder);
 836
 21837            return rootFolder;
 838        }
 839
 840        public Folder GetUserRootFolder()
 841        {
 765842            if (_userRootFolder is null)
 21843            {
 844                lock (_userRootFolderSyncLock)
 845                {
 21846                    if (_userRootFolder is null)
 847                    {
 21848                        var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 849
 21850                        _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
 21851                        Directory.CreateDirectory(userRootPath);
 852
 21853                        var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
 21854                        UserRootFolder? tmpItem = null;
 855                        try
 856                        {
 21857                            tmpItem = GetItemById(newItemId) as UserRootFolder;
 21858                        }
 0859                        catch (Exception ex)
 860                        {
 0861                            _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
 0862                        }
 863
 21864                        if (tmpItem is null)
 865                        {
 21866                            _logger.LogDebug("Creating new userRootFolder with DeepCopy");
 21867                            tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new In
 21868                                        .DeepCopy<Folder, UserRootFolder>();
 869                        }
 870
 871                        // In case program data folder was moved
 21872                        if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
 873                        {
 0874                            _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
 0875                            tmpItem.Path = userRootPath;
 876                        }
 877
 21878                        _userRootFolder = tmpItem;
 21879                        _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
 880                    }
 21881                }
 882            }
 883
 765884            return _userRootFolder;
 885        }
 886
 887        /// <inheritdoc />
 888        public BaseItem? FindByPath(string path, bool? isFolder)
 889        {
 890            // If this returns multiple items it could be tricky figuring out which one is correct.
 891            // In most cases, the newest one will be and the others obsolete but not yet cleaned up
 0892            ArgumentException.ThrowIfNullOrEmpty(path);
 893
 0894            var query = new InternalItemsQuery
 0895            {
 0896                Path = path,
 0897                IsFolder = isFolder,
 0898                OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
 0899                Limit = 1,
 0900                DtoOptions = new DtoOptions(true)
 0901            };
 902
 0903            return GetItemList(query)
 0904                .FirstOrDefault();
 905        }
 906
 907        /// <inheritdoc />
 908        public Person? GetPerson(string name)
 909        {
 1910            var path = Person.GetPath(name);
 1911            var id = GetItemByNameId<Person>(path);
 1912            if (GetItemById(id) is Person item)
 913            {
 0914                return item;
 915            }
 916
 1917            return null;
 918        }
 919
 920        /// <summary>
 921        /// Gets the studio.
 922        /// </summary>
 923        /// <param name="name">The name.</param>
 924        /// <returns>Task{Studio}.</returns>
 925        public Studio GetStudio(string name)
 926        {
 0927            return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
 928        }
 929
 930        public Guid GetStudioId(string name)
 931        {
 0932            return GetItemByNameId<Studio>(Studio.GetPath(name));
 933        }
 934
 935        public Guid GetGenreId(string name)
 936        {
 0937            return GetItemByNameId<Genre>(Genre.GetPath(name));
 938        }
 939
 940        public Guid GetMusicGenreId(string name)
 941        {
 0942            return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
 943        }
 944
 945        /// <summary>
 946        /// Gets the genre.
 947        /// </summary>
 948        /// <param name="name">The name.</param>
 949        /// <returns>Task{Genre}.</returns>
 950        public Genre GetGenre(string name)
 951        {
 0952            return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
 953        }
 954
 955        /// <summary>
 956        /// Gets the music genre.
 957        /// </summary>
 958        /// <param name="name">The name.</param>
 959        /// <returns>Task{MusicGenre}.</returns>
 960        public MusicGenre GetMusicGenre(string name)
 961        {
 0962            return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
 963        }
 964
 965        /// <summary>
 966        /// Gets the year.
 967        /// </summary>
 968        /// <param name="value">The value.</param>
 969        /// <returns>Task{Year}.</returns>
 970        public Year GetYear(int value)
 971        {
 0972            if (value <= 0)
 973            {
 0974                throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
 975            }
 976
 0977            var name = value.ToString(CultureInfo.InvariantCulture);
 978
 0979            return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
 980        }
 981
 982        /// <summary>
 983        /// Gets a Genre.
 984        /// </summary>
 985        /// <param name="name">The name.</param>
 986        /// <returns>Task{Genre}.</returns>
 987        public MusicArtist GetArtist(string name)
 988        {
 0989            return GetArtist(name, new DtoOptions(true));
 990        }
 991
 992        public MusicArtist GetArtist(string name, DtoOptions options)
 993        {
 0994            return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
 995        }
 996
 997        private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
 998            where T : BaseItem, new()
 999        {
 01000            if (typeof(T) == typeof(MusicArtist))
 1001            {
 01002                var existing = GetItemList(new InternalItemsQuery
 01003                {
 01004                    IncludeItemTypes = [BaseItemKind.MusicArtist],
 01005                    Name = name,
 01006                    DtoOptions = options
 01007                }).Cast<MusicArtist>()
 01008                .OrderBy(i => i.IsAccessedByName ? 1 : 0)
 01009                .Cast<T>()
 01010                .FirstOrDefault();
 1011
 01012                if (existing is not null)
 1013                {
 01014                    return existing;
 1015                }
 1016            }
 1017
 01018            var path = getPathFn(name);
 01019            var id = GetItemByNameId<T>(path);
 01020            var item = GetItemById(id) as T;
 01021            if (item is null)
 1022            {
 01023                var info = Directory.CreateDirectory(path);
 01024                item = new T
 01025                {
 01026                    Name = name,
 01027                    Id = id,
 01028                    DateCreated = info.CreationTimeUtc,
 01029                    DateModified = info.LastWriteTimeUtc,
 01030                    Path = path
 01031                };
 1032
 01033                CreateItem(item, null);
 1034            }
 1035
 01036            return item;
 1037        }
 1038
 1039        private Guid GetItemByNameId<T>(string path)
 1040              where T : BaseItem, new()
 1041        {
 11042            var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
 11043            return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
 1044        }
 1045
 1046        /// <inheritdoc />
 1047        public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
 1048        {
 1049            // Ensure the location is available.
 01050            Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
 1051
 01052            return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
 1053        }
 1054
 1055        /// <summary>
 1056        /// Reloads the root media folder.
 1057        /// </summary>
 1058        /// <param name="progress">The progress.</param>
 1059        /// <param name="cancellationToken">The cancellation token.</param>
 1060        /// <returns>Task.</returns>
 1061        public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
 1062        {
 1063            // Just run the scheduled task so that the user can see it
 31064            _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
 1065
 31066            return Task.CompletedTask;
 1067        }
 1068
 1069        /// <summary>
 1070        /// Validates the media library internal.
 1071        /// </summary>
 1072        /// <param name="progress">The progress.</param>
 1073        /// <param name="cancellationToken">The cancellation token.</param>
 1074        /// <returns>Task.</returns>
 1075        public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
 1076        {
 1077            IsScanRunning = true;
 1078            LibraryMonitor.Stop();
 1079
 1080            try
 1081            {
 1082                await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
 1083            }
 1084            finally
 1085            {
 1086                LibraryMonitor.Start();
 1087                IsScanRunning = false;
 1088            }
 1089        }
 1090
 1091        public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
 1092        {
 1093            await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1094
 1095            // Start by just validating the children of the root, but go no further
 1096            await RootFolder.ValidateChildren(
 1097                new Progress<double>(),
 1098                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1099                recursive: false,
 1100                allowRemoveRoot: removeRoot,
 1101                cancellationToken: cancellationToken).ConfigureAwait(false);
 1102
 1103            await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1104
 1105            await GetUserRootFolder().ValidateChildren(
 1106                new Progress<double>(),
 1107                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1108                recursive: false,
 1109                allowRemoveRoot: removeRoot,
 1110                cancellationToken: cancellationToken).ConfigureAwait(false);
 1111
 1112            // Quickly scan CollectionFolders for changes
 1113            foreach (var child in GetUserRootFolder().Children.OfType<Folder>())
 1114            {
 1115                // If the user has somehow deleted the collection directory, remove the metadata from the database.
 1116                if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
 1117                {
 1118                    _itemRepository.DeleteItem(collectionFolder.Id);
 1119                }
 1120                else
 1121                {
 1122                    await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1123                }
 1124            }
 1125        }
 1126
 1127        private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
 1128        {
 1129            _logger.LogInformation("Validating media library");
 1130
 1131            await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
 1132
 1133            var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
 1134
 1135            // Validate the entire media library
 1136            await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem
 1137
 1138            progress.Report(96);
 1139
 1140            innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
 1141
 1142            await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
 1143
 1144            progress.Report(100);
 1145        }
 1146
 1147        /// <summary>
 1148        /// Runs the post scan tasks.
 1149        /// </summary>
 1150        /// <param name="progress">The progress.</param>
 1151        /// <param name="cancellationToken">The cancellation token.</param>
 1152        /// <returns>Task.</returns>
 1153        private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
 1154        {
 1155            var tasks = PostScanTasks.ToList();
 1156
 1157            var numComplete = 0;
 1158            var numTasks = tasks.Count;
 1159
 1160            foreach (var task in tasks)
 1161            {
 1162                // Prevent access to modified closure
 1163                var currentNumComplete = numComplete;
 1164
 1165                var innerProgress = new Progress<double>(pct =>
 1166                {
 1167                    double innerPercent = pct;
 1168                    innerPercent /= 100;
 1169                    innerPercent += currentNumComplete;
 1170
 1171                    innerPercent /= numTasks;
 1172                    innerPercent *= 100;
 1173
 1174                    progress.Report(innerPercent);
 1175                });
 1176
 1177                _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
 1178
 1179                try
 1180                {
 1181                    await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
 1182                }
 1183                catch (OperationCanceledException)
 1184                {
 1185                    _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
 1186                    throw;
 1187                }
 1188                catch (Exception ex)
 1189                {
 1190                    _logger.LogError(ex, "Error running post-scan task");
 1191                }
 1192
 1193                numComplete++;
 1194                double percent = numComplete;
 1195                percent /= numTasks;
 1196                progress.Report(percent * 100);
 1197            }
 1198
 1199            _itemRepository.UpdateInheritedValues();
 1200
 1201            progress.Report(100);
 1202        }
 1203
 1204        /// <summary>
 1205        /// Gets the default view.
 1206        /// </summary>
 1207        /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
 1208        public List<VirtualFolderInfo> GetVirtualFolders()
 1209        {
 231210            return GetVirtualFolders(false);
 1211        }
 1212
 1213        public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
 1214        {
 241215            _logger.LogDebug("Getting topLibraryFolders");
 241216            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 1217
 241218            _logger.LogDebug("Getting refreshQueue");
 241219            var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
 1220
 241221            return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
 241222                .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
 241223                .ToList();
 1224        }
 1225
 1226        private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? r
 1227        {
 11228            var info = new VirtualFolderInfo
 11229            {
 11230                Name = Path.GetFileName(dir),
 11231
 11232                Locations = _fileSystem.GetFilePaths(dir, false)
 11233                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 11234                    .Select(i =>
 11235                    {
 11236                        try
 11237                        {
 11238                            return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
 11239                        }
 11240                        catch (Exception ex)
 11241                        {
 11242                            _logger.LogError(ex, "Error resolving shortcut file {File}", i);
 11243                            return null;
 11244                        }
 11245                    })
 11246                    .Where(i => i is not null)
 11247                    .Order()
 11248                    .ToArray(),
 11249
 11250                CollectionType = GetCollectionType(dir)
 11251            };
 1252
 11253            var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.Ord
 11254            if (libraryFolder is not null)
 1255            {
 11256                var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
 11257                info.ItemId = libraryFolderId;
 11258                if (libraryFolder.HasImage(ImageType.Primary))
 1259                {
 01260                    info.PrimaryImageItemId = libraryFolderId;
 1261                }
 1262
 11263                info.LibraryOptions = GetLibraryOptions(libraryFolder);
 1264
 11265                if (refreshQueue is not null)
 1266                {
 11267                    info.RefreshProgress = libraryFolder.GetRefreshProgress();
 1268
 11269                    info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.
 1270                }
 1271            }
 1272
 11273            return info;
 1274        }
 1275
 1276        private CollectionTypeOptions? GetCollectionType(string path)
 1277        {
 11278            var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
 21279            foreach (ReadOnlySpan<char> file in files)
 1280            {
 01281                if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
 1282                {
 01283                    return res;
 1284                }
 1285            }
 1286
 11287            return null;
 01288        }
 1289
 1290        /// <inheritdoc />
 1291        public BaseItem? GetItemById(Guid id)
 1292        {
 7851293            if (id.IsEmpty())
 1294            {
 01295                throw new ArgumentException("Guid can't be empty", nameof(id));
 1296            }
 1297
 7851298            if (_cache.TryGet(id, out var item))
 1299            {
 5521300                return item;
 1301            }
 1302
 2331303            item = RetrieveItem(id);
 1304
 2331305            if (item is not null)
 1306            {
 01307                RegisterItem(item);
 1308            }
 1309
 2331310            return item;
 1311        }
 1312
 1313        /// <inheritdoc />
 1314        public T? GetItemById<T>(Guid id)
 1315            where T : BaseItem
 1316        {
 231317            var item = GetItemById(id);
 231318            if (item is T typedItem)
 1319            {
 11320                return typedItem;
 1321            }
 1322
 221323            return null;
 1324        }
 1325
 1326        /// <inheritdoc />
 1327        public T? GetItemById<T>(Guid id, Guid userId)
 1328            where T : BaseItem
 1329        {
 11330            var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
 11331            return GetItemById<T>(id, user);
 1332        }
 1333
 1334        /// <inheritdoc />
 1335        public T? GetItemById<T>(Guid id, User? user)
 1336            where T : BaseItem
 1337        {
 211338            var item = GetItemById<T>(id);
 211339            return ItemIsVisible(item, user) ? item : null;
 1340        }
 1341
 1342        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
 1343        {
 941344            if (query.Recursive && !query.ParentId.IsEmpty())
 1345            {
 371346                var parent = GetItemById(query.ParentId);
 371347                if (parent is not null)
 1348                {
 371349                    SetTopParentIdsOrAncestors(query, [parent]);
 1350                }
 1351            }
 1352
 941353            if (query.User is not null)
 1354            {
 11355                AddUserToQuery(query, query.User, allowExternalContent);
 1356            }
 1357
 941358            var itemList = _itemRepository.GetItemList(query);
 941359            var user = query.User;
 941360            if (user is not null)
 1361            {
 11362                return itemList.Where(i => i.IsVisible(user)).ToList();
 1363            }
 1364
 931365            return itemList;
 1366        }
 1367
 1368        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 1369        {
 941370            return GetItemList(query, true);
 1371        }
 1372
 1373        public int GetCount(InternalItemsQuery query)
 1374        {
 01375            if (query.Recursive && !query.ParentId.IsEmpty())
 1376            {
 01377                var parent = GetItemById(query.ParentId);
 01378                if (parent is not null)
 1379                {
 01380                    SetTopParentIdsOrAncestors(query, [parent]);
 1381                }
 1382            }
 1383
 01384            if (query.User is not null)
 1385            {
 01386                AddUserToQuery(query, query.User);
 1387            }
 1388
 01389            return _itemRepository.GetCount(query);
 1390        }
 1391
 1392        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
 1393        {
 01394            SetTopParentIdsOrAncestors(query, parents);
 1395
 01396            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1397            {
 01398                if (query.User is not null)
 1399                {
 01400                    AddUserToQuery(query, query.User);
 1401                }
 1402            }
 1403
 01404            return _itemRepository.GetItemList(query);
 1405        }
 1406
 1407        public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, Coll
 1408        {
 01409            SetTopParentIdsOrAncestors(query, parents);
 1410
 01411            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1412            {
 01413                if (query.User is not null)
 1414                {
 01415                    AddUserToQuery(query, query.User);
 1416                }
 1417            }
 1418
 01419            return _itemRepository.GetLatestItemList(query, collectionType);
 1420        }
 1421
 1422        public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents
 1423        {
 01424            SetTopParentIdsOrAncestors(query, parents);
 1425
 01426            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1427            {
 01428                if (query.User is not null)
 1429                {
 01430                    AddUserToQuery(query, query.User);
 1431                }
 1432            }
 1433
 01434            return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
 1435        }
 1436
 1437        public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
 1438        {
 01439            if (query.User is not null)
 1440            {
 01441                AddUserToQuery(query, query.User);
 1442            }
 1443
 01444            if (query.EnableTotalRecordCount)
 1445            {
 01446                return _itemRepository.GetItems(query);
 1447            }
 1448
 01449            return new QueryResult<BaseItem>(
 01450                query.StartIndex,
 01451                null,
 01452                _itemRepository.GetItemList(query));
 1453        }
 1454
 1455        public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
 1456        {
 111457            if (query.User is not null)
 1458            {
 01459                AddUserToQuery(query, query.User);
 1460            }
 1461
 111462            return _itemRepository.GetItemIdsList(query);
 1463        }
 1464
 1465        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
 1466        {
 01467            if (query.User is not null)
 1468            {
 01469                AddUserToQuery(query, query.User);
 1470            }
 1471
 01472            SetTopParentOrAncestorIds(query);
 01473            return _itemRepository.GetStudios(query);
 1474        }
 1475
 1476        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
 1477        {
 01478            if (query.User is not null)
 1479            {
 01480                AddUserToQuery(query, query.User);
 1481            }
 1482
 01483            SetTopParentOrAncestorIds(query);
 01484            return _itemRepository.GetGenres(query);
 1485        }
 1486
 1487        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
 1488        {
 01489            if (query.User is not null)
 1490            {
 01491                AddUserToQuery(query, query.User);
 1492            }
 1493
 01494            SetTopParentOrAncestorIds(query);
 01495            return _itemRepository.GetMusicGenres(query);
 1496        }
 1497
 1498        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
 1499        {
 01500            if (query.User is not null)
 1501            {
 01502                AddUserToQuery(query, query.User);
 1503            }
 1504
 01505            SetTopParentOrAncestorIds(query);
 01506            return _itemRepository.GetAllArtists(query);
 1507        }
 1508
 1509        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
 1510        {
 01511            if (query.User is not null)
 1512            {
 01513                AddUserToQuery(query, query.User);
 1514            }
 1515
 01516            SetTopParentOrAncestorIds(query);
 01517            return _itemRepository.GetArtists(query);
 1518        }
 1519
 1520        private void SetTopParentOrAncestorIds(InternalItemsQuery query)
 1521        {
 01522            var ancestorIds = query.AncestorIds;
 01523            int len = ancestorIds.Length;
 01524            if (len == 0)
 1525            {
 01526                return;
 1527            }
 1528
 01529            var parents = new BaseItem[len];
 01530            for (int i = 0; i < len; i++)
 1531            {
 01532                parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id:
 01533                if (parents[i] is not (ICollectionFolder or UserView))
 1534                {
 01535                    return;
 1536                }
 1537            }
 1538
 1539            // Optimize by querying against top level views
 01540            query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 01541            query.AncestorIds = [];
 1542
 1543            // Prevent searching in all libraries due to empty filter
 01544            if (query.TopParentIds.Length == 0)
 1545            {
 01546                query.TopParentIds = [Guid.NewGuid()];
 1547            }
 01548        }
 1549
 1550        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
 1551        {
 01552            if (query.User is not null)
 1553            {
 01554                AddUserToQuery(query, query.User);
 1555            }
 1556
 01557            SetTopParentOrAncestorIds(query);
 01558            return _itemRepository.GetAlbumArtists(query);
 1559        }
 1560
 1561        public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
 1562        {
 141563            if (query.Recursive && !query.ParentId.IsEmpty())
 1564            {
 131565                var parent = GetItemById(query.ParentId);
 131566                if (parent is not null)
 1567                {
 131568                    SetTopParentIdsOrAncestors(query, [parent]);
 1569                }
 1570            }
 1571
 141572            if (query.User is not null)
 1573            {
 11574                AddUserToQuery(query, query.User);
 1575            }
 1576
 141577            if (query.EnableTotalRecordCount)
 1578            {
 11579                return _itemRepository.GetItems(query);
 1580            }
 1581
 131582            return new QueryResult<BaseItem>(
 131583                query.StartIndex,
 131584                null,
 131585                _itemRepository.GetItemList(query));
 1586        }
 1587
 1588        private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
 1589        {
 501590            if (parents.All(i => i is ICollectionFolder || i is UserView))
 1591            {
 1592                // Optimize by querying against top level views
 131593                query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 1594
 1595                // Prevent searching in all libraries due to empty filter
 131596                if (query.TopParentIds.Length == 0)
 1597                {
 131598                    query.TopParentIds = [Guid.NewGuid()];
 1599                }
 1600            }
 1601            else
 1602            {
 1603                // We need to be able to query from any arbitrary ancestor up the tree
 371604                query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
 1605
 1606                // Prevent searching in all libraries due to empty filter
 371607                if (query.AncestorIds.Length == 0)
 1608                {
 01609                    query.AncestorIds = [Guid.NewGuid()];
 1610                }
 1611            }
 1612
 501613            query.Parent = null;
 501614        }
 1615
 1616        private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
 1617        {
 21618            if (query.AncestorIds.Length == 0 &&
 21619                query.ParentId.IsEmpty() &&
 21620                query.ChannelIds.Count == 0 &&
 21621                query.TopParentIds.Length == 0 &&
 21622                string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
 21623                string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
 21624                query.ItemIds.Length == 0)
 1625            {
 11626                var userViews = UserViewManager.GetUserViews(new UserViewQuery
 11627                {
 11628                    User = user,
 11629                    IncludeHidden = true,
 11630                    IncludeExternalContent = allowExternalContent
 11631                });
 1632
 11633                query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
 1634
 1635                // Prevent searching in all libraries due to empty filter
 11636                if (query.TopParentIds.Length == 0)
 1637                {
 11638                    query.TopParentIds = [Guid.NewGuid()];
 1639                }
 1640            }
 21641        }
 1642
 1643        private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
 1644        {
 131645            if (item is UserView view)
 1646            {
 01647                if (view.ViewType == CollectionType.livetv)
 1648                {
 01649                    return [view.Id];
 1650                }
 1651
 1652                // Translate view into folders
 01653                if (!view.DisplayParentId.IsEmpty())
 1654                {
 01655                    var displayParent = GetItemById(view.DisplayParentId);
 01656                    if (displayParent is not null)
 1657                    {
 01658                        return GetTopParentIdsForQuery(displayParent, user);
 1659                    }
 1660
 01661                    return [];
 1662                }
 1663
 01664                if (!view.ParentId.IsEmpty())
 1665                {
 01666                    var displayParent = GetItemById(view.ParentId);
 01667                    if (displayParent is not null)
 1668                    {
 01669                        return GetTopParentIdsForQuery(displayParent, user);
 1670                    }
 1671
 01672                    return [];
 1673                }
 1674
 1675                // Handle grouping
 01676                if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.V
 01677                    && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
 1678                {
 01679                    return GetUserRootFolder()
 01680                        .GetChildren(user, true)
 01681                        .OfType<CollectionFolder>()
 01682                        .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
 01683                        .Where(i => user.IsFolderGrouped(i.Id))
 01684                        .SelectMany(i => GetTopParentIdsForQuery(i, user));
 1685                }
 1686
 01687                return [];
 1688            }
 1689
 131690            if (item is CollectionFolder collectionFolder)
 1691            {
 131692                return collectionFolder.PhysicalFolderIds;
 1693            }
 1694
 01695            var topParent = item.GetTopParent();
 01696            if (topParent is not null)
 1697            {
 01698                return [topParent.Id];
 1699            }
 1700
 01701            return [];
 1702        }
 1703
 1704        /// <summary>
 1705        /// Gets the intros.
 1706        /// </summary>
 1707        /// <param name="item">The item.</param>
 1708        /// <param name="user">The user.</param>
 1709        /// <returns>IEnumerable{System.String}.</returns>
 1710        public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
 1711        {
 1712            if (IntroProviders.Length == 0)
 1713            {
 1714                return [];
 1715            }
 1716
 1717            var tasks = IntroProviders
 1718                .Select(i => GetIntros(i, item, user));
 1719
 1720            var items = await Task.WhenAll(tasks).ConfigureAwait(false);
 1721
 1722            return items
 1723                .SelectMany(i => i)
 1724                .Select(ResolveIntro)
 1725                .Where(i => i is not null)!; // null values got filtered out
 1726        }
 1727
 1728        /// <summary>
 1729        /// Gets the intros.
 1730        /// </summary>
 1731        /// <param name="provider">The provider.</param>
 1732        /// <param name="item">The item.</param>
 1733        /// <param name="user">The user.</param>
 1734        /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
 1735        private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
 1736        {
 1737            try
 1738            {
 1739                return await provider.GetIntros(item, user).ConfigureAwait(false);
 1740            }
 1741            catch (Exception ex)
 1742            {
 1743                _logger.LogError(ex, "Error getting intros");
 1744
 1745                return [];
 1746            }
 1747        }
 1748
 1749        /// <summary>
 1750        /// Resolves the intro.
 1751        /// </summary>
 1752        /// <param name="info">The info.</param>
 1753        /// <returns>Video.</returns>
 1754        private Video? ResolveIntro(IntroInfo info)
 1755        {
 01756            Video? video = null;
 1757
 01758            if (info.ItemId.HasValue)
 1759            {
 1760                // Get an existing item by Id
 01761                video = GetItemById(info.ItemId.Value) as Video;
 1762
 01763                if (video is null)
 1764                {
 01765                    _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
 1766                }
 1767            }
 01768            else if (!string.IsNullOrEmpty(info.Path))
 1769            {
 1770                try
 1771                {
 1772                    // Try to resolve the path into a video
 01773                    video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
 1774
 01775                    if (video is null)
 1776                    {
 01777                        _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
 1778                    }
 1779                    else
 1780                    {
 1781                        // Pull the saved db item that will include metadata
 01782                        var dbItem = GetItemById(video.Id) as Video;
 1783
 01784                        if (dbItem is not null)
 1785                        {
 01786                            video = dbItem;
 1787                        }
 1788                        else
 1789                        {
 01790                            return null;
 1791                        }
 1792                    }
 01793                }
 01794                catch (Exception ex)
 1795                {
 01796                    _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
 01797                }
 1798            }
 1799            else
 1800            {
 01801                _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
 1802            }
 1803
 01804            return video;
 01805        }
 1806
 1807        /// <inheritdoc />
 1808        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortO
 1809        {
 11810            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1811
 41812            foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
 1813            {
 11814                if (orderBy is RandomComparer)
 1815                {
 01816                    var randomItems = items.ToArray();
 01817                    Random.Shared.Shuffle(randomItems);
 01818                    items = randomItems;
 1819                    // Items are no longer ordered at this point, so set orderedItems back to null
 01820                    orderedItems = null;
 1821                }
 11822                else if (orderedItems is null)
 1823                {
 11824                    orderedItems = sortOrder == SortOrder.Descending
 11825                        ? items.OrderByDescending(i => i, orderBy)
 11826                        : items.OrderBy(i => i, orderBy);
 1827                }
 1828                else
 1829                {
 01830                    orderedItems = sortOrder == SortOrder.Descending
 01831                        ? orderedItems!.ThenByDescending(i => i, orderBy)
 01832                        : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
 1833                }
 1834            }
 1835
 11836            return orderedItems ?? items;
 1837        }
 1838
 1839        /// <inheritdoc />
 1840        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, Sort
 1841        {
 01842            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1843
 01844            foreach (var (name, sortOrder) in orderBy)
 1845            {
 01846                var comparer = GetComparer(name, user);
 01847                if (comparer is null)
 1848                {
 1849                    continue;
 1850                }
 1851
 01852                if (comparer is RandomComparer)
 1853                {
 01854                    var randomItems = items.ToArray();
 01855                    Random.Shared.Shuffle(randomItems);
 01856                    items = randomItems;
 1857                    // Items are no longer ordered at this point, so set orderedItems back to null
 01858                    orderedItems = null;
 1859                }
 01860                else if (orderedItems is null)
 1861                {
 01862                    orderedItems = sortOrder == SortOrder.Descending
 01863                        ? items.OrderByDescending(i => i, comparer)
 01864                        : items.OrderBy(i => i, comparer);
 1865                }
 1866                else
 1867                {
 01868                    orderedItems = sortOrder == SortOrder.Descending
 01869                        ? orderedItems!.ThenByDescending(i => i, comparer)
 01870                        : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
 1871                }
 1872            }
 1873
 01874            return orderedItems ?? items;
 1875        }
 1876
 1877        /// <summary>
 1878        /// Gets the comparer.
 1879        /// </summary>
 1880        /// <param name="name">The name.</param>
 1881        /// <param name="user">The user.</param>
 1882        /// <returns>IBaseItemComparer.</returns>
 1883        private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
 1884        {
 11885            var comparer = Comparers.FirstOrDefault(c => name == c.Type);
 1886
 1887            // If it requires a user, create a new one, and assign the user
 11888            if (comparer is IUserBaseItemComparer)
 1889            {
 01890                var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null fo
 1891
 01892                userComparer.User = user;
 01893                userComparer.UserManager = _userManager;
 01894                userComparer.UserDataManager = _userDataManager;
 1895
 01896                return userComparer;
 1897            }
 1898
 11899            return comparer;
 1900        }
 1901
 1902        /// <inheritdoc />
 1903        public void CreateItem(BaseItem item, BaseItem? parent)
 1904        {
 01905            CreateItems([item], parent, CancellationToken.None);
 01906        }
 1907
 1908        /// <inheritdoc />
 1909        public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
 1910        {
 21911            _itemRepository.SaveItems(items, cancellationToken);
 1912
 81913            foreach (var item in items)
 1914            {
 21915                RegisterItem(item);
 1916            }
 1917
 21918            if (ItemAdded is not null)
 1919            {
 81920                foreach (var item in items)
 1921                {
 1922                    // With the live tv guide this just creates too much noise
 21923                    if (item.SourceType != SourceType.Library)
 1924                    {
 1925                        continue;
 1926                    }
 1927
 1928                    try
 1929                    {
 21930                        ItemAdded(
 21931                            this,
 21932                            new ItemChangeEventArgs
 21933                            {
 21934                                Item = item,
 21935                                Parent = parent ?? item.GetParent()
 21936                            });
 21937                    }
 01938                    catch (Exception ex)
 1939                    {
 01940                        _logger.LogError(ex, "Error in ItemAdded event handler");
 01941                    }
 1942                }
 1943            }
 21944        }
 1945
 1946        private bool ImageNeedsRefresh(ItemImageInfo image)
 1947        {
 01948            if (image.Path is not null && image.IsLocalFile)
 1949            {
 01950                if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
 1951                {
 01952                    return true;
 1953                }
 1954
 1955                try
 1956                {
 01957                    return _fileSystem.GetLastWriteTimeUtc(image.Path) != image.DateModified;
 1958                }
 01959                catch (Exception ex)
 1960                {
 01961                    _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
 01962                    return false;
 1963                }
 1964            }
 1965
 01966            return image.Path is not null && !image.IsLocalFile;
 01967        }
 1968
 1969        /// <inheritdoc />
 1970        public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
 1971        {
 1972            ArgumentNullException.ThrowIfNull(item);
 1973
 1974            var outdated = forceUpdate
 1975                ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
 1976                : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
 1977            // Skip image processing if current or live tv source
 1978            if (outdated.Length == 0 || item.SourceType != SourceType.Library)
 1979            {
 1980                RegisterItem(item);
 1981                return;
 1982            }
 1983
 1984            foreach (var img in outdated)
 1985            {
 1986                var image = img;
 1987                if (!img.IsLocalFile)
 1988                {
 1989                    try
 1990                    {
 1991                        var index = item.GetImageIndex(img);
 1992                        image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
 1993                    }
 1994                    catch (ArgumentException)
 1995                    {
 1996                        _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
 1997                        continue;
 1998                    }
 1999                    catch (Exception ex) when (ex is InvalidOperationException or IOException)
 2000                    {
 2001                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
 2002                        continue;
 2003                    }
 2004                    catch (HttpRequestException ex)
 2005                    {
 2006                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", im
 2007                        continue;
 2008                    }
 2009                }
 2010
 2011                ImageDimensions size;
 2012                try
 2013                {
 2014                    size = _imageProcessor.GetImageDimensions(item, image);
 2015                    image.Width = size.Width;
 2016                    image.Height = size.Height;
 2017                }
 2018                catch (Exception ex)
 2019                {
 2020                    _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
 2021                    size = default;
 2022                    image.Width = 0;
 2023                    image.Height = 0;
 2024                }
 2025
 2026                try
 2027                {
 2028                    image.BlurHash = _imageProcessor.GetImageBlurHash(image.Path, size);
 2029                }
 2030                catch (Exception ex)
 2031                {
 2032                    _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
 2033                    image.BlurHash = string.Empty;
 2034                }
 2035
 2036                try
 2037                {
 2038                    image.DateModified = _fileSystem.GetLastWriteTimeUtc(image.Path);
 2039                }
 2040                catch (Exception ex)
 2041                {
 2042                    _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
 2043                }
 2044            }
 2045
 2046            _itemRepository.SaveImages(item);
 2047            RegisterItem(item);
 2048        }
 2049
 2050        /// <inheritdoc />
 2051        public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, 
 2052        {
 2053            _itemRepository.SaveItems(items, cancellationToken);
 2054
 2055            foreach (var item in items)
 2056            {
 2057                await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
 2058            }
 2059
 2060            if (ItemUpdated is not null)
 2061            {
 2062                foreach (var item in items)
 2063                {
 2064                    // With the live tv guide this just creates too much noise
 2065                    if (item.SourceType != SourceType.Library)
 2066                    {
 2067                        continue;
 2068                    }
 2069
 2070                    try
 2071                    {
 2072                        ItemUpdated(
 2073                            this,
 2074                            new ItemChangeEventArgs
 2075                            {
 2076                                Item = item,
 2077                                Parent = parent,
 2078                                UpdateReason = updateReason
 2079                            });
 2080                    }
 2081                    catch (Exception ex)
 2082                    {
 2083                        _logger.LogError(ex, "Error in ItemUpdated event handler");
 2084                    }
 2085                }
 2086            }
 2087        }
 2088
 2089        /// <inheritdoc />
 2090        public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance
 872091            => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
 2092
 2093        public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
 2094        {
 2095            if (item.IsFileProtocol)
 2096            {
 2097                await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
 2098            }
 2099
 2100            item.DateLastSaved = DateTime.UtcNow;
 2101
 2102            await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
 2103        }
 2104
 2105        /// <summary>
 2106        /// Reports the item removed.
 2107        /// </summary>
 2108        /// <param name="item">The item.</param>
 2109        /// <param name="parent">The parent item.</param>
 2110        public void ReportItemRemoved(BaseItem item, BaseItem parent)
 2111        {
 22112            if (ItemRemoved is not null)
 2113            {
 2114                try
 2115                {
 22116                    ItemRemoved(
 22117                        this,
 22118                        new ItemChangeEventArgs
 22119                        {
 22120                            Item = item,
 22121                            Parent = parent
 22122                        });
 22123                }
 02124                catch (Exception ex)
 2125                {
 02126                    _logger.LogError(ex, "Error in ItemRemoved event handler");
 02127                }
 2128            }
 22129        }
 2130
 2131        /// <summary>
 2132        /// Retrieves the item.
 2133        /// </summary>
 2134        /// <param name="id">The id.</param>
 2135        /// <returns>BaseItem.</returns>
 2136        public BaseItem RetrieveItem(Guid id)
 2137        {
 2332138            return _itemRepository.RetrieveItem(id);
 2139        }
 2140
 2141        public List<Folder> GetCollectionFolders(BaseItem item)
 2142        {
 6382143            return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
 2144        }
 2145
 2146        public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2147        {
 6802148            while (item is not null)
 2149            {
 6802150                var parent = item.GetParent();
 2151
 6802152                if (parent is AggregateFolder)
 2153                {
 2154                    break;
 2155                }
 2156
 6562157                if (parent is null)
 2158                {
 6142159                    var owner = item.GetOwner();
 2160
 6142161                    if (owner is null)
 2162                    {
 2163                        break;
 2164                    }
 2165
 02166                    item = owner;
 2167                }
 2168                else
 2169                {
 422170                    item = parent;
 2171                }
 2172            }
 2173
 6382174            if (item is null)
 2175            {
 02176                return new List<Folder>();
 2177            }
 2178
 6382179            return GetCollectionFoldersInternal(item, allUserRootChildren);
 2180        }
 2181
 2182        private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2183        {
 6382184            return allUserRootChildren
 6382185                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 6382186                .ToList();
 2187        }
 2188
 2189        public LibraryOptions GetLibraryOptions(BaseItem item)
 2190        {
 4082191            if (item is CollectionFolder collectionFolder)
 2192            {
 592193                return collectionFolder.GetLibraryOptions();
 2194            }
 2195
 2196            // List.Find is more performant than FirstOrDefault due to enumerator allocation
 3492197            return GetCollectionFolders(item)
 3492198                .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
 3492199                ? collectionFolder2.GetLibraryOptions()
 3492200                : new LibraryOptions();
 2201        }
 2202
 2203        public CollectionType? GetContentType(BaseItem item)
 2204        {
 412205            var configuredContentType = GetConfiguredContentType(item, false);
 412206            if (configuredContentType is not null)
 2207            {
 02208                return configuredContentType;
 2209            }
 2210
 412211            configuredContentType = GetConfiguredContentType(item, true);
 412212            if (configuredContentType is not null)
 2213            {
 02214                return configuredContentType;
 2215            }
 2216
 412217            return GetInheritedContentType(item);
 2218        }
 2219
 2220        public CollectionType? GetInheritedContentType(BaseItem item)
 2221        {
 412222            var type = GetTopFolderContentType(item);
 2223
 412224            if (type is not null)
 2225            {
 02226                return type;
 2227            }
 2228
 412229            return item.GetParents()
 412230                .Select(GetConfiguredContentType)
 412231                .LastOrDefault(i => i is not null);
 2232        }
 2233
 2234        public CollectionType? GetConfiguredContentType(BaseItem item)
 2235        {
 02236            return GetConfiguredContentType(item, false);
 2237        }
 2238
 2239        public CollectionType? GetConfiguredContentType(string path)
 2240        {
 02241            return GetContentTypeOverride(path, false);
 2242        }
 2243
 2244        public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
 2245        {
 822246            if (item is ICollectionFolder collectionFolder)
 2247            {
 02248                return collectionFolder.CollectionType;
 2249            }
 2250
 822251            return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
 2252        }
 2253
 2254        private CollectionType? GetContentTypeOverride(string path, bool inherit)
 2255        {
 972256            var nameValuePair = _configurationManager.Configuration.ContentTypes
 972257                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
 972258                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
 972259                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
 972260            if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
 2261            {
 02262                return collectionType;
 2263            }
 2264
 972265            return null;
 2266        }
 2267
 2268        private CollectionType? GetTopFolderContentType(BaseItem item)
 2269        {
 412270            if (item is null)
 2271            {
 02272                return null;
 2273            }
 2274
 412275            while (!item.ParentId.IsEmpty())
 2276            {
 02277                var parent = item.GetParent();
 02278                if (parent is null || parent is AggregateFolder)
 2279                {
 2280                    break;
 2281                }
 2282
 02283                item = parent;
 2284            }
 2285
 412286            return GetUserRootFolder().Children
 412287                .OfType<ICollectionFolder>()
 412288                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 412289                .Select(i => i.CollectionType)
 412290                .FirstOrDefault(i => i is not null);
 2291        }
 2292
 2293        public UserView GetNamedView(
 2294            User user,
 2295            string name,
 2296            CollectionType? viewType,
 2297            string sortName)
 2298        {
 02299            return GetNamedView(user, name, Guid.Empty, viewType, sortName);
 2300        }
 2301
 2302        public UserView GetNamedView(
 2303            string name,
 2304            CollectionType viewType,
 2305            string sortName)
 2306        {
 02307            var path = Path.Combine(
 02308                _configurationManager.ApplicationPaths.InternalMetadataPath,
 02309                "views",
 02310                _fileSystem.GetValidFilename(viewType.ToString()));
 2311
 02312            var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 2313
 02314            var item = GetItemById(id) as UserView;
 2315
 02316            var refresh = false;
 2317
 02318            if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
 2319            {
 02320                var info = Directory.CreateDirectory(path);
 02321                item = new UserView
 02322                {
 02323                    Path = path,
 02324                    Id = id,
 02325                    DateCreated = info.CreationTimeUtc,
 02326                    DateModified = info.LastWriteTimeUtc,
 02327                    Name = name,
 02328                    ViewType = viewType,
 02329                    ForcedSortName = sortName
 02330                };
 2331
 02332                CreateItem(item, null);
 2333
 02334                refresh = true;
 2335            }
 2336
 02337            if (refresh)
 2338            {
 02339                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu
 02340                ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref
 2341            }
 2342
 02343            return item;
 2344        }
 2345
 2346        public UserView GetNamedView(
 2347            User user,
 2348            string name,
 2349            Guid parentId,
 2350            CollectionType? viewType,
 2351            string sortName)
 2352        {
 02353            var parentIdString = parentId.IsEmpty()
 02354                ? null
 02355                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02356            var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin
 2357
 02358            var id = GetNewItemId(idValues, typeof(UserView));
 2359
 02360            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2361
 02362            var item = GetItemById(id) as UserView;
 2363
 02364            var isNew = false;
 2365
 02366            if (item is null)
 2367            {
 02368                var info = Directory.CreateDirectory(path);
 02369                item = new UserView
 02370                {
 02371                    Path = path,
 02372                    Id = id,
 02373                    DateCreated = info.CreationTimeUtc,
 02374                    DateModified = info.LastWriteTimeUtc,
 02375                    Name = name,
 02376                    ViewType = viewType,
 02377                    ForcedSortName = sortName,
 02378                    UserId = user.Id,
 02379                    DisplayParentId = parentId
 02380                };
 2381
 02382                CreateItem(item, null);
 2383
 02384                isNew = true;
 2385            }
 2386
 02387            var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
 2388
 02389            if (!refresh && !item.DisplayParentId.IsEmpty())
 2390            {
 02391                var displayParent = GetItemById(item.DisplayParentId);
 02392                refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
 2393            }
 2394
 02395            if (refresh)
 2396            {
 02397                ProviderManager.QueueRefresh(
 02398                    item.Id,
 02399                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02400                    {
 02401                        // Need to force save to increment DateLastSaved
 02402                        ForceSave = true
 02403                    },
 02404                    RefreshPriority.Normal);
 2405            }
 2406
 02407            return item;
 2408        }
 2409
 2410        public UserView GetShadowView(
 2411            BaseItem parent,
 2412            CollectionType? viewType,
 2413            string sortName)
 2414        {
 02415            ArgumentNullException.ThrowIfNull(parent);
 2416
 02417            var name = parent.Name;
 02418            var parentId = parent.Id;
 2419
 02420            var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
 2421
 02422            var id = GetNewItemId(idValues, typeof(UserView));
 2423
 02424            var path = parent.Path;
 2425
 02426            var item = GetItemById(id) as UserView;
 2427
 02428            var isNew = false;
 2429
 02430            if (item is null)
 2431            {
 02432                var info = Directory.CreateDirectory(path);
 02433                item = new UserView
 02434                {
 02435                    Path = path,
 02436                    Id = id,
 02437                    DateCreated = info.CreationTimeUtc,
 02438                    DateModified = info.LastWriteTimeUtc,
 02439                    Name = name,
 02440                    ViewType = viewType,
 02441                    ForcedSortName = sortName,
 02442                    DisplayParentId = parentId
 02443                };
 2444
 02445                CreateItem(item, null);
 2446
 02447                isNew = true;
 2448            }
 2449
 02450            var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
 2451
 02452            if (!refresh && !item.DisplayParentId.IsEmpty())
 2453            {
 02454                var displayParent = GetItemById(item.DisplayParentId);
 02455                refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
 2456            }
 2457
 02458            if (refresh)
 2459            {
 02460                ProviderManager.QueueRefresh(
 02461                    item.Id,
 02462                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02463                    {
 02464                        // Need to force save to increment DateLastSaved
 02465                        ForceSave = true
 02466                    },
 02467                    RefreshPriority.Normal);
 2468            }
 2469
 02470            return item;
 2471        }
 2472
 2473        public UserView GetNamedView(
 2474            string name,
 2475            Guid parentId,
 2476            CollectionType? viewType,
 2477            string sortName,
 2478            string uniqueId)
 2479        {
 02480            ArgumentException.ThrowIfNullOrEmpty(name);
 2481
 02482            var parentIdString = parentId.IsEmpty()
 02483                ? null
 02484                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02485            var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E
 02486            if (!string.IsNullOrEmpty(uniqueId))
 2487            {
 02488                idValues += uniqueId;
 2489            }
 2490
 02491            var id = GetNewItemId(idValues, typeof(UserView));
 2492
 02493            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2494
 02495            var item = GetItemById(id) as UserView;
 2496
 02497            var isNew = false;
 2498
 02499            if (item is null)
 2500            {
 02501                var info = Directory.CreateDirectory(path);
 02502                item = new UserView
 02503                {
 02504                    Path = path,
 02505                    Id = id,
 02506                    DateCreated = info.CreationTimeUtc,
 02507                    DateModified = info.LastWriteTimeUtc,
 02508                    Name = name,
 02509                    ViewType = viewType,
 02510                    ForcedSortName = sortName,
 02511                    DisplayParentId = parentId
 02512                };
 2513
 02514                CreateItem(item, null);
 2515
 02516                isNew = true;
 2517            }
 2518
 02519            if (viewType != item.ViewType)
 2520            {
 02521                item.ViewType = viewType;
 02522                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult
 2523            }
 2524
 02525            var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
 2526
 02527            if (!refresh && !item.DisplayParentId.IsEmpty())
 2528            {
 02529                var displayParent = GetItemById(item.DisplayParentId);
 02530                refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
 2531            }
 2532
 02533            if (refresh)
 2534            {
 02535                ProviderManager.QueueRefresh(
 02536                    item.Id,
 02537                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02538                    {
 02539                        // Need to force save to increment DateLastSaved
 02540                        ForceSave = true
 02541                    },
 02542                    RefreshPriority.Normal);
 2543            }
 2544
 02545            return item;
 2546        }
 2547
 2548        public BaseItem GetParentItem(Guid? parentId, Guid? userId)
 2549        {
 32550            if (parentId.HasValue)
 2551            {
 02552                return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}"
 2553            }
 2554
 32555            if (!userId.IsNullOrEmpty())
 2556            {
 32557                return GetUserRootFolder();
 2558            }
 2559
 02560            return RootFolder;
 2561        }
 2562
 2563        /// <inheritdoc />
 2564        public void QueueLibraryScan()
 2565        {
 02566            _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
 02567        }
 2568
 2569        /// <inheritdoc />
 2570        public int? GetSeasonNumberFromPath(string path, Guid? parentId)
 2571        {
 02572            var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
 02573            return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
 2574        }
 2575
 2576        /// <inheritdoc />
 2577        public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
 2578        {
 02579            var series = episode.Series;
 02580            bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis
 02581            if (!isAbsoluteNaming.Value)
 2582            {
 2583                // In other words, no filter applied
 02584                isAbsoluteNaming = null;
 2585            }
 2586
 02587            var resolver = new EpisodeResolver(_namingOptions);
 2588
 02589            var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
 2590
 02591            EpisodeInfo? episodeInfo = null;
 02592            if (episode.IsFileProtocol)
 2593            {
 02594                episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
 2595                // Resolve from parent folder if it's not the Season folder
 02596                var parent = episode.GetParent();
 02597                if (episodeInfo is null && parent.GetType() == typeof(Folder))
 2598                {
 02599                    episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
 02600                    if (episodeInfo is not null)
 2601                    {
 2602                        // add the container
 02603                        episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
 2604                    }
 2605                }
 2606            }
 2607
 02608            var changed = false;
 02609            if (episodeInfo is null)
 2610            {
 02611                return changed;
 2612            }
 2613
 02614            if (episodeInfo.IsByDate)
 2615            {
 02616                if (episode.IndexNumber.HasValue)
 2617                {
 02618                    episode.IndexNumber = null;
 02619                    changed = true;
 2620                }
 2621
 02622                if (episode.IndexNumberEnd.HasValue)
 2623                {
 02624                    episode.IndexNumberEnd = null;
 02625                    changed = true;
 2626                }
 2627
 02628                if (!episode.PremiereDate.HasValue)
 2629                {
 02630                    if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
 2631                    {
 02632                        episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo
 2633                    }
 2634
 02635                    if (episode.PremiereDate.HasValue)
 2636                    {
 02637                        changed = true;
 2638                    }
 2639                }
 2640
 02641                if (!episode.ProductionYear.HasValue)
 2642                {
 02643                    episode.ProductionYear = episodeInfo.Year;
 2644
 02645                    if (episode.ProductionYear.HasValue)
 2646                    {
 02647                        changed = true;
 2648                    }
 2649                }
 2650            }
 2651            else
 2652            {
 02653                if (!episode.IndexNumber.HasValue || forceRefresh)
 2654                {
 02655                    if (episode.IndexNumber != episodeInfo.EpisodeNumber)
 2656                    {
 02657                        changed = true;
 2658                    }
 2659
 02660                    episode.IndexNumber = episodeInfo.EpisodeNumber;
 2661                }
 2662
 02663                if (!episode.IndexNumberEnd.HasValue || forceRefresh)
 2664                {
 02665                    if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
 2666                    {
 02667                        changed = true;
 2668                    }
 2669
 02670                    episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
 2671                }
 2672
 02673                if (!episode.ParentIndexNumber.HasValue || forceRefresh)
 2674                {
 02675                    if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
 2676                    {
 02677                        changed = true;
 2678                    }
 2679
 02680                    episode.ParentIndexNumber = episodeInfo.SeasonNumber;
 2681                }
 2682            }
 2683
 02684            if (!episode.ParentIndexNumber.HasValue)
 2685            {
 02686                var season = episode.Season;
 2687
 02688                if (season is not null)
 2689                {
 02690                    episode.ParentIndexNumber = season.IndexNumber;
 2691                }
 2692
 02693                if (episode.ParentIndexNumber.HasValue)
 2694                {
 02695                    changed = true;
 2696                }
 2697            }
 2698
 02699            return changed;
 2700        }
 2701
 2702        public ItemLookupInfo ParseName(string name)
 2703        {
 02704            var namingOptions = _namingOptions;
 02705            var result = VideoResolver.CleanDateTime(name, namingOptions);
 2706
 02707            return new ItemLookupInfo
 02708            {
 02709                Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name
 02710                Year = result.Year
 02711            };
 2712        }
 2713
 2714        public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID
 2715        {
 2716            // Apply .ignore rules
 2717            var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
 2718            var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co
 2719            if (ownerVideoInfo is null)
 2720            {
 2721                yield break;
 2722            }
 2723
 2724            var count = filtered.Count;
 2725            for (var i = 0; i < count; i++)
 2726            {
 2727                var current = filtered[i];
 2728                if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
 2729                {
 2730                    var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
 2731                    var filesInSubFolderList = filesInSubFolder.ToList();
 2732
 2733                    bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
 2734
 2735                    foreach (var file in filesInSubFolderList)
 2736                    {
 2737                        if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
 2738                        {
 2739                            continue;
 2740                        }
 2741
 2742                        var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
 2743                        if (extra is not null)
 2744                        {
 2745                            yield return extra;
 2746                        }
 2747                    }
 2748                }
 2749                else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo
 2750                {
 2751                    var extra = GetExtra(current, extraType.Value, false);
 2752                    if (extra is not null)
 2753                    {
 2754                        yield return extra;
 2755                    }
 2756                }
 2757            }
 2758
 2759            BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
 2760            {
 2761                var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso
 2762                if (extra is not Video && extra is not Audio)
 2763                {
 2764                    return null;
 2765                }
 2766
 2767                // Try to retrieve it from the db. If we don't find it, use the resolved version
 2768                var itemById = GetItemById(extra.Id);
 2769                if (itemById is not null)
 2770                {
 2771                    extra = itemById;
 2772                }
 2773
 2774                // Only update extra type if it is more specific then the currently known extra type
 2775                if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
 2776                {
 2777                    extra.ExtraType = extraType;
 2778                }
 2779
 2780                extra.ParentId = Guid.Empty;
 2781                extra.OwnerId = owner.Id;
 2782                extra.IsInMixedFolder = isInMixedFolder;
 2783                return extra;
 2784            }
 2785        }
 2786
 2787        public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
 2788        {
 122789            foreach (var map in _configurationManager.Configuration.PathSubstitutions)
 2790            {
 02791                if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
 2792                {
 02793                    return newPath;
 2794                }
 2795            }
 2796
 62797            return path;
 2798        }
 2799
 2800        public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
 2801        {
 02802            return _peopleRepository.GetPeople(query);
 2803        }
 2804
 2805        public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
 2806        {
 62807            if (item.SupportsPeople)
 2808            {
 02809                var people = GetPeople(new InternalPeopleQuery
 02810                {
 02811                    ItemId = item.Id
 02812                });
 2813
 02814                if (people.Count > 0)
 2815                {
 02816                    return people;
 2817                }
 2818            }
 2819
 62820            return [];
 2821        }
 2822
 2823        public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
 2824        {
 02825            return _peopleRepository.GetPeopleNames(query)
 02826            .Select(i =>
 02827            {
 02828                try
 02829                {
 02830                    return GetPerson(i);
 02831                }
 02832                catch (Exception ex)
 02833                {
 02834                    _logger.LogError(ex, "Error getting person");
 02835                    return null;
 02836                }
 02837            })
 02838            .Where(i => i is not null)
 02839            .Where(i => query.User is null || i!.IsVisible(query.User))
 02840            .ToList()!; // null values are filtered out
 2841        }
 2842
 2843        public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
 2844        {
 02845            return _peopleRepository.GetPeopleNames(query);
 2846        }
 2847
 2848        public void UpdatePeople(BaseItem item, List<PersonInfo> people)
 2849        {
 02850            UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
 02851        }
 2852
 2853        /// <inheritdoc />
 2854        public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat
 2855        {
 2856            if (!item.SupportsPeople)
 2857            {
 2858                return;
 2859            }
 2860
 2861            if (people is not null)
 2862            {
 2863                people = people.Where(e => e is not null).ToArray();
 2864                _peopleRepository.UpdatePeople(item.Id, people);
 2865                await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
 2866            }
 2867        }
 2868
 2869        public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re
 2870        {
 2871            foreach (var url in image.Path.Split('|'))
 2872            {
 2873                try
 2874                {
 2875                    _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
 2876
 2877                    await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure
 2878
 2879                    await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai
 2880
 2881                    return item.GetImageInfo(image.Type, imageIndex);
 2882                }
 2883                catch (HttpRequestException ex)
 2884                {
 2885                    if (ex.StatusCode.HasValue
 2886                        && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb
 2887                    {
 2888                        _logger.LogDebug(ex, "Error downloading image {Url}", url);
 2889                        continue;
 2890                    }
 2891
 2892                    throw;
 2893                }
 2894            }
 2895
 2896            if (removeOnFailure)
 2897            {
 2898                // Remove this image to prevent it from retrying over and over
 2899                item.RemoveImage(image);
 2900                await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa
 2901            }
 2902
 2903            throw new InvalidOperationException("Unable to convert any images to local");
 2904        }
 2905
 2906        public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b
 2907        {
 2908            if (string.IsNullOrWhiteSpace(name))
 2909            {
 2910                throw new ArgumentNullException(nameof(name));
 2911            }
 2912
 2913            name = _fileSystem.GetValidFilename(name.Trim());
 2914
 2915            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 2916
 2917            var existingNameCount = 1; // first numbered name will be 2
 2918            var virtualFolderPath = Path.Combine(rootFolderPath, name);
 2919            var originalName = name;
 2920            while (Directory.Exists(virtualFolderPath))
 2921            {
 2922                existingNameCount++;
 2923                name = originalName + existingNameCount;
 2924                virtualFolderPath = Path.Combine(rootFolderPath, name);
 2925            }
 2926
 2927            var mediaPathInfos = options.PathInfos;
 2928            if (mediaPathInfos is not null)
 2929            {
 2930                var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
 2931                if (invalidpath is not null)
 2932                {
 2933                    throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
 2934                }
 2935            }
 2936
 2937            LibraryMonitor.Stop();
 2938
 2939            try
 2940            {
 2941                Directory.CreateDirectory(virtualFolderPath);
 2942
 2943                if (collectionType is not null)
 2944                {
 2945                    var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect
 2946
 2947                    FileHelper.CreateEmpty(path);
 2948                }
 2949
 2950                CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
 2951
 2952                if (mediaPathInfos is not null)
 2953                {
 2954                    foreach (var path in mediaPathInfos)
 2955                    {
 2956                        AddMediaPathInternal(name, path, false);
 2957                    }
 2958                }
 2959            }
 2960            finally
 2961            {
 2962                if (refreshLibrary)
 2963                {
 2964                    await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
 2965
 2966                    StartScanInBackground();
 2967                }
 2968                else
 2969                {
 2970                    // Need to add a delay here or directory watchers may still pick up the changes
 2971                    await Task.Delay(1000).ConfigureAwait(false);
 2972                    LibraryMonitor.Start();
 2973                }
 2974            }
 2975        }
 2976
 2977        private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
 2978        {
 2979            foreach (var person in people)
 2980            {
 2981                cancellationToken.ThrowIfCancellationRequested();
 2982
 2983                var itemUpdateType = ItemUpdateType.MetadataDownload;
 2984                var saveEntity = false;
 2985                var createEntity = false;
 2986                var personEntity = GetPerson(person.Name);
 2987
 2988                if (personEntity is null)
 2989                {
 2990                    var path = Person.GetPath(person.Name);
 2991                    var info = Directory.CreateDirectory(path);
 2992                    var lastWriteTime = info.LastWriteTimeUtc;
 2993                    personEntity = new Person()
 2994                    {
 2995                        Name = person.Name,
 2996                        Id = GetItemByNameId<Person>(path),
 2997                        DateCreated = info.CreationTimeUtc,
 2998                        DateModified = lastWriteTime,
 2999                        Path = path
 3000                    };
 3001
 3002                    personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
 3003                    saveEntity = true;
 3004                    createEntity = true;
 3005                }
 3006
 3007                foreach (var id in person.ProviderIds)
 3008                {
 3009                    if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)
 3010                    {
 3011                        personEntity.SetProviderId(id.Key, id.Value);
 3012                        saveEntity = true;
 3013                    }
 3014                }
 3015
 3016                if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
 3017                {
 3018                    personEntity.SetImage(
 3019                        new ItemImageInfo
 3020                        {
 3021                            Path = person.ImageUrl,
 3022                            Type = ImageType.Primary
 3023                        },
 3024                        0);
 3025
 3026                    saveEntity = true;
 3027                    itemUpdateType = ItemUpdateType.ImageUpdate;
 3028                }
 3029
 3030                if (saveEntity)
 3031                {
 3032                    if (createEntity)
 3033                    {
 3034                        CreateItems([personEntity], null, CancellationToken.None);
 3035                    }
 3036
 3037                    await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
 3038                    CreateItems([personEntity], null, CancellationToken.None);
 3039                }
 3040            }
 3041        }
 3042
 3043        private void StartScanInBackground()
 3044        {
 33045            Task.Run(() =>
 33046            {
 33047                // No need to start if scanning the library because it will handle it
 33048                ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
 33049            });
 33050        }
 3051
 3052        public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3053        {
 13054            AddMediaPathInternal(virtualFolderName, mediaPath, true);
 03055        }
 3056
 3057        private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
 3058        {
 13059            ArgumentNullException.ThrowIfNull(pathInfo);
 3060
 13061            var path = pathInfo.Path;
 3062
 13063            if (string.IsNullOrWhiteSpace(path))
 3064            {
 03065                throw new ArgumentException(nameof(path));
 3066            }
 3067
 13068            if (!Directory.Exists(path))
 3069            {
 13070                throw new FileNotFoundException("The path does not exist.");
 3071            }
 3072
 03073            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03074            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3075
 03076            var shortcutFilename = Path.GetFileNameWithoutExtension(path);
 3077
 03078            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3079
 03080            while (File.Exists(lnk))
 3081            {
 03082                shortcutFilename += "1";
 03083                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3084            }
 3085
 03086            _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
 3087
 03088            RemoveContentTypeOverrides(path);
 3089
 03090            if (saveLibraryOptions)
 3091            {
 03092                var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3093
 03094                libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
 3095
 03096                SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3097
 03098                CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 3099            }
 03100        }
 3101
 3102        public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3103        {
 03104            ArgumentNullException.ThrowIfNull(mediaPath);
 3105
 03106            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03107            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3108
 03109            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3110
 03111            SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3112
 03113            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03114        }
 3115
 3116        private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
 3117        {
 03118            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 03119            var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
 3120
 03121            if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
 3122            {
 03123                var list = options.PathInfos.ToList();
 3124
 03125                foreach (var location in info.Locations)
 3126                {
 03127                    if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
 3128                    {
 03129                        list.Add(new MediaPathInfo(location));
 3130                    }
 3131                }
 3132
 03133                options.PathInfos = list.ToArray();
 3134            }
 03135        }
 3136
 3137        public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
 3138        {
 3139            if (string.IsNullOrWhiteSpace(name))
 3140            {
 3141                throw new ArgumentNullException(nameof(name));
 3142            }
 3143
 3144            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3145
 3146            var path = Path.Combine(rootFolderPath, name);
 3147
 3148            if (!Directory.Exists(path))
 3149            {
 3150                throw new FileNotFoundException("The media folder does not exist");
 3151            }
 3152
 3153            LibraryMonitor.Stop();
 3154
 3155            try
 3156            {
 3157                Directory.Delete(path, true);
 3158            }
 3159            finally
 3160            {
 3161                CollectionFolder.OnCollectionFolderChange();
 3162
 3163                if (refreshLibrary)
 3164                {
 3165                    await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
 3166
 3167                    StartScanInBackground();
 3168                }
 3169                else
 3170                {
 3171                    // Need to add a delay here or directory watchers may still pick up the changes
 3172                    await Task.Delay(1000).ConfigureAwait(false);
 3173                    LibraryMonitor.Start();
 3174                }
 3175            }
 3176        }
 3177
 3178        private void RemoveContentTypeOverrides(string path)
 3179        {
 03180            if (string.IsNullOrWhiteSpace(path))
 3181            {
 03182                throw new ArgumentNullException(nameof(path));
 3183            }
 3184
 03185            List<NameValuePair>? removeList = null;
 3186
 03187            foreach (var contentType in _configurationManager.Configuration.ContentTypes)
 3188            {
 03189                if (string.IsNullOrWhiteSpace(contentType.Name)
 03190                    || _fileSystem.AreEqual(path, contentType.Name)
 03191                    || _fileSystem.ContainsSubPath(path, contentType.Name))
 3192                {
 03193                    (removeList ??= new()).Add(contentType);
 3194                }
 3195            }
 3196
 03197            if (removeList is not null)
 3198            {
 03199                _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
 03200                    .Except(removeList)
 03201                    .ToArray();
 3202
 03203                _configurationManager.SaveConfiguration();
 3204            }
 03205        }
 3206
 3207        public void RemoveMediaPath(string virtualFolderName, string mediaPath)
 3208        {
 13209            ArgumentException.ThrowIfNullOrEmpty(mediaPath);
 3210
 13211            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 13212            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3213
 13214            if (!Directory.Exists(virtualFolderPath))
 3215            {
 13216                throw new FileNotFoundException(
 13217                    string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder
 3218            }
 3219
 03220            var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
 03221                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 03222                .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String
 3223
 03224            if (!string.IsNullOrEmpty(shortcut))
 3225            {
 03226                _fileSystem.DeleteFile(shortcut);
 3227            }
 3228
 03229            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3230
 03231            libraryOptions.PathInfos = libraryOptions
 03232                .PathInfos
 03233                .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
 03234                .ToArray();
 3235
 03236            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03237        }
 3238
 3239        private static bool ItemIsVisible(BaseItem? item, User? user)
 3240        {
 213241            if (item is null)
 3242            {
 213243                return false;
 3244            }
 3245
 03246            if (user is null)
 3247            {
 03248                return true;
 3249            }
 3250
 03251            return item is UserRootFolder || item.IsVisibleStandalone(user);
 3252        }
 3253    }
 3254}

Methods/Properties

.ctor(MediaBrowser.Controller.IServerApplicationHost,Microsoft.Extensions.Logging.ILoggerFactory,MediaBrowser.Model.Tasks.ITaskManager,MediaBrowser.Controller.Library.IUserManager,MediaBrowser.Controller.Configuration.IServerConfigurationManager,MediaBrowser.Controller.Library.IUserDataManager,System.Lazy`1<MediaBrowser.Controller.Library.ILibraryMonitor>,MediaBrowser.Model.IO.IFileSystem,System.Lazy`1<MediaBrowser.Controller.Providers.IProviderManager>,System.Lazy`1<MediaBrowser.Controller.Library.IUserViewManager>,MediaBrowser.Controller.MediaEncoding.IMediaEncoder,MediaBrowser.Controller.Persistence.IItemRepository,MediaBrowser.Controller.Drawing.IImageProcessor,Emby.Naming.Common.NamingOptions,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Persistence.IPeopleRepository,MediaBrowser.Controller.IO.IPathManager)
get_RootFolder()
get_LibraryMonitor()
get_ProviderManager()
get_UserViewManager()
AddParts(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Resolvers.IResolverIgnoreRule>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Resolvers.IItemResolver>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Library.IIntroProvider>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Sorting.IBaseItemComparer>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Library.ILibraryPostScanTask>)
RecordConfigurationValues(MediaBrowser.Model.Configuration.ServerConfiguration)
ConfigurationUpdated(System.Object,System.EventArgs)
RegisterItem(MediaBrowser.Controller.Entities.BaseItem)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions,System.Boolean)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions,MediaBrowser.Controller.Entities.BaseItem,System.Boolean)
IsInternalItem(MediaBrowser.Controller.Entities.BaseItem)
GetMetadataPaths(MediaBrowser.Controller.Entities.BaseItem,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>)
GetInternalMetadataPaths(MediaBrowser.Controller.Entities.BaseItem)
ResolveItem(MediaBrowser.Controller.Library.ItemResolveArgs,MediaBrowser.Controller.Resolvers.IItemResolver[])
Resolve(MediaBrowser.Controller.Library.ItemResolveArgs,MediaBrowser.Controller.Resolvers.IItemResolver)
GetNewItemId(System.String,System.Type)
GetNewItemIdInternal(System.String,System.Type,System.Boolean)
ResolvePath(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Controller.Providers.IDirectoryService)
ResolvePath(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Resolvers.IItemResolver[],MediaBrowser.Controller.Entities.Folder,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,MediaBrowser.Model.Configuration.LibraryOptions)
IgnoreFile(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Entities.BaseItem)
NormalizeRootPathList(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>)
ResolvePaths(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Model.Configuration.LibraryOptions,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>)
ResolvePaths(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Model.Configuration.LibraryOptions,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,MediaBrowser.Controller.Resolvers.IItemResolver[])
CreateRootFolder()
GetUserRootFolder()
FindByPath(System.String,System.Nullable`1<System.Boolean>)
GetPerson(System.String)
GetStudio(System.String)
GetStudioId(System.String)
GetGenreId(System.String)
GetMusicGenreId(System.String)
GetGenre(System.String)
GetMusicGenre(System.String)
GetYear(System.Int32)
GetArtist(System.String)
GetArtist(System.String,MediaBrowser.Controller.Dto.DtoOptions)
CreateItemByName(System.Func`2<System.String,System.String>,System.String,MediaBrowser.Controller.Dto.DtoOptions)
GetItemByNameId(System.String)
ValidatePeopleAsync(System.IProgress`1<System.Double>,System.Threading.CancellationToken)
ValidateMediaLibrary(System.IProgress`1<System.Double>,System.Threading.CancellationToken)
GetVirtualFolders()
GetVirtualFolders(System.Boolean)
GetVirtualFolderInfo(System.String,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.BaseItem>,System.Collections.Generic.HashSet`1<System.Guid>)
GetCollectionType(System.String)
GetItemById(System.Guid)
GetItemById(System.Guid)
GetItemById(System.Guid,System.Guid)
GetItemById(System.Guid,Jellyfin.Database.Implementations.Entities.User)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Boolean)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetCount(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.BaseItem>)
GetLatestItemList(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Controller.Entities.BaseItem>,Jellyfin.Data.Enums.CollectionType)
GetNextUpSeriesKeys(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.IReadOnlyCollection`1<MediaBrowser.Controller.Entities.BaseItem>,System.DateTime)
QueryItems(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemIds(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetStudios(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetGenres(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetMusicGenres(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetAllArtists(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetArtists(MediaBrowser.Controller.Entities.InternalItemsQuery)
SetTopParentOrAncestorIds(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetAlbumArtists(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemsResult(MediaBrowser.Controller.Entities.InternalItemsQuery)
SetTopParentIdsOrAncestors(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Collections.Generic.IReadOnlyCollection`1<MediaBrowser.Controller.Entities.BaseItem>)
AddUserToQuery(MediaBrowser.Controller.Entities.InternalItemsQuery,Jellyfin.Database.Implementations.Entities.User,System.Boolean)
GetTopParentIdsForQuery(MediaBrowser.Controller.Entities.BaseItem,Jellyfin.Database.Implementations.Entities.User)
ResolveIntro(MediaBrowser.Controller.Library.IntroInfo)
Sort(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.IEnumerable`1<Jellyfin.Data.Enums.ItemSortBy>,Jellyfin.Database.Implementations.Enums.SortOrder)
Sort(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>,Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.IEnumerable`1<System.ValueTuple`2<Jellyfin.Data.Enums.ItemSortBy,Jellyfin.Database.Implementations.Enums.SortOrder>>)
GetComparer(Jellyfin.Data.Enums.ItemSortBy,Jellyfin.Database.Implementations.Entities.User)
CreateItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Entities.BaseItem)
CreateItems(System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Controller.Entities.BaseItem>,MediaBrowser.Controller.Entities.BaseItem,System.Threading.CancellationToken)
ImageNeedsRefresh(MediaBrowser.Controller.Entities.ItemImageInfo)
UpdateItemAsync(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.ItemUpdateType,System.Threading.CancellationToken)
ReportItemRemoved(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Entities.BaseItem)
RetrieveItem(System.Guid)
GetCollectionFolders(MediaBrowser.Controller.Entities.BaseItem)
GetCollectionFolders(MediaBrowser.Controller.Entities.BaseItem,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.Folder>)
GetCollectionFoldersInternal(MediaBrowser.Controller.Entities.BaseItem,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.Folder>)
GetLibraryOptions(MediaBrowser.Controller.Entities.BaseItem)
GetContentType(MediaBrowser.Controller.Entities.BaseItem)
GetInheritedContentType(MediaBrowser.Controller.Entities.BaseItem)
GetConfiguredContentType(MediaBrowser.Controller.Entities.BaseItem)
GetConfiguredContentType(System.String)
GetConfiguredContentType(MediaBrowser.Controller.Entities.BaseItem,System.Boolean)
GetContentTypeOverride(System.String,System.Boolean)
GetTopFolderContentType(MediaBrowser.Controller.Entities.BaseItem)
GetNamedView(Jellyfin.Database.Implementations.Entities.User,System.String,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,System.String)
GetNamedView(System.String,Jellyfin.Data.Enums.CollectionType,System.String)
GetNamedView(Jellyfin.Database.Implementations.Entities.User,System.String,System.Guid,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,System.String)
GetShadowView(MediaBrowser.Controller.Entities.BaseItem,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,System.String)
GetNamedView(System.String,System.Guid,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,System.String,System.String)
GetParentItem(System.Nullable`1<System.Guid>,System.Nullable`1<System.Guid>)
QueueLibraryScan()
GetSeasonNumberFromPath(System.String,System.Nullable`1<System.Guid>)
FillMissingEpisodeNumbersFromPath(MediaBrowser.Controller.Entities.TV.Episode,System.Boolean)
ParseName(System.String)
GetPathAfterNetworkSubstitution(System.String,MediaBrowser.Controller.Entities.BaseItem)
GetPeople(MediaBrowser.Controller.Entities.InternalPeopleQuery)
GetPeople(MediaBrowser.Controller.Entities.BaseItem)
GetPeopleItems(MediaBrowser.Controller.Entities.InternalPeopleQuery)
GetPeopleNames(MediaBrowser.Controller.Entities.InternalPeopleQuery)
UpdatePeople(MediaBrowser.Controller.Entities.BaseItem,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.PersonInfo>)
StartScanInBackground()
AddMediaPath(System.String,MediaBrowser.Model.Configuration.MediaPathInfo)
AddMediaPathInternal(System.String,MediaBrowser.Model.Configuration.MediaPathInfo,System.Boolean)
UpdateMediaPath(System.String,MediaBrowser.Model.Configuration.MediaPathInfo)
SyncLibraryOptionsToLocations(System.String,MediaBrowser.Model.Configuration.LibraryOptions)
RemoveContentTypeOverrides(System.String)
RemoveMediaPath(System.String,System.String)
ItemIsVisible(MediaBrowser.Controller.Entities.BaseItem,Jellyfin.Database.Implementations.Entities.User)