< 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: 651
Coverable lines: 1078
Total lines: 3266
Line coverage: 39.6%
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            {
 143191                if (_rootFolder is null)
 21192                {
 193                    lock (_rootFolderSyncLock)
 194                    {
 21195                        _rootFolder ??= CreateRootFolder();
 21196                    }
 197                }
 198
 143199                return _rootFolder;
 200            }
 201        }
 202
 39203        private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
 204
 84205        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        {
 145296            ArgumentNullException.ThrowIfNull(item);
 297
 145298            if (item is IItemByName)
 299            {
 0300                if (item is not MusicArtist)
 301                {
 0302                    return;
 303                }
 304            }
 145305            else if (!item.IsFolder)
 306            {
 0307                if (item is not Video && item is not LiveTvChannel)
 308                {
 0309                    return;
 310                }
 311            }
 312
 145313            _cache.AddOrUpdate(item.Id, item);
 145314        }
 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            {
 66563                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            {
 276573                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            }
 276580        }
 581
 582        public Guid GetNewItemId(string key, Type type)
 583        {
 129584            return GetNewItemIdInternal(key, type, false);
 585        }
 586
 587        private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
 588        {
 130589            ArgumentException.ThrowIfNullOrEmpty(key);
 130590            ArgumentNullException.ThrowIfNull(type);
 591
 130592            string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
 130593            if (key.StartsWith(programDataPath, StringComparison.Ordinal))
 594            {
 595                // Try to normalize paths located underneath program-data in an attempt to make them more portable
 113596                key = key.Substring(programDataPath.Length)
 113597                    .TrimStart('/', '\\')
 113598                    .Replace('/', '\\');
 599            }
 600
 130601            if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
 602            {
 1603                key = key.ToLowerInvariant();
 604            }
 605
 130606            key = type.FullName + key;
 607
 130608            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            {
 49648                var isPhysicalRoot = args.IsPhysicalRoot;
 649
 650                // When resolving the root, we need it's grandchildren (children of user views)
 49651                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
 652
 653                FileSystemMetadata[] files;
 49654                var isVf = args.IsVf;
 655
 656                try
 657                {
 49658                    files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l
 49659                }
 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
 49676                if (isPhysicalRoot)
 677                {
 21678                    files = NormalizeRootPathList(files).ToArray();
 679                }
 680
 49681                args.FileSystemChildren = files;
 682            }
 683
 684            // Filter content based on ignore rules
 74685            if (args.IsDirectory)
 686            {
 49687                var filtered = args.GetActualFileSystemChildren().ToArray();
 49688                args.FileSystemChildren = filtered ?? [];
 689            }
 690
 74691            return ResolveItem(args, resolvers);
 692        }
 693
 694        public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
 96695            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 696
 697        public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
 698        {
 63699            var originalList = paths.ToList();
 700
 63701            var list = originalList.Where(i => i.IsDirectory)
 63702                .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
 63703                .Distinct()
 63704                .ToList();
 705
 63706            var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS
 63707                .ToList();
 708
 126709            foreach (var dupe in dupes)
 710            {
 0711                _logger.LogInformation("Found duplicate path: {0}", dupe);
 712            }
 713
 63714            var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
 63715            newList.AddRange(originalList.Where(i => !i.IsDirectory));
 63716            return newList;
 717        }
 718
 719        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ
 720        {
 35721            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        {
 35732            var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
 733
 35734            if (parent is not null)
 735            {
 35736                var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>()
 737
 210738                foreach (var resolver in multiItemResolvers)
 739                {
 70740                    var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
 741
 70742                    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
 35752            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        {
 715842            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
 715884            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        {
 7751293            if (id.IsEmpty())
 1294            {
 01295                throw new ArgumentException("Guid can't be empty", nameof(id));
 1296            }
 1297
 7751298            if (_cache.TryGet(id, out var item))
 1299            {
 5441300                return item;
 1301            }
 1302
 2311303            item = RetrieveItem(id);
 1304
 2311305            if (item is not null)
 1306            {
 01307                RegisterItem(item);
 1308            }
 1309
 2311310            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        {
 861344            if (query.Recursive && !query.ParentId.IsEmpty())
 1345            {
 351346                var parent = GetItemById(query.ParentId);
 351347                if (parent is not null)
 1348                {
 351349                    SetTopParentIdsOrAncestors(query, [parent]);
 1350                }
 1351            }
 1352
 861353            if (query.User is not null)
 1354            {
 11355                AddUserToQuery(query, query.User, allowExternalContent);
 1356            }
 1357
 861358            var itemList = _itemRepository.GetItemList(query);
 861359            var user = query.User;
 861360            if (user is not null)
 1361            {
 11362                return itemList.Where(i => i.IsVisible(user)).ToList();
 1363            }
 1364
 851365            return itemList;
 1366        }
 1367
 1368        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 1369        {
 861370            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        {
 91457            if (query.User is not null)
 1458            {
 01459                AddUserToQuery(query, query.User);
 1460            }
 1461
 91462            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        {
 151563            if (query.Recursive && !query.ParentId.IsEmpty())
 1564            {
 141565                var parent = GetItemById(query.ParentId);
 141566                if (parent is not null)
 1567                {
 141568                    SetTopParentIdsOrAncestors(query, [parent]);
 1569                }
 1570            }
 1571
 151572            if (query.User is not null)
 1573            {
 11574                AddUserToQuery(query, query.User);
 1575            }
 1576
 151577            if (query.EnableTotalRecordCount)
 1578            {
 11579                return _itemRepository.GetItems(query);
 1580            }
 1581
 141582            return new QueryResult<BaseItem>(
 141583                query.StartIndex,
 141584                null,
 141585                _itemRepository.GetItemList(query));
 1586        }
 1587
 1588        private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
 1589        {
 491590            if (parents.All(i => i is ICollectionFolder || i is UserView))
 1591            {
 1592                // Optimize by querying against top level views
 141593                query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 1594
 1595                // Prevent searching in all libraries due to empty filter
 141596                if (query.TopParentIds.Length == 0)
 1597                {
 141598                    query.TopParentIds = [Guid.NewGuid()];
 1599                }
 1600            }
 1601            else
 1602            {
 1603                // We need to be able to query from any arbitrary ancestor up the tree
 351604                query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
 1605
 1606                // Prevent searching in all libraries due to empty filter
 351607                if (query.AncestorIds.Length == 0)
 1608                {
 01609                    query.AncestorIds = [Guid.NewGuid()];
 1610                }
 1611            }
 1612
 491613            query.Parent = null;
 491614        }
 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        {
 141645            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
 141690            if (item is CollectionFolder collectionFolder)
 1691            {
 141692                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            foreach (var item in items)
 2054            {
 2055                item.DateLastSaved = DateTime.UtcNow;
 2056                await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
 2057
 2058                // Modify again, so saved value is after write time of externally saved metadata
 2059                item.DateLastSaved = DateTime.UtcNow;
 2060            }
 2061
 2062            _itemRepository.SaveItems(items, cancellationToken);
 2063
 2064            if (ItemUpdated is not null)
 2065            {
 2066                foreach (var item in items)
 2067                {
 2068                    // With the live tv guide this just creates too much noise
 2069                    if (item.SourceType != SourceType.Library)
 2070                    {
 2071                        continue;
 2072                    }
 2073
 2074                    try
 2075                    {
 2076                        ItemUpdated(
 2077                            this,
 2078                            new ItemChangeEventArgs
 2079                            {
 2080                                Item = item,
 2081                                Parent = parent,
 2082                                UpdateReason = updateReason
 2083                            });
 2084                    }
 2085                    catch (Exception ex)
 2086                    {
 2087                        _logger.LogError(ex, "Error in ItemUpdated event handler");
 2088                    }
 2089                }
 2090            }
 2091        }
 2092
 2093        /// <inheritdoc />
 2094        public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance
 832095            => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
 2096
 2097        public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
 2098        {
 2099            if (item.IsFileProtocol)
 2100            {
 2101                await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
 2102            }
 2103
 2104            await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
 2105        }
 2106
 2107        /// <summary>
 2108        /// Reports the item removed.
 2109        /// </summary>
 2110        /// <param name="item">The item.</param>
 2111        /// <param name="parent">The parent item.</param>
 2112        public void ReportItemRemoved(BaseItem item, BaseItem parent)
 2113        {
 22114            if (ItemRemoved is not null)
 2115            {
 2116                try
 2117                {
 22118                    ItemRemoved(
 22119                        this,
 22120                        new ItemChangeEventArgs
 22121                        {
 22122                            Item = item,
 22123                            Parent = parent
 22124                        });
 22125                }
 02126                catch (Exception ex)
 2127                {
 02128                    _logger.LogError(ex, "Error in ItemRemoved event handler");
 02129                }
 2130            }
 22131        }
 2132
 2133        /// <summary>
 2134        /// Retrieves the item.
 2135        /// </summary>
 2136        /// <param name="id">The id.</param>
 2137        /// <returns>BaseItem.</returns>
 2138        public BaseItem RetrieveItem(Guid id)
 2139        {
 2312140            return _itemRepository.RetrieveItem(id);
 2141        }
 2142
 2143        public List<Folder> GetCollectionFolders(BaseItem item)
 2144        {
 6012145            return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
 2146        }
 2147
 2148        public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2149        {
 6452150            while (item is not null)
 2151            {
 6452152                var parent = item.GetParent();
 2153
 6452154                if (parent is AggregateFolder)
 2155                {
 2156                    break;
 2157                }
 2158
 6242159                if (parent is null)
 2160                {
 5802161                    var owner = item.GetOwner();
 2162
 5802163                    if (owner is null)
 2164                    {
 2165                        break;
 2166                    }
 2167
 02168                    item = owner;
 2169                }
 2170                else
 2171                {
 442172                    item = parent;
 2173                }
 2174            }
 2175
 6012176            if (item is null)
 2177            {
 02178                return new List<Folder>();
 2179            }
 2180
 6012181            return GetCollectionFoldersInternal(item, allUserRootChildren);
 2182        }
 2183
 2184        private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2185        {
 6012186            return allUserRootChildren
 6012187                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 6012188                .ToList();
 2189        }
 2190
 2191        public LibraryOptions GetLibraryOptions(BaseItem item)
 2192        {
 3872193            if (item is CollectionFolder collectionFolder)
 2194            {
 632195                return collectionFolder.GetLibraryOptions();
 2196            }
 2197
 2198            // List.Find is more performant than FirstOrDefault due to enumerator allocation
 3242199            return GetCollectionFolders(item)
 3242200                .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
 3242201                ? collectionFolder2.GetLibraryOptions()
 3242202                : new LibraryOptions();
 2203        }
 2204
 2205        public CollectionType? GetContentType(BaseItem item)
 2206        {
 352207            var configuredContentType = GetConfiguredContentType(item, false);
 352208            if (configuredContentType is not null)
 2209            {
 02210                return configuredContentType;
 2211            }
 2212
 352213            configuredContentType = GetConfiguredContentType(item, true);
 352214            if (configuredContentType is not null)
 2215            {
 02216                return configuredContentType;
 2217            }
 2218
 352219            return GetInheritedContentType(item);
 2220        }
 2221
 2222        public CollectionType? GetInheritedContentType(BaseItem item)
 2223        {
 352224            var type = GetTopFolderContentType(item);
 2225
 352226            if (type is not null)
 2227            {
 02228                return type;
 2229            }
 2230
 352231            return item.GetParents()
 352232                .Select(GetConfiguredContentType)
 352233                .LastOrDefault(i => i is not null);
 2234        }
 2235
 2236        public CollectionType? GetConfiguredContentType(BaseItem item)
 2237        {
 02238            return GetConfiguredContentType(item, false);
 2239        }
 2240
 2241        public CollectionType? GetConfiguredContentType(string path)
 2242        {
 02243            return GetContentTypeOverride(path, false);
 2244        }
 2245
 2246        public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
 2247        {
 702248            if (item is ICollectionFolder collectionFolder)
 2249            {
 02250                return collectionFolder.CollectionType;
 2251            }
 2252
 702253            return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
 2254        }
 2255
 2256        private CollectionType? GetContentTypeOverride(string path, bool inherit)
 2257        {
 852258            var nameValuePair = _configurationManager.Configuration.ContentTypes
 852259                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
 852260                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
 852261                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
 852262            if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
 2263            {
 02264                return collectionType;
 2265            }
 2266
 852267            return null;
 2268        }
 2269
 2270        private CollectionType? GetTopFolderContentType(BaseItem item)
 2271        {
 352272            if (item is null)
 2273            {
 02274                return null;
 2275            }
 2276
 352277            while (!item.ParentId.IsEmpty())
 2278            {
 02279                var parent = item.GetParent();
 02280                if (parent is null || parent is AggregateFolder)
 2281                {
 2282                    break;
 2283                }
 2284
 02285                item = parent;
 2286            }
 2287
 352288            return GetUserRootFolder().Children
 352289                .OfType<ICollectionFolder>()
 352290                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 352291                .Select(i => i.CollectionType)
 352292                .FirstOrDefault(i => i is not null);
 2293        }
 2294
 2295        public UserView GetNamedView(
 2296            User user,
 2297            string name,
 2298            CollectionType? viewType,
 2299            string sortName)
 2300        {
 02301            return GetNamedView(user, name, Guid.Empty, viewType, sortName);
 2302        }
 2303
 2304        public UserView GetNamedView(
 2305            string name,
 2306            CollectionType viewType,
 2307            string sortName)
 2308        {
 02309            var path = Path.Combine(
 02310                _configurationManager.ApplicationPaths.InternalMetadataPath,
 02311                "views",
 02312                _fileSystem.GetValidFilename(viewType.ToString()));
 2313
 02314            var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 2315
 02316            var item = GetItemById(id) as UserView;
 2317
 02318            var refresh = false;
 2319
 02320            if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
 2321            {
 02322                var info = Directory.CreateDirectory(path);
 02323                item = new UserView
 02324                {
 02325                    Path = path,
 02326                    Id = id,
 02327                    DateCreated = info.CreationTimeUtc,
 02328                    DateModified = info.LastWriteTimeUtc,
 02329                    Name = name,
 02330                    ViewType = viewType,
 02331                    ForcedSortName = sortName
 02332                };
 2333
 02334                CreateItem(item, null);
 2335
 02336                refresh = true;
 2337            }
 2338
 02339            if (refresh)
 2340            {
 02341                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu
 02342                ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref
 2343            }
 2344
 02345            return item;
 2346        }
 2347
 2348        public UserView GetNamedView(
 2349            User user,
 2350            string name,
 2351            Guid parentId,
 2352            CollectionType? viewType,
 2353            string sortName)
 2354        {
 02355            var parentIdString = parentId.IsEmpty()
 02356                ? null
 02357                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02358            var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin
 2359
 02360            var id = GetNewItemId(idValues, typeof(UserView));
 2361
 02362            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2363
 02364            var item = GetItemById(id) as UserView;
 2365
 02366            var isNew = false;
 2367
 02368            if (item is null)
 2369            {
 02370                var info = Directory.CreateDirectory(path);
 02371                item = new UserView
 02372                {
 02373                    Path = path,
 02374                    Id = id,
 02375                    DateCreated = info.CreationTimeUtc,
 02376                    DateModified = info.LastWriteTimeUtc,
 02377                    Name = name,
 02378                    ViewType = viewType,
 02379                    ForcedSortName = sortName,
 02380                    UserId = user.Id,
 02381                    DisplayParentId = parentId
 02382                };
 2383
 02384                CreateItem(item, null);
 2385
 02386                isNew = true;
 2387            }
 2388
 02389            var lastRefreshedUtc = item.DateLastRefreshed;
 02390            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2391
 02392            if (!refresh && !item.DisplayParentId.IsEmpty())
 2393            {
 02394                var displayParent = GetItemById(item.DisplayParentId);
 02395                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2396            }
 2397
 02398            if (refresh)
 2399            {
 02400                ProviderManager.QueueRefresh(
 02401                    item.Id,
 02402                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02403                    {
 02404                        // Need to force save to increment DateLastSaved
 02405                        ForceSave = true
 02406                    },
 02407                    RefreshPriority.Normal);
 2408            }
 2409
 02410            return item;
 2411        }
 2412
 2413        public UserView GetShadowView(
 2414            BaseItem parent,
 2415            CollectionType? viewType,
 2416            string sortName)
 2417        {
 02418            ArgumentNullException.ThrowIfNull(parent);
 2419
 02420            var name = parent.Name;
 02421            var parentId = parent.Id;
 2422
 02423            var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
 2424
 02425            var id = GetNewItemId(idValues, typeof(UserView));
 2426
 02427            var path = parent.Path;
 2428
 02429            var item = GetItemById(id) as UserView;
 2430
 02431            var isNew = false;
 2432
 02433            if (item is null)
 2434            {
 02435                var info = Directory.CreateDirectory(path);
 02436                item = new UserView
 02437                {
 02438                    Path = path,
 02439                    Id = id,
 02440                    DateCreated = info.CreationTimeUtc,
 02441                    DateModified = info.LastWriteTimeUtc,
 02442                    Name = name,
 02443                    ViewType = viewType,
 02444                    ForcedSortName = sortName,
 02445                    DisplayParentId = parentId
 02446                };
 2447
 02448                CreateItem(item, null);
 2449
 02450                isNew = true;
 2451            }
 2452
 02453            var lastRefreshedUtc = item.DateLastRefreshed;
 02454            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2455
 02456            if (!refresh && !item.DisplayParentId.IsEmpty())
 2457            {
 02458                var displayParent = GetItemById(item.DisplayParentId);
 02459                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2460            }
 2461
 02462            if (refresh)
 2463            {
 02464                ProviderManager.QueueRefresh(
 02465                    item.Id,
 02466                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02467                    {
 02468                        // Need to force save to increment DateLastSaved
 02469                        ForceSave = true
 02470                    },
 02471                    RefreshPriority.Normal);
 2472            }
 2473
 02474            return item;
 2475        }
 2476
 2477        public UserView GetNamedView(
 2478            string name,
 2479            Guid parentId,
 2480            CollectionType? viewType,
 2481            string sortName,
 2482            string uniqueId)
 2483        {
 02484            ArgumentException.ThrowIfNullOrEmpty(name);
 2485
 02486            var parentIdString = parentId.IsEmpty()
 02487                ? null
 02488                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02489            var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E
 02490            if (!string.IsNullOrEmpty(uniqueId))
 2491            {
 02492                idValues += uniqueId;
 2493            }
 2494
 02495            var id = GetNewItemId(idValues, typeof(UserView));
 2496
 02497            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2498
 02499            var item = GetItemById(id) as UserView;
 2500
 02501            var isNew = false;
 2502
 02503            if (item is null)
 2504            {
 02505                var info = Directory.CreateDirectory(path);
 02506                item = new UserView
 02507                {
 02508                    Path = path,
 02509                    Id = id,
 02510                    DateCreated = info.CreationTimeUtc,
 02511                    DateModified = info.LastWriteTimeUtc,
 02512                    Name = name,
 02513                    ViewType = viewType,
 02514                    ForcedSortName = sortName,
 02515                    DisplayParentId = parentId
 02516                };
 2517
 02518                CreateItem(item, null);
 2519
 02520                isNew = true;
 2521            }
 2522
 02523            if (viewType != item.ViewType)
 2524            {
 02525                item.ViewType = viewType;
 02526                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult
 2527            }
 2528
 02529            var lastRefreshedUtc = item.DateLastRefreshed;
 02530            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2531
 02532            if (!refresh && !item.DisplayParentId.IsEmpty())
 2533            {
 02534                var displayParent = GetItemById(item.DisplayParentId);
 02535                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2536            }
 2537
 02538            if (refresh)
 2539            {
 02540                ProviderManager.QueueRefresh(
 02541                    item.Id,
 02542                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02543                    {
 02544                        // Need to force save to increment DateLastSaved
 02545                        ForceSave = true
 02546                    },
 02547                    RefreshPriority.Normal);
 2548            }
 2549
 02550            return item;
 2551        }
 2552
 2553        public BaseItem GetParentItem(Guid? parentId, Guid? userId)
 2554        {
 32555            if (parentId.HasValue)
 2556            {
 02557                return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}"
 2558            }
 2559
 32560            if (!userId.IsNullOrEmpty())
 2561            {
 32562                return GetUserRootFolder();
 2563            }
 2564
 02565            return RootFolder;
 2566        }
 2567
 2568        /// <inheritdoc />
 2569        public void QueueLibraryScan()
 2570        {
 02571            _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
 02572        }
 2573
 2574        /// <inheritdoc />
 2575        public int? GetSeasonNumberFromPath(string path, Guid? parentId)
 2576        {
 02577            var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
 02578            return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
 2579        }
 2580
 2581        /// <inheritdoc />
 2582        public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
 2583        {
 02584            var series = episode.Series;
 02585            bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis
 02586            if (!isAbsoluteNaming.Value)
 2587            {
 2588                // In other words, no filter applied
 02589                isAbsoluteNaming = null;
 2590            }
 2591
 02592            var resolver = new EpisodeResolver(_namingOptions);
 2593
 02594            var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
 2595
 02596            EpisodeInfo? episodeInfo = null;
 02597            if (episode.IsFileProtocol)
 2598            {
 02599                episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
 2600                // Resolve from parent folder if it's not the Season folder
 02601                var parent = episode.GetParent();
 02602                if (episodeInfo is null && parent.GetType() == typeof(Folder))
 2603                {
 02604                    episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
 02605                    if (episodeInfo is not null)
 2606                    {
 2607                        // add the container
 02608                        episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
 2609                    }
 2610                }
 2611            }
 2612
 02613            var changed = false;
 02614            if (episodeInfo is null)
 2615            {
 02616                return changed;
 2617            }
 2618
 02619            if (episodeInfo.IsByDate)
 2620            {
 02621                if (episode.IndexNumber.HasValue)
 2622                {
 02623                    episode.IndexNumber = null;
 02624                    changed = true;
 2625                }
 2626
 02627                if (episode.IndexNumberEnd.HasValue)
 2628                {
 02629                    episode.IndexNumberEnd = null;
 02630                    changed = true;
 2631                }
 2632
 02633                if (!episode.PremiereDate.HasValue)
 2634                {
 02635                    if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
 2636                    {
 02637                        episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo
 2638                    }
 2639
 02640                    if (episode.PremiereDate.HasValue)
 2641                    {
 02642                        changed = true;
 2643                    }
 2644                }
 2645
 02646                if (!episode.ProductionYear.HasValue)
 2647                {
 02648                    episode.ProductionYear = episodeInfo.Year;
 2649
 02650                    if (episode.ProductionYear.HasValue)
 2651                    {
 02652                        changed = true;
 2653                    }
 2654                }
 2655            }
 2656            else
 2657            {
 02658                if (!episode.IndexNumber.HasValue || forceRefresh)
 2659                {
 02660                    if (episode.IndexNumber != episodeInfo.EpisodeNumber)
 2661                    {
 02662                        changed = true;
 2663                    }
 2664
 02665                    episode.IndexNumber = episodeInfo.EpisodeNumber;
 2666                }
 2667
 02668                if (!episode.IndexNumberEnd.HasValue || forceRefresh)
 2669                {
 02670                    if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
 2671                    {
 02672                        changed = true;
 2673                    }
 2674
 02675                    episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
 2676                }
 2677
 02678                if (!episode.ParentIndexNumber.HasValue || forceRefresh)
 2679                {
 02680                    if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
 2681                    {
 02682                        changed = true;
 2683                    }
 2684
 02685                    episode.ParentIndexNumber = episodeInfo.SeasonNumber;
 2686                }
 2687            }
 2688
 02689            if (!episode.ParentIndexNumber.HasValue)
 2690            {
 02691                var season = episode.Season;
 2692
 02693                if (season is not null)
 2694                {
 02695                    episode.ParentIndexNumber = season.IndexNumber;
 2696                }
 2697
 02698                if (episode.ParentIndexNumber.HasValue)
 2699                {
 02700                    changed = true;
 2701                }
 2702            }
 2703
 02704            return changed;
 2705        }
 2706
 2707        public ItemLookupInfo ParseName(string name)
 2708        {
 02709            var namingOptions = _namingOptions;
 02710            var result = VideoResolver.CleanDateTime(name, namingOptions);
 2711
 02712            return new ItemLookupInfo
 02713            {
 02714                Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name
 02715                Year = result.Year
 02716            };
 2717        }
 2718
 2719        public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID
 2720        {
 2721            // Apply .ignore rules
 2722            var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
 2723            var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co
 2724            if (ownerVideoInfo is null)
 2725            {
 2726                yield break;
 2727            }
 2728
 2729            var count = filtered.Count;
 2730            for (var i = 0; i < count; i++)
 2731            {
 2732                var current = filtered[i];
 2733                if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
 2734                {
 2735                    var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
 2736                    var filesInSubFolderList = filesInSubFolder.ToList();
 2737
 2738                    bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
 2739
 2740                    foreach (var file in filesInSubFolderList)
 2741                    {
 2742                        if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
 2743                        {
 2744                            continue;
 2745                        }
 2746
 2747                        var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
 2748                        if (extra is not null)
 2749                        {
 2750                            yield return extra;
 2751                        }
 2752                    }
 2753                }
 2754                else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo
 2755                {
 2756                    var extra = GetExtra(current, extraType.Value, false);
 2757                    if (extra is not null)
 2758                    {
 2759                        yield return extra;
 2760                    }
 2761                }
 2762            }
 2763
 2764            BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
 2765            {
 2766                var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso
 2767                if (extra is not Video && extra is not Audio)
 2768                {
 2769                    return null;
 2770                }
 2771
 2772                // Try to retrieve it from the db. If we don't find it, use the resolved version
 2773                var itemById = GetItemById(extra.Id);
 2774                if (itemById is not null)
 2775                {
 2776                    extra = itemById;
 2777                }
 2778
 2779                // Only update extra type if it is more specific then the currently known extra type
 2780                if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
 2781                {
 2782                    extra.ExtraType = extraType;
 2783                }
 2784
 2785                extra.ParentId = Guid.Empty;
 2786                extra.OwnerId = owner.Id;
 2787                extra.IsInMixedFolder = isInMixedFolder;
 2788                return extra;
 2789            }
 2790        }
 2791
 2792        public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
 2793        {
 122794            foreach (var map in _configurationManager.Configuration.PathSubstitutions)
 2795            {
 02796                if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
 2797                {
 02798                    return newPath;
 2799                }
 2800            }
 2801
 62802            return path;
 2803        }
 2804
 2805        public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
 2806        {
 02807            return _peopleRepository.GetPeople(query);
 2808        }
 2809
 2810        public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
 2811        {
 62812            if (item.SupportsPeople)
 2813            {
 02814                var people = GetPeople(new InternalPeopleQuery
 02815                {
 02816                    ItemId = item.Id
 02817                });
 2818
 02819                if (people.Count > 0)
 2820                {
 02821                    return people;
 2822                }
 2823            }
 2824
 62825            return [];
 2826        }
 2827
 2828        public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
 2829        {
 02830            return _peopleRepository.GetPeopleNames(query)
 02831            .Select(i =>
 02832            {
 02833                try
 02834                {
 02835                    return GetPerson(i);
 02836                }
 02837                catch (Exception ex)
 02838                {
 02839                    _logger.LogError(ex, "Error getting person");
 02840                    return null;
 02841                }
 02842            })
 02843            .Where(i => i is not null)
 02844            .Where(i => query.User is null || i!.IsVisible(query.User))
 02845            .ToList()!; // null values are filtered out
 2846        }
 2847
 2848        public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
 2849        {
 02850            return _peopleRepository.GetPeopleNames(query);
 2851        }
 2852
 2853        public void UpdatePeople(BaseItem item, List<PersonInfo> people)
 2854        {
 02855            UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
 02856        }
 2857
 2858        /// <inheritdoc />
 2859        public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat
 2860        {
 2861            if (!item.SupportsPeople)
 2862            {
 2863                return;
 2864            }
 2865
 2866            if (people is not null)
 2867            {
 2868                people = people.Where(e => e is not null).ToArray();
 2869                _peopleRepository.UpdatePeople(item.Id, people);
 2870                await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
 2871            }
 2872        }
 2873
 2874        public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re
 2875        {
 2876            foreach (var url in image.Path.Split('|'))
 2877            {
 2878                try
 2879                {
 2880                    _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
 2881
 2882                    await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure
 2883
 2884                    await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai
 2885
 2886                    return item.GetImageInfo(image.Type, imageIndex);
 2887                }
 2888                catch (HttpRequestException ex)
 2889                {
 2890                    if (ex.StatusCode.HasValue
 2891                        && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb
 2892                    {
 2893                        _logger.LogDebug(ex, "Error downloading image {Url}", url);
 2894                        continue;
 2895                    }
 2896
 2897                    throw;
 2898                }
 2899            }
 2900
 2901            if (removeOnFailure)
 2902            {
 2903                // Remove this image to prevent it from retrying over and over
 2904                item.RemoveImage(image);
 2905                await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa
 2906            }
 2907
 2908            throw new InvalidOperationException("Unable to convert any images to local");
 2909        }
 2910
 2911        public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b
 2912        {
 2913            if (string.IsNullOrWhiteSpace(name))
 2914            {
 2915                throw new ArgumentNullException(nameof(name));
 2916            }
 2917
 2918            name = _fileSystem.GetValidFilename(name.Trim());
 2919
 2920            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 2921
 2922            var existingNameCount = 1; // first numbered name will be 2
 2923            var virtualFolderPath = Path.Combine(rootFolderPath, name);
 2924            var originalName = name;
 2925            while (Directory.Exists(virtualFolderPath))
 2926            {
 2927                existingNameCount++;
 2928                name = originalName + existingNameCount;
 2929                virtualFolderPath = Path.Combine(rootFolderPath, name);
 2930            }
 2931
 2932            var mediaPathInfos = options.PathInfos;
 2933            if (mediaPathInfos is not null)
 2934            {
 2935                var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
 2936                if (invalidpath is not null)
 2937                {
 2938                    throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
 2939                }
 2940            }
 2941
 2942            LibraryMonitor.Stop();
 2943
 2944            try
 2945            {
 2946                Directory.CreateDirectory(virtualFolderPath);
 2947
 2948                if (collectionType is not null)
 2949                {
 2950                    var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect
 2951
 2952                    FileHelper.CreateEmpty(path);
 2953                }
 2954
 2955                CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
 2956
 2957                if (mediaPathInfos is not null)
 2958                {
 2959                    foreach (var path in mediaPathInfos)
 2960                    {
 2961                        AddMediaPathInternal(name, path, false);
 2962                    }
 2963                }
 2964            }
 2965            finally
 2966            {
 2967                if (refreshLibrary)
 2968                {
 2969                    await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
 2970
 2971                    StartScanInBackground();
 2972                }
 2973                else
 2974                {
 2975                    // Need to add a delay here or directory watchers may still pick up the changes
 2976                    await Task.Delay(1000).ConfigureAwait(false);
 2977                    LibraryMonitor.Start();
 2978                }
 2979            }
 2980        }
 2981
 2982        private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
 2983        {
 2984            foreach (var person in people)
 2985            {
 2986                cancellationToken.ThrowIfCancellationRequested();
 2987
 2988                var itemUpdateType = ItemUpdateType.MetadataDownload;
 2989                var saveEntity = false;
 2990                var createEntity = false;
 2991                var personEntity = GetPerson(person.Name);
 2992
 2993                if (personEntity is null)
 2994                {
 2995                    try
 2996                    {
 2997                        var path = Person.GetPath(person.Name);
 2998                        var info = Directory.CreateDirectory(path);
 2999                        personEntity = new Person()
 3000                        {
 3001                            Name = person.Name,
 3002                            Id = GetItemByNameId<Person>(path),
 3003                            DateCreated = info.CreationTimeUtc,
 3004                            DateModified = info.LastWriteTimeUtc,
 3005                            Path = path
 3006                        };
 3007
 3008                        personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
 3009                        saveEntity = true;
 3010                        createEntity = true;
 3011                    }
 3012                    catch (Exception ex)
 3013                    {
 3014                        _logger.LogWarning(ex, "Failed to create person {Name}", person.Name);
 3015                        continue;
 3016                    }
 3017                }
 3018
 3019                foreach (var id in person.ProviderIds)
 3020                {
 3021                    if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)
 3022                    {
 3023                        personEntity.SetProviderId(id.Key, id.Value);
 3024                        saveEntity = true;
 3025                    }
 3026                }
 3027
 3028                if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
 3029                {
 3030                    personEntity.SetImage(
 3031                        new ItemImageInfo
 3032                        {
 3033                            Path = person.ImageUrl,
 3034                            Type = ImageType.Primary
 3035                        },
 3036                        0);
 3037
 3038                    saveEntity = true;
 3039                    itemUpdateType = ItemUpdateType.ImageUpdate;
 3040                }
 3041
 3042                if (saveEntity)
 3043                {
 3044                    if (createEntity)
 3045                    {
 3046                        CreateItems([personEntity], null, CancellationToken.None);
 3047                    }
 3048
 3049                    await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
 3050                    CreateItems([personEntity], null, CancellationToken.None);
 3051                }
 3052            }
 3053        }
 3054
 3055        private void StartScanInBackground()
 3056        {
 33057            Task.Run(() =>
 33058            {
 33059                // No need to start if scanning the library because it will handle it
 33060                ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
 33061            });
 33062        }
 3063
 3064        public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3065        {
 13066            AddMediaPathInternal(virtualFolderName, mediaPath, true);
 03067        }
 3068
 3069        private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
 3070        {
 13071            ArgumentNullException.ThrowIfNull(pathInfo);
 3072
 13073            var path = pathInfo.Path;
 3074
 13075            if (string.IsNullOrWhiteSpace(path))
 3076            {
 03077                throw new ArgumentException(nameof(path));
 3078            }
 3079
 13080            if (!Directory.Exists(path))
 3081            {
 13082                throw new FileNotFoundException("The path does not exist.");
 3083            }
 3084
 03085            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03086            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3087
 03088            var shortcutFilename = Path.GetFileNameWithoutExtension(path);
 3089
 03090            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3091
 03092            while (File.Exists(lnk))
 3093            {
 03094                shortcutFilename += "1";
 03095                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3096            }
 3097
 03098            _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
 3099
 03100            RemoveContentTypeOverrides(path);
 3101
 03102            if (saveLibraryOptions)
 3103            {
 03104                var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3105
 03106                libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
 3107
 03108                SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3109
 03110                CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 3111            }
 03112        }
 3113
 3114        public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3115        {
 03116            ArgumentNullException.ThrowIfNull(mediaPath);
 3117
 03118            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03119            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3120
 03121            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3122
 03123            SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3124
 03125            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03126        }
 3127
 3128        private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
 3129        {
 03130            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 03131            var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
 3132
 03133            if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
 3134            {
 03135                var list = options.PathInfos.ToList();
 3136
 03137                foreach (var location in info.Locations)
 3138                {
 03139                    if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
 3140                    {
 03141                        list.Add(new MediaPathInfo(location));
 3142                    }
 3143                }
 3144
 03145                options.PathInfos = list.ToArray();
 3146            }
 03147        }
 3148
 3149        public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
 3150        {
 3151            if (string.IsNullOrWhiteSpace(name))
 3152            {
 3153                throw new ArgumentNullException(nameof(name));
 3154            }
 3155
 3156            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3157
 3158            var path = Path.Combine(rootFolderPath, name);
 3159
 3160            if (!Directory.Exists(path))
 3161            {
 3162                throw new FileNotFoundException("The media folder does not exist");
 3163            }
 3164
 3165            LibraryMonitor.Stop();
 3166
 3167            try
 3168            {
 3169                Directory.Delete(path, true);
 3170            }
 3171            finally
 3172            {
 3173                CollectionFolder.OnCollectionFolderChange();
 3174
 3175                if (refreshLibrary)
 3176                {
 3177                    await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
 3178
 3179                    StartScanInBackground();
 3180                }
 3181                else
 3182                {
 3183                    // Need to add a delay here or directory watchers may still pick up the changes
 3184                    await Task.Delay(1000).ConfigureAwait(false);
 3185                    LibraryMonitor.Start();
 3186                }
 3187            }
 3188        }
 3189
 3190        private void RemoveContentTypeOverrides(string path)
 3191        {
 03192            if (string.IsNullOrWhiteSpace(path))
 3193            {
 03194                throw new ArgumentNullException(nameof(path));
 3195            }
 3196
 03197            List<NameValuePair>? removeList = null;
 3198
 03199            foreach (var contentType in _configurationManager.Configuration.ContentTypes)
 3200            {
 03201                if (string.IsNullOrWhiteSpace(contentType.Name)
 03202                    || _fileSystem.AreEqual(path, contentType.Name)
 03203                    || _fileSystem.ContainsSubPath(path, contentType.Name))
 3204                {
 03205                    (removeList ??= new()).Add(contentType);
 3206                }
 3207            }
 3208
 03209            if (removeList is not null)
 3210            {
 03211                _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
 03212                    .Except(removeList)
 03213                    .ToArray();
 3214
 03215                _configurationManager.SaveConfiguration();
 3216            }
 03217        }
 3218
 3219        public void RemoveMediaPath(string virtualFolderName, string mediaPath)
 3220        {
 13221            ArgumentException.ThrowIfNullOrEmpty(mediaPath);
 3222
 13223            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 13224            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3225
 13226            if (!Directory.Exists(virtualFolderPath))
 3227            {
 13228                throw new FileNotFoundException(
 13229                    string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder
 3230            }
 3231
 03232            var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
 03233                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 03234                .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String
 3235
 03236            if (!string.IsNullOrEmpty(shortcut))
 3237            {
 03238                _fileSystem.DeleteFile(shortcut);
 3239            }
 3240
 03241            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3242
 03243            libraryOptions.PathInfos = libraryOptions
 03244                .PathInfos
 03245                .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
 03246                .ToArray();
 3247
 03248            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03249        }
 3250
 3251        private static bool ItemIsVisible(BaseItem? item, User? user)
 3252        {
 213253            if (item is null)
 3254            {
 213255                return false;
 3256            }
 3257
 03258            if (user is null)
 3259            {
 03260                return true;
 3261            }
 3262
 03263            return item is UserRootFolder || item.IsVisibleStandalone(user);
 3264        }
 3265    }
 3266}

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)