< 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
34%
Covered lines: 383
Uncovered lines: 731
Coverable lines: 1114
Total lines: 3376
Line coverage: 34.3%
Branch coverage
28%
Covered branches: 177
Total branches: 630
Branch coverage: 28%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 10/1/2025 - 12:09:48 AM Line coverage: 38.6% (428/1107) Branch coverage: 31.9% (200/626) Total lines: 335510/9/2025 - 12:11:25 AM Line coverage: 38.6% (428/1107) Branch coverage: 31.9% (200/626) Total lines: 335710/12/2025 - 12:11:07 AM Line coverage: 34.3% (380/1107) Branch coverage: 27.9% (175/626) Total lines: 335711/18/2025 - 12:11:25 AM Line coverage: 34.4% (383/1113) Branch coverage: 28% (177/630) Total lines: 337512/29/2025 - 12:13:19 AM Line coverage: 34.3% (383/1114) Branch coverage: 28% (177/630) Total lines: 3376 10/1/2025 - 12:09:48 AM Line coverage: 38.6% (428/1107) Branch coverage: 31.9% (200/626) Total lines: 335510/9/2025 - 12:11:25 AM Line coverage: 38.6% (428/1107) Branch coverage: 31.9% (200/626) Total lines: 335710/12/2025 - 12:11:07 AM Line coverage: 34.3% (380/1107) Branch coverage: 27.9% (175/626) Total lines: 335711/18/2025 - 12:11:25 AM Line coverage: 34.4% (383/1113) Branch coverage: 28% (177/630) Total lines: 337512/29/2025 - 12:13:19 AM Line coverage: 34.3% (383/1114) Branch coverage: 28% (177/630) Total lines: 3376

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%
DeleteItemsUnsafeFast(...)0%110100%
DeleteItem(...)0%1190340%
DeleteItemPath(...)0%272160%
IsInternalItem(...)0%342180%
GetMetadataPaths(...)0%620%
GetInternalMetadataPaths(...)0%7280%
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.88%
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%
GetArtists(...)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%
GetItemCounts(...)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(...)91.66%121285.71%
ImageNeedsRefresh(...)0%156120%
UpdateItemAsync(...)100%11100%
ReportItemRemoved(...)0%620%
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            {
 179191                if (_rootFolder is null)
 21192                {
 193                    lock (_rootFolderSyncLock)
 194                    {
 21195                        _rootFolder ??= CreateRootFolder();
 21196                    }
 197                }
 198
 179199                return _rootFolder;
 200            }
 201        }
 202
 41203        private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
 204
 112205        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        {
 180296            ArgumentNullException.ThrowIfNull(item);
 297
 180298            if (item is IItemByName)
 299            {
 0300                if (item is not MusicArtist)
 301                {
 0302                    return;
 303                }
 304            }
 180305            else if (!item.IsFolder)
 306            {
 0307                if (item is not Video && item is not LiveTvChannel)
 308                {
 0309                    return;
 310                }
 311            }
 312
 180313            _cache.AddOrUpdate(item.Id, item);
 180314        }
 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 DeleteItemsUnsafeFast(IEnumerable<BaseItem> items)
 331        {
 0332            var pathMaps = items.Select(e => (Item: e, InternalPath: GetInternalMetadataPaths(e), DeletePaths: e.GetDele
 333
 0334            foreach (var (item, internalPaths, pathsToDelete) in pathMaps)
 335            {
 0336                foreach (var metadataPath in internalPaths)
 337                {
 0338                    if (!Directory.Exists(metadataPath))
 339                    {
 340                        continue;
 341                    }
 342
 0343                    _logger.LogDebug(
 0344                        "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0345                        item.GetType().Name,
 0346                        item.Name ?? "Unknown name",
 0347                        metadataPath,
 0348                        item.Id);
 349
 350                    try
 351                    {
 0352                        Directory.Delete(metadataPath, true);
 0353                    }
 0354                    catch (Exception ex)
 355                    {
 0356                        _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0357                    }
 358                }
 359
 0360                foreach (var fileSystemInfo in pathsToDelete)
 361                {
 0362                    DeleteItemPath(item, false, fileSystemInfo);
 363                }
 364            }
 365
 0366            _itemRepository.DeleteItem([.. pathMaps.Select(f => f.Item.Id)]);
 0367        }
 368
 369        public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem)
 370        {
 0371            ArgumentNullException.ThrowIfNull(item);
 372
 0373            if (item.SourceType == SourceType.Channel)
 374            {
 0375                if (options.DeleteFromExternalProvider)
 376                {
 377                    try
 378                    {
 0379                        BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult();
 0380                    }
 0381                    catch (ArgumentException)
 382                    {
 383                        // channel no longer installed
 0384                    }
 385                }
 386
 0387                options.DeleteFileLocation = false;
 388            }
 389
 0390            if (item is LiveTvProgram)
 391            {
 0392                _logger.LogDebug(
 0393                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0394                    item.GetType().Name,
 0395                    item.Name ?? "Unknown name",
 0396                    item.Path ?? string.Empty,
 0397                    item.Id);
 398            }
 399            else
 400            {
 0401                _logger.LogInformation(
 0402                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0403                    item.GetType().Name,
 0404                    item.Name ?? "Unknown name",
 0405                    item.Path ?? string.Empty,
 0406                    item.Id);
 407            }
 408
 0409            var children = item.IsFolder
 0410                ? ((Folder)item).GetRecursiveChildren(false)
 0411                : [];
 412
 0413            foreach (var metadataPath in GetMetadataPaths(item, children))
 414            {
 0415                if (!Directory.Exists(metadataPath))
 416                {
 417                    continue;
 418                }
 419
 0420                _logger.LogDebug(
 0421                    "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0422                    item.GetType().Name,
 0423                    item.Name ?? "Unknown name",
 0424                    metadataPath,
 0425                    item.Id);
 426
 427                try
 428                {
 0429                    Directory.Delete(metadataPath, true);
 0430                }
 0431                catch (Exception ex)
 432                {
 0433                    _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0434                }
 435            }
 436
 0437            if ((options.DeleteFileLocation && item.IsFileProtocol) || IsInternalItem(item))
 438            {
 439                // Assume only the first is required
 440                // Add this flag to GetDeletePaths if required in the future
 0441                var isRequiredForDelete = true;
 442
 0443                foreach (var fileSystemInfo in item.GetDeletePaths())
 444                {
 0445                    DeleteItemPath(item, isRequiredForDelete, fileSystemInfo);
 446
 0447                    isRequiredForDelete = false;
 448                }
 449            }
 450
 0451            item.SetParent(null);
 452
 0453            _itemRepository.DeleteItem([item.Id, .. children.Select(f => f.Id)]);
 0454            _cache.TryRemove(item.Id, out _);
 0455            foreach (var child in children)
 456            {
 0457                _cache.TryRemove(child.Id, out _);
 458            }
 459
 0460            if (parent is Folder folder)
 461            {
 0462                folder.Children = null;
 0463                folder.UserData = null;
 464            }
 465
 0466            ReportItemRemoved(item, parent);
 0467        }
 468
 469        private void DeleteItemPath(BaseItem item, bool isRequiredForDelete, FileSystemMetadata fileSystemInfo)
 470        {
 0471            if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
 472            {
 473                try
 474                {
 0475                    _logger.LogInformation(
 0476                        "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0477                        item.GetType().Name,
 0478                        item.Name ?? "Unknown name",
 0479                        fileSystemInfo.FullName,
 0480                        item.Id);
 481
 0482                    if (fileSystemInfo.IsDirectory)
 483                    {
 0484                        Directory.Delete(fileSystemInfo.FullName, true);
 485                    }
 486                    else
 487                    {
 0488                        File.Delete(fileSystemInfo.FullName);
 489                    }
 0490                }
 0491                catch (DirectoryNotFoundException)
 492                {
 0493                    _logger.LogInformation(
 0494                        "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id:
 0495                        item.GetType().Name,
 0496                        item.Name ?? "Unknown name",
 0497                        fileSystemInfo.FullName,
 0498                        item.Id);
 0499                }
 0500                catch (FileNotFoundException)
 501                {
 0502                    _logger.LogInformation(
 0503                        "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}
 0504                        item.GetType().Name,
 0505                        item.Name ?? "Unknown name",
 0506                        fileSystemInfo.FullName,
 0507                        item.Id);
 0508                }
 0509                catch (IOException)
 510                {
 0511                    if (isRequiredForDelete)
 512                    {
 0513                        throw;
 514                    }
 0515                }
 0516                catch (UnauthorizedAccessException)
 517                {
 0518                    if (isRequiredForDelete)
 519                    {
 0520                        throw;
 521                    }
 0522                }
 523            }
 0524        }
 525
 526        private bool IsInternalItem(BaseItem item)
 527        {
 0528            if (!item.IsFileProtocol)
 529            {
 0530                return false;
 531            }
 532
 0533            var pathToCheck = item switch
 0534            {
 0535                Genre => _configurationManager.ApplicationPaths.GenrePath,
 0536                MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath,
 0537                MusicGenre => _configurationManager.ApplicationPaths.MusicGenrePath,
 0538                Person => _configurationManager.ApplicationPaths.PeoplePath,
 0539                Studio => _configurationManager.ApplicationPaths.StudioPath,
 0540                Year => _configurationManager.ApplicationPaths.YearPath,
 0541                _ => null
 0542            };
 543
 0544            var itemPath = item.Path;
 0545            if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath))
 546            {
 0547                var cleanPath = _fileSystem.GetValidFilename(itemPath);
 0548                var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck);
 549
 0550                return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal);
 551            }
 552
 0553            return false;
 554        }
 555
 556        private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
 557        {
 0558            var list = GetInternalMetadataPaths(item);
 0559            foreach (var child in children)
 560            {
 0561                list.AddRange(GetInternalMetadataPaths(child));
 562            }
 563
 0564            return list;
 565        }
 566
 567        private List<string> GetInternalMetadataPaths(BaseItem item)
 568        {
 0569            var list = new List<string>
 0570            {
 0571                item.GetInternalMetadataPath()
 0572            };
 573
 0574            if (item is Video video)
 575            {
 576                // Trickplay
 0577                list.Add(_pathManager.GetTrickplayDirectory(video));
 578
 579                // Subtitles and attachments
 0580                foreach (var mediaSource in item.GetMediaSources(false))
 581                {
 0582                    var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id);
 0583                    if (subtitleFolder is not null)
 584                    {
 0585                        list.Add(subtitleFolder);
 586                    }
 587
 0588                    var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0589                    if (attachmentFolder is not null)
 590                    {
 0591                        list.Add(attachmentFolder);
 592                    }
 593                }
 594            }
 595
 0596            return list;
 597        }
 598
 599        /// <summary>
 600        /// Resolves the item.
 601        /// </summary>
 602        /// <param name="args">The args.</param>
 603        /// <param name="resolvers">The resolvers.</param>
 604        /// <returns>BaseItem.</returns>
 605        private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers)
 606        {
 76607            var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r))
 76608                .FirstOrDefault(i => i is not null);
 609
 76610            if (item is not null)
 611            {
 66612                ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
 613            }
 614
 76615            return item;
 616        }
 617
 618        private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver)
 619        {
 620            try
 621            {
 304622                return resolver.ResolvePath(args);
 623            }
 0624            catch (Exception ex)
 625            {
 0626                _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path);
 0627                return null;
 628            }
 304629        }
 630
 631        public Guid GetNewItemId(string key, Type type)
 632        {
 129633            return GetNewItemIdInternal(key, type, false);
 634        }
 635
 636        private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
 637        {
 130638            ArgumentException.ThrowIfNullOrEmpty(key);
 130639            ArgumentNullException.ThrowIfNull(type);
 640
 130641            string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
 130642            if (key.StartsWith(programDataPath, StringComparison.Ordinal))
 643            {
 644                // Try to normalize paths located underneath program-data in an attempt to make them more portable
 113645                key = key.Substring(programDataPath.Length)
 113646                    .TrimStart('/', '\\')
 113647                    .Replace('/', '\\');
 648            }
 649
 130650            if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
 651            {
 1652                key = key.ToLowerInvariant();
 653            }
 654
 130655            key = type.FullName + key;
 656
 130657            return key.GetMD5();
 658        }
 659
 660        public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directorySer
 42661            => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent);
 662
 663        private BaseItem? ResolvePath(
 664            FileSystemMetadata fileInfo,
 665            IDirectoryService directoryService,
 666            IItemResolver[]? resolvers,
 667            Folder? parent = null,
 668            CollectionType? collectionType = null,
 669            LibraryOptions? libraryOptions = null)
 670        {
 76671            ArgumentNullException.ThrowIfNull(fileInfo);
 672
 76673            var fullPath = fileInfo.FullName;
 674
 76675            if (collectionType is null && parent is not null)
 676            {
 17677                collectionType = GetContentTypeOverride(fullPath, true);
 678            }
 679
 76680            var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this)
 76681            {
 76682                Parent = parent,
 76683                FileInfo = fileInfo,
 76684                CollectionType = collectionType,
 76685                LibraryOptions = libraryOptions
 76686            };
 687
 688            // Return null if ignore rules deem that we should do so
 76689            if (IgnoreFile(args.FileInfo, args.Parent))
 690            {
 0691                return null;
 692            }
 693
 694            // Gather child folder and files
 76695            if (args.IsDirectory)
 696            {
 49697                var isPhysicalRoot = args.IsPhysicalRoot;
 698
 699                // When resolving the root, we need it's grandchildren (children of user views)
 49700                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
 701
 702                FileSystemMetadata[] files;
 49703                var isVf = args.IsVf;
 704
 705                try
 706                {
 49707                    files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l
 49708                }
 0709                catch (Exception ex)
 710                {
 0711                    if (parent is not null && parent.IsPhysicalRoot)
 712                    {
 0713                        _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPh
 714
 0715                        files = [];
 716                    }
 717                    else
 718                    {
 0719                        throw;
 720                    }
 0721                }
 722
 723                // Need to remove sub-paths that may have been resolved from shortcuts
 724                // Example: if \\server\movies exists, then strip out \\server\movies\action
 49725                if (isPhysicalRoot)
 726                {
 21727                    files = NormalizeRootPathList(files).ToArray();
 728                }
 729
 49730                args.FileSystemChildren = files;
 731            }
 732
 733            // Filter content based on ignore rules
 76734            if (args.IsDirectory)
 735            {
 49736                var filtered = args.GetActualFileSystemChildren().ToArray();
 49737                args.FileSystemChildren = filtered ?? [];
 738            }
 739
 76740            return ResolveItem(args, resolvers);
 741        }
 742
 743        public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
 100744            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 745
 746        public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
 747        {
 81748            var originalList = paths.ToList();
 749
 81750            var list = originalList.Where(i => i.IsDirectory)
 81751                .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
 81752                .Distinct()
 81753                .ToList();
 754
 81755            var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS
 81756                .ToList();
 757
 162758            foreach (var dupe in dupes)
 759            {
 0760                _logger.LogInformation("Found duplicate path: {0}", dupe);
 761            }
 762
 81763            var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
 81764            newList.AddRange(originalList.Where(i => !i.IsDirectory));
 81765            return newList;
 766        }
 767
 768        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ
 769        {
 60770            return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
 771        }
 772
 773        public IEnumerable<BaseItem> ResolvePaths(
 774            IEnumerable<FileSystemMetadata> files,
 775            IDirectoryService directoryService,
 776            Folder parent,
 777            LibraryOptions libraryOptions,
 778            CollectionType? collectionType,
 779            IItemResolver[] resolvers)
 780        {
 60781            var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
 782
 60783            if (parent is not null)
 784            {
 60785                var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>()
 786
 360787                foreach (var resolver in multiItemResolvers)
 788                {
 120789                    var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
 790
 120791                    if (result?.Items.Count > 0)
 792                    {
 0793                        var items = result.Items;
 0794                        items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryServic
 0795                        items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, reso
 0796                        return items;
 797                    }
 798                }
 799            }
 800
 60801            return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
 0802        }
 803
 804        private IEnumerable<BaseItem> ResolveFileList(
 805            IReadOnlyList<FileSystemMetadata> fileList,
 806            IDirectoryService directoryService,
 807            Folder? parent,
 808            CollectionType? collectionType,
 809            IItemResolver[]? resolvers,
 810            LibraryOptions libraryOptions)
 811        {
 812            // Given that fileList is a list we can save enumerator allocations by indexing
 813            for (var i = 0; i < fileList.Count; i++)
 814            {
 815                var file = fileList[i];
 816                BaseItem? result = null;
 817                try
 818                {
 819                    result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
 820                }
 821                catch (Exception ex)
 822                {
 823                    _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
 824                }
 825
 826                if (result is not null)
 827                {
 828                    yield return result;
 829                }
 830            }
 831        }
 832
 833        /// <summary>
 834        /// Creates the root media folder.
 835        /// </summary>
 836        /// <returns>AggregateFolder.</returns>
 837        /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</except
 838        public AggregateFolder CreateRootFolder()
 839        {
 21840            var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
 841
 21842            var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
 21843                             (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOp
 21844                             .DeepCopy<Folder, AggregateFolder>();
 845
 846            // In case program data folder was moved
 21847            if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
 848            {
 0849                _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
 0850                rootFolder.Path = rootFolderPath;
 851            }
 852
 853            // Add in the plug-in folders
 21854            var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
 855
 21856            var info = Directory.CreateDirectory(path);
 21857            Folder folder = new PlaylistsFolder
 21858            {
 21859                Path = path,
 21860                DateCreated = info.CreationTimeUtc,
 21861                DateModified = info.LastWriteTimeUtc,
 21862            };
 863
 21864            if (folder.Id.IsEmpty())
 865            {
 21866                folder.Id = GetNewItemId(folder.Path, folder.GetType());
 867            }
 868
 21869            var dbItem = GetItemById(folder.Id) as BasePluginFolder;
 870
 21871            if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
 872            {
 0873                folder = dbItem;
 874            }
 875
 21876            if (!folder.ParentId.Equals(rootFolder.Id))
 877            {
 21878                rootFolder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().G
 21879                folder.ParentId = rootFolder.Id;
 21880                folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetRe
 881            }
 882
 21883            rootFolder.AddVirtualChild(folder);
 884
 21885            RegisterItem(folder);
 886
 21887            return rootFolder;
 888        }
 889
 890        public Folder GetUserRootFolder()
 891        {
 919892            if (_userRootFolder is null)
 21893            {
 894                lock (_userRootFolderSyncLock)
 895                {
 21896                    if (_userRootFolder is null)
 897                    {
 21898                        var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 899
 21900                        _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
 21901                        Directory.CreateDirectory(userRootPath);
 902
 21903                        var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
 21904                        UserRootFolder? tmpItem = null;
 905                        try
 906                        {
 21907                            tmpItem = GetItemById(newItemId) as UserRootFolder;
 21908                        }
 0909                        catch (Exception ex)
 910                        {
 0911                            _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
 0912                        }
 913
 21914                        if (tmpItem is null)
 915                        {
 21916                            _logger.LogDebug("Creating new userRootFolder with DeepCopy");
 21917                            tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new In
 21918                                        .DeepCopy<Folder, UserRootFolder>();
 919                        }
 920
 921                        // In case program data folder was moved
 21922                        if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
 923                        {
 0924                            _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
 0925                            tmpItem.Path = userRootPath;
 926                        }
 927
 21928                        _userRootFolder = tmpItem;
 21929                        _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
 930                    }
 21931                }
 932            }
 933
 919934            return _userRootFolder;
 935        }
 936
 937        /// <inheritdoc />
 938        public BaseItem? FindByPath(string path, bool? isFolder)
 939        {
 940            // If this returns multiple items it could be tricky figuring out which one is correct.
 941            // In most cases, the newest one will be and the others obsolete but not yet cleaned up
 0942            ArgumentException.ThrowIfNullOrEmpty(path);
 943
 0944            var query = new InternalItemsQuery
 0945            {
 0946                Path = path,
 0947                IsFolder = isFolder,
 0948                OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
 0949                Limit = 1,
 0950                DtoOptions = new DtoOptions(true)
 0951            };
 952
 0953            return GetItemList(query)
 0954                .FirstOrDefault();
 955        }
 956
 957        /// <inheritdoc />
 958        public Person? GetPerson(string name)
 959        {
 1960            var path = Person.GetPath(name);
 1961            var id = GetItemByNameId<Person>(path);
 1962            if (GetItemById(id) is Person item)
 963            {
 0964                return item;
 965            }
 966
 1967            return null;
 968        }
 969
 970        /// <summary>
 971        /// Gets the studio.
 972        /// </summary>
 973        /// <param name="name">The name.</param>
 974        /// <returns>Task{Studio}.</returns>
 975        public Studio GetStudio(string name)
 976        {
 0977            return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
 978        }
 979
 980        public Guid GetStudioId(string name)
 981        {
 0982            return GetItemByNameId<Studio>(Studio.GetPath(name));
 983        }
 984
 985        public Guid GetGenreId(string name)
 986        {
 0987            return GetItemByNameId<Genre>(Genre.GetPath(name));
 988        }
 989
 990        public Guid GetMusicGenreId(string name)
 991        {
 0992            return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
 993        }
 994
 995        /// <summary>
 996        /// Gets the genre.
 997        /// </summary>
 998        /// <param name="name">The name.</param>
 999        /// <returns>Task{Genre}.</returns>
 1000        public Genre GetGenre(string name)
 1001        {
 01002            return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
 1003        }
 1004
 1005        /// <summary>
 1006        /// Gets the music genre.
 1007        /// </summary>
 1008        /// <param name="name">The name.</param>
 1009        /// <returns>Task{MusicGenre}.</returns>
 1010        public MusicGenre GetMusicGenre(string name)
 1011        {
 01012            return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
 1013        }
 1014
 1015        /// <summary>
 1016        /// Gets the year.
 1017        /// </summary>
 1018        /// <param name="value">The value.</param>
 1019        /// <returns>Task{Year}.</returns>
 1020        public Year GetYear(int value)
 1021        {
 01022            if (value <= 0)
 1023            {
 01024                throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
 1025            }
 1026
 01027            var name = value.ToString(CultureInfo.InvariantCulture);
 1028
 01029            return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
 1030        }
 1031
 1032        /// <summary>
 1033        /// Gets a Genre.
 1034        /// </summary>
 1035        /// <param name="name">The name.</param>
 1036        /// <returns>Task{Genre}.</returns>
 1037        public MusicArtist GetArtist(string name)
 1038        {
 01039            return GetArtist(name, new DtoOptions(true));
 1040        }
 1041
 1042        public IReadOnlyDictionary<string, MusicArtist[]> GetArtists(IReadOnlyList<string> names)
 1043        {
 01044            return _itemRepository.FindArtists(names);
 1045        }
 1046
 1047        public MusicArtist GetArtist(string name, DtoOptions options)
 1048        {
 01049            return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
 1050        }
 1051
 1052        private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
 1053            where T : BaseItem, new()
 1054        {
 01055            if (typeof(T) == typeof(MusicArtist))
 1056            {
 01057                var existing = GetItemList(new InternalItemsQuery
 01058                {
 01059                    IncludeItemTypes = [BaseItemKind.MusicArtist],
 01060                    Name = name,
 01061                    UseRawName = true,
 01062                    DtoOptions = options
 01063                }).Cast<MusicArtist>()
 01064                .OrderBy(i => i.IsAccessedByName ? 1 : 0)
 01065                .Cast<T>()
 01066                .FirstOrDefault();
 1067
 01068                if (existing is not null)
 1069                {
 01070                    return existing;
 1071                }
 1072            }
 1073
 01074            var path = getPathFn(name);
 01075            var id = GetItemByNameId<T>(path);
 01076            var item = GetItemById(id) as T;
 01077            if (item is null)
 1078            {
 01079                var info = Directory.CreateDirectory(path);
 01080                item = new T
 01081                {
 01082                    Name = name,
 01083                    Id = id,
 01084                    DateCreated = info.CreationTimeUtc,
 01085                    DateModified = info.LastWriteTimeUtc,
 01086                    Path = path
 01087                };
 1088
 01089                CreateItem(item, null);
 1090            }
 1091
 01092            return item;
 1093        }
 1094
 1095        private Guid GetItemByNameId<T>(string path)
 1096              where T : BaseItem, new()
 1097        {
 11098            var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
 11099            return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
 1100        }
 1101
 1102        /// <inheritdoc />
 1103        public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
 1104        {
 1105            // Ensure the location is available.
 01106            Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
 1107
 01108            return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
 1109        }
 1110
 1111        /// <summary>
 1112        /// Reloads the root media folder.
 1113        /// </summary>
 1114        /// <param name="progress">The progress.</param>
 1115        /// <param name="cancellationToken">The cancellation token.</param>
 1116        /// <returns>Task.</returns>
 1117        public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
 1118        {
 1119            // Just run the scheduled task so that the user can see it
 31120            _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
 1121
 31122            return Task.CompletedTask;
 1123        }
 1124
 1125        /// <summary>
 1126        /// Validates the media library internal.
 1127        /// </summary>
 1128        /// <param name="progress">The progress.</param>
 1129        /// <param name="cancellationToken">The cancellation token.</param>
 1130        /// <returns>Task.</returns>
 1131        public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
 1132        {
 1133            IsScanRunning = true;
 1134            LibraryMonitor.Stop();
 1135
 1136            try
 1137            {
 1138                await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
 1139            }
 1140            finally
 1141            {
 1142                LibraryMonitor.Start();
 1143                IsScanRunning = false;
 1144            }
 1145        }
 1146
 1147        public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
 1148        {
 1149            RootFolder.Children = null;
 1150            await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1151
 1152            // Start by just validating the children of the root, but go no further
 1153            await RootFolder.ValidateChildren(
 1154                new Progress<double>(),
 1155                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1156                recursive: false,
 1157                allowRemoveRoot: removeRoot,
 1158                cancellationToken: cancellationToken).ConfigureAwait(false);
 1159
 1160            var rootFolder = GetUserRootFolder();
 1161            rootFolder.Children = null;
 1162
 1163            await rootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1164
 1165            await rootFolder.ValidateChildren(
 1166                new Progress<double>(),
 1167                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1168                recursive: false,
 1169                allowRemoveRoot: removeRoot,
 1170                cancellationToken: cancellationToken).ConfigureAwait(false);
 1171
 1172            // Quickly scan CollectionFolders for changes
 1173            var toDelete = new List<Guid>();
 1174            foreach (var child in rootFolder.Children!.OfType<Folder>())
 1175            {
 1176                // If the user has somehow deleted the collection directory, remove the metadata from the database.
 1177                if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
 1178                {
 1179                    toDelete.Add(collectionFolder.Id);
 1180                }
 1181                else
 1182                {
 1183                    await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1184                }
 1185            }
 1186
 1187            if (toDelete.Count > 0)
 1188            {
 1189                _itemRepository.DeleteItem(toDelete.ToArray());
 1190            }
 1191        }
 1192
 1193        private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
 1194        {
 1195            _logger.LogInformation("Validating media library");
 1196
 1197            await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
 1198
 1199            var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
 1200
 1201            // Validate the entire media library
 1202            await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem
 1203
 1204            progress.Report(96);
 1205
 1206            innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
 1207
 1208            await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
 1209
 1210            progress.Report(100);
 1211        }
 1212
 1213        /// <summary>
 1214        /// Runs the post scan tasks.
 1215        /// </summary>
 1216        /// <param name="progress">The progress.</param>
 1217        /// <param name="cancellationToken">The cancellation token.</param>
 1218        /// <returns>Task.</returns>
 1219        private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
 1220        {
 1221            var tasks = PostScanTasks.ToList();
 1222
 1223            var numComplete = 0;
 1224            var numTasks = tasks.Count;
 1225
 1226            foreach (var task in tasks)
 1227            {
 1228                // Prevent access to modified closure
 1229                var currentNumComplete = numComplete;
 1230
 1231                var innerProgress = new Progress<double>(pct =>
 1232                {
 1233                    double innerPercent = pct;
 1234                    innerPercent /= 100;
 1235                    innerPercent += currentNumComplete;
 1236
 1237                    innerPercent /= numTasks;
 1238                    innerPercent *= 100;
 1239
 1240                    progress.Report(innerPercent);
 1241                });
 1242
 1243                _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
 1244
 1245                try
 1246                {
 1247                    await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
 1248                }
 1249                catch (OperationCanceledException)
 1250                {
 1251                    _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
 1252                    throw;
 1253                }
 1254                catch (Exception ex)
 1255                {
 1256                    _logger.LogError(ex, "Error running post-scan task");
 1257                }
 1258
 1259                numComplete++;
 1260                double percent = numComplete;
 1261                percent /= numTasks;
 1262                progress.Report(percent * 100);
 1263            }
 1264
 1265            _itemRepository.UpdateInheritedValues();
 1266
 1267            progress.Report(100);
 1268        }
 1269
 1270        /// <summary>
 1271        /// Gets the default view.
 1272        /// </summary>
 1273        /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
 1274        public List<VirtualFolderInfo> GetVirtualFolders()
 1275        {
 231276            return GetVirtualFolders(false);
 1277        }
 1278
 1279        public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
 1280        {
 241281            _logger.LogDebug("Getting topLibraryFolders");
 241282            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 1283
 241284            _logger.LogDebug("Getting refreshQueue");
 241285            var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
 1286
 241287            return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
 241288                .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
 241289                .ToList();
 1290        }
 1291
 1292        private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? r
 1293        {
 11294            var info = new VirtualFolderInfo
 11295            {
 11296                Name = Path.GetFileName(dir),
 11297
 11298                Locations = _fileSystem.GetFilePaths(dir, false)
 11299                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 11300                    .Select(i =>
 11301                    {
 11302                        try
 11303                        {
 11304                            return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
 11305                        }
 11306                        catch (Exception ex)
 11307                        {
 11308                            _logger.LogError(ex, "Error resolving shortcut file {File}", i);
 11309                            return null;
 11310                        }
 11311                    })
 11312                    .Where(i => i is not null)
 11313                    .Order()
 11314                    .ToArray(),
 11315
 11316                CollectionType = GetCollectionType(dir)
 11317            };
 1318
 11319            var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.Ord
 11320            if (libraryFolder is not null)
 1321            {
 11322                var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
 11323                info.ItemId = libraryFolderId;
 11324                if (libraryFolder.HasImage(ImageType.Primary))
 1325                {
 01326                    info.PrimaryImageItemId = libraryFolderId;
 1327                }
 1328
 11329                info.LibraryOptions = GetLibraryOptions(libraryFolder);
 1330
 11331                if (refreshQueue is not null)
 1332                {
 11333                    info.RefreshProgress = libraryFolder.GetRefreshProgress();
 1334
 11335                    info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.
 1336                }
 1337            }
 1338
 11339            return info;
 1340        }
 1341
 1342        private CollectionTypeOptions? GetCollectionType(string path)
 1343        {
 11344            var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
 21345            foreach (ReadOnlySpan<char> file in files)
 1346            {
 01347                if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
 1348                {
 01349                    return res;
 1350                }
 1351            }
 1352
 11353            return null;
 01354        }
 1355
 1356        /// <inheritdoc />
 1357        public BaseItem? GetItemById(Guid id)
 1358        {
 5461359            if (id.IsEmpty())
 1360            {
 01361                throw new ArgumentException("Guid can't be empty", nameof(id));
 1362            }
 1363
 5461364            if (_cache.TryGet(id, out var item))
 1365            {
 4431366                return item;
 1367            }
 1368
 1031369            item = RetrieveItem(id);
 1370
 1031371            if (item is not null)
 1372            {
 01373                RegisterItem(item);
 1374            }
 1375
 1031376            return item;
 1377        }
 1378
 1379        /// <inheritdoc />
 1380        public T? GetItemById<T>(Guid id)
 1381            where T : BaseItem
 1382        {
 231383            var item = GetItemById(id);
 231384            if (item is T typedItem)
 1385            {
 11386                return typedItem;
 1387            }
 1388
 221389            return null;
 1390        }
 1391
 1392        /// <inheritdoc />
 1393        public T? GetItemById<T>(Guid id, Guid userId)
 1394            where T : BaseItem
 1395        {
 11396            var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
 11397            return GetItemById<T>(id, user);
 1398        }
 1399
 1400        /// <inheritdoc />
 1401        public T? GetItemById<T>(Guid id, User? user)
 1402            where T : BaseItem
 1403        {
 211404            var item = GetItemById<T>(id);
 211405            return ItemIsVisible(item, user) ? item : null;
 1406        }
 1407
 1408        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
 1409        {
 1201410            if (query.Recursive && !query.ParentId.IsEmpty())
 1411            {
 451412                var parent = GetItemById(query.ParentId);
 451413                if (parent is not null)
 1414                {
 451415                    SetTopParentIdsOrAncestors(query, [parent]);
 1416                }
 1417            }
 1418
 1201419            if (query.User is not null)
 1420            {
 11421                AddUserToQuery(query, query.User, allowExternalContent);
 1422            }
 1423
 1201424            var itemList = _itemRepository.GetItemList(query);
 1201425            var user = query.User;
 1201426            if (user is not null)
 1427            {
 11428                return itemList.Where(i => i.IsVisible(user)).ToList();
 1429            }
 1430
 1191431            return itemList;
 1432        }
 1433
 1434        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 1435        {
 1201436            return GetItemList(query, true);
 1437        }
 1438
 1439        public int GetCount(InternalItemsQuery query)
 1440        {
 01441            if (query.Recursive && !query.ParentId.IsEmpty())
 1442            {
 01443                var parent = GetItemById(query.ParentId);
 01444                if (parent is not null)
 1445                {
 01446                    SetTopParentIdsOrAncestors(query, [parent]);
 1447                }
 1448            }
 1449
 01450            if (query.User is not null)
 1451            {
 01452                AddUserToQuery(query, query.User);
 1453            }
 1454
 01455            return _itemRepository.GetCount(query);
 1456        }
 1457
 1458        public ItemCounts GetItemCounts(InternalItemsQuery query)
 1459        {
 01460            if (query.Recursive && !query.ParentId.IsEmpty())
 1461            {
 01462                var parent = GetItemById(query.ParentId);
 01463                if (parent is not null)
 1464                {
 01465                    SetTopParentIdsOrAncestors(query, [parent]);
 1466                }
 1467            }
 1468
 01469            if (query.User is not null)
 1470            {
 01471                AddUserToQuery(query, query.User);
 1472            }
 1473
 01474            return _itemRepository.GetItemCounts(query);
 1475        }
 1476
 1477        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
 1478        {
 01479            SetTopParentIdsOrAncestors(query, parents);
 1480
 01481            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1482            {
 01483                if (query.User is not null)
 1484                {
 01485                    AddUserToQuery(query, query.User);
 1486                }
 1487            }
 1488
 01489            return _itemRepository.GetItemList(query);
 1490        }
 1491
 1492        public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, Coll
 1493        {
 01494            SetTopParentIdsOrAncestors(query, parents);
 1495
 01496            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1497            {
 01498                if (query.User is not null)
 1499                {
 01500                    AddUserToQuery(query, query.User);
 1501                }
 1502            }
 1503
 01504            return _itemRepository.GetLatestItemList(query, collectionType);
 1505        }
 1506
 1507        public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents
 1508        {
 01509            SetTopParentIdsOrAncestors(query, parents);
 1510
 01511            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1512            {
 01513                if (query.User is not null)
 1514                {
 01515                    AddUserToQuery(query, query.User);
 1516                }
 1517            }
 1518
 01519            return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
 1520        }
 1521
 1522        public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
 1523        {
 01524            if (query.User is not null)
 1525            {
 01526                AddUserToQuery(query, query.User);
 1527            }
 1528
 01529            if (query.EnableTotalRecordCount)
 1530            {
 01531                return _itemRepository.GetItems(query);
 1532            }
 1533
 01534            return new QueryResult<BaseItem>(
 01535                query.StartIndex,
 01536                null,
 01537                _itemRepository.GetItemList(query));
 1538        }
 1539
 1540        public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
 1541        {
 171542            if (query.User is not null)
 1543            {
 01544                AddUserToQuery(query, query.User);
 1545            }
 1546
 171547            return _itemRepository.GetItemIdsList(query);
 1548        }
 1549
 1550        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
 1551        {
 01552            if (query.User is not null)
 1553            {
 01554                AddUserToQuery(query, query.User);
 1555            }
 1556
 01557            SetTopParentOrAncestorIds(query);
 01558            return _itemRepository.GetStudios(query);
 1559        }
 1560
 1561        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
 1562        {
 01563            if (query.User is not null)
 1564            {
 01565                AddUserToQuery(query, query.User);
 1566            }
 1567
 01568            SetTopParentOrAncestorIds(query);
 01569            return _itemRepository.GetGenres(query);
 1570        }
 1571
 1572        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
 1573        {
 01574            if (query.User is not null)
 1575            {
 01576                AddUserToQuery(query, query.User);
 1577            }
 1578
 01579            SetTopParentOrAncestorIds(query);
 01580            return _itemRepository.GetMusicGenres(query);
 1581        }
 1582
 1583        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
 1584        {
 01585            if (query.User is not null)
 1586            {
 01587                AddUserToQuery(query, query.User);
 1588            }
 1589
 01590            SetTopParentOrAncestorIds(query);
 01591            return _itemRepository.GetAllArtists(query);
 1592        }
 1593
 1594        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
 1595        {
 01596            if (query.User is not null)
 1597            {
 01598                AddUserToQuery(query, query.User);
 1599            }
 1600
 01601            SetTopParentOrAncestorIds(query);
 01602            return _itemRepository.GetArtists(query);
 1603        }
 1604
 1605        private void SetTopParentOrAncestorIds(InternalItemsQuery query)
 1606        {
 01607            var ancestorIds = query.AncestorIds;
 01608            int len = ancestorIds.Length;
 01609            if (len == 0)
 1610            {
 01611                return;
 1612            }
 1613
 01614            var parents = new BaseItem[len];
 01615            for (int i = 0; i < len; i++)
 1616            {
 01617                parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id:
 01618                if (parents[i] is not (ICollectionFolder or UserView))
 1619                {
 01620                    return;
 1621                }
 1622            }
 1623
 1624            // Optimize by querying against top level views
 01625            query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 01626            query.AncestorIds = [];
 1627
 1628            // Prevent searching in all libraries due to empty filter
 01629            if (query.TopParentIds.Length == 0)
 1630            {
 01631                query.TopParentIds = [Guid.NewGuid()];
 1632            }
 01633        }
 1634
 1635        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
 1636        {
 01637            if (query.User is not null)
 1638            {
 01639                AddUserToQuery(query, query.User);
 1640            }
 1641
 01642            SetTopParentOrAncestorIds(query);
 01643            return _itemRepository.GetAlbumArtists(query);
 1644        }
 1645
 1646        public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
 1647        {
 121648            if (query.Recursive && !query.ParentId.IsEmpty())
 1649            {
 111650                var parent = GetItemById(query.ParentId);
 111651                if (parent is not null)
 1652                {
 111653                    SetTopParentIdsOrAncestors(query, [parent]);
 1654                }
 1655            }
 1656
 121657            if (query.User is not null)
 1658            {
 11659                AddUserToQuery(query, query.User);
 1660            }
 1661
 121662            if (query.EnableTotalRecordCount)
 1663            {
 11664                return _itemRepository.GetItems(query);
 1665            }
 1666
 111667            return new QueryResult<BaseItem>(
 111668                query.StartIndex,
 111669                null,
 111670                _itemRepository.GetItemList(query));
 1671        }
 1672
 1673        private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
 1674        {
 561675            if (parents.All(i => i is ICollectionFolder || i is UserView))
 1676            {
 1677                // Optimize by querying against top level views
 111678                query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 1679
 1680                // Prevent searching in all libraries due to empty filter
 111681                if (query.TopParentIds.Length == 0)
 1682                {
 111683                    query.TopParentIds = [Guid.NewGuid()];
 1684                }
 1685            }
 1686            else
 1687            {
 1688                // We need to be able to query from any arbitrary ancestor up the tree
 451689                query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
 1690
 1691                // Prevent searching in all libraries due to empty filter
 451692                if (query.AncestorIds.Length == 0)
 1693                {
 01694                    query.AncestorIds = [Guid.NewGuid()];
 1695                }
 1696            }
 1697
 561698            query.Parent = null;
 561699        }
 1700
 1701        private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
 1702        {
 21703            if (query.AncestorIds.Length == 0 &&
 21704                query.ParentId.IsEmpty() &&
 21705                query.ChannelIds.Count == 0 &&
 21706                query.TopParentIds.Length == 0 &&
 21707                string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
 21708                string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
 21709                query.ItemIds.Length == 0)
 1710            {
 11711                var userViews = UserViewManager.GetUserViews(new UserViewQuery
 11712                {
 11713                    User = user,
 11714                    IncludeHidden = true,
 11715                    IncludeExternalContent = allowExternalContent
 11716                });
 1717
 11718                query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
 1719
 1720                // Prevent searching in all libraries due to empty filter
 11721                if (query.TopParentIds.Length == 0)
 1722                {
 11723                    query.TopParentIds = [Guid.NewGuid()];
 1724                }
 1725            }
 21726        }
 1727
 1728        private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
 1729        {
 111730            if (item is UserView view)
 1731            {
 01732                if (view.ViewType == CollectionType.livetv)
 1733                {
 01734                    return [view.Id];
 1735                }
 1736
 1737                // Translate view into folders
 01738                if (!view.DisplayParentId.IsEmpty())
 1739                {
 01740                    var displayParent = GetItemById(view.DisplayParentId);
 01741                    if (displayParent is not null)
 1742                    {
 01743                        return GetTopParentIdsForQuery(displayParent, user);
 1744                    }
 1745
 01746                    return [];
 1747                }
 1748
 01749                if (!view.ParentId.IsEmpty())
 1750                {
 01751                    var displayParent = GetItemById(view.ParentId);
 01752                    if (displayParent is not null)
 1753                    {
 01754                        return GetTopParentIdsForQuery(displayParent, user);
 1755                    }
 1756
 01757                    return [];
 1758                }
 1759
 1760                // Handle grouping
 01761                if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.V
 01762                    && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
 1763                {
 01764                    return GetUserRootFolder()
 01765                        .GetChildren(user, true)
 01766                        .OfType<CollectionFolder>()
 01767                        .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
 01768                        .Where(i => user.IsFolderGrouped(i.Id))
 01769                        .SelectMany(i => GetTopParentIdsForQuery(i, user));
 1770                }
 1771
 01772                return [];
 1773            }
 1774
 111775            if (item is CollectionFolder collectionFolder)
 1776            {
 111777                return collectionFolder.PhysicalFolderIds;
 1778            }
 1779
 01780            var topParent = item.GetTopParent();
 01781            if (topParent is not null)
 1782            {
 01783                return [topParent.Id];
 1784            }
 1785
 01786            return [];
 1787        }
 1788
 1789        /// <summary>
 1790        /// Gets the intros.
 1791        /// </summary>
 1792        /// <param name="item">The item.</param>
 1793        /// <param name="user">The user.</param>
 1794        /// <returns>IEnumerable{System.String}.</returns>
 1795        public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
 1796        {
 1797            if (IntroProviders.Length == 0)
 1798            {
 1799                return [];
 1800            }
 1801
 1802            var tasks = IntroProviders
 1803                .Select(i => GetIntros(i, item, user));
 1804
 1805            var items = await Task.WhenAll(tasks).ConfigureAwait(false);
 1806
 1807            return items
 1808                .SelectMany(i => i)
 1809                .Select(ResolveIntro)
 1810                .Where(i => i is not null)!; // null values got filtered out
 1811        }
 1812
 1813        /// <summary>
 1814        /// Gets the intros.
 1815        /// </summary>
 1816        /// <param name="provider">The provider.</param>
 1817        /// <param name="item">The item.</param>
 1818        /// <param name="user">The user.</param>
 1819        /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
 1820        private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
 1821        {
 1822            try
 1823            {
 1824                return await provider.GetIntros(item, user).ConfigureAwait(false);
 1825            }
 1826            catch (Exception ex)
 1827            {
 1828                _logger.LogError(ex, "Error getting intros");
 1829
 1830                return [];
 1831            }
 1832        }
 1833
 1834        /// <summary>
 1835        /// Resolves the intro.
 1836        /// </summary>
 1837        /// <param name="info">The info.</param>
 1838        /// <returns>Video.</returns>
 1839        private Video? ResolveIntro(IntroInfo info)
 1840        {
 01841            Video? video = null;
 1842
 01843            if (info.ItemId.HasValue)
 1844            {
 1845                // Get an existing item by Id
 01846                video = GetItemById(info.ItemId.Value) as Video;
 1847
 01848                if (video is null)
 1849                {
 01850                    _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
 1851                }
 1852            }
 01853            else if (!string.IsNullOrEmpty(info.Path))
 1854            {
 1855                try
 1856                {
 1857                    // Try to resolve the path into a video
 01858                    video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
 1859
 01860                    if (video is null)
 1861                    {
 01862                        _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
 1863                    }
 1864                    else
 1865                    {
 1866                        // Pull the saved db item that will include metadata
 01867                        var dbItem = GetItemById(video.Id) as Video;
 1868
 01869                        if (dbItem is not null)
 1870                        {
 01871                            video = dbItem;
 1872                        }
 1873                        else
 1874                        {
 01875                            return null;
 1876                        }
 1877                    }
 01878                }
 01879                catch (Exception ex)
 1880                {
 01881                    _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
 01882                }
 1883            }
 1884            else
 1885            {
 01886                _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
 1887            }
 1888
 01889            return video;
 01890        }
 1891
 1892        /// <inheritdoc />
 1893        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortO
 1894        {
 11895            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1896
 41897            foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
 1898            {
 11899                if (orderBy is RandomComparer)
 1900                {
 01901                    var randomItems = items.ToArray();
 01902                    Random.Shared.Shuffle(randomItems);
 01903                    items = randomItems;
 1904                    // Items are no longer ordered at this point, so set orderedItems back to null
 01905                    orderedItems = null;
 1906                }
 11907                else if (orderedItems is null)
 1908                {
 11909                    orderedItems = sortOrder == SortOrder.Descending
 11910                        ? items.OrderByDescending(i => i, orderBy)
 11911                        : items.OrderBy(i => i, orderBy);
 1912                }
 1913                else
 1914                {
 01915                    orderedItems = sortOrder == SortOrder.Descending
 01916                        ? orderedItems!.ThenByDescending(i => i, orderBy)
 01917                        : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
 1918                }
 1919            }
 1920
 11921            return orderedItems ?? items;
 1922        }
 1923
 1924        /// <inheritdoc />
 1925        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, Sort
 1926        {
 01927            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1928
 01929            foreach (var (name, sortOrder) in orderBy)
 1930            {
 01931                var comparer = GetComparer(name, user);
 01932                if (comparer is null)
 1933                {
 1934                    continue;
 1935                }
 1936
 01937                if (comparer is RandomComparer)
 1938                {
 01939                    var randomItems = items.ToArray();
 01940                    Random.Shared.Shuffle(randomItems);
 01941                    items = randomItems;
 1942                    // Items are no longer ordered at this point, so set orderedItems back to null
 01943                    orderedItems = null;
 1944                }
 01945                else if (orderedItems is null)
 1946                {
 01947                    orderedItems = sortOrder == SortOrder.Descending
 01948                        ? items.OrderByDescending(i => i, comparer)
 01949                        : items.OrderBy(i => i, comparer);
 1950                }
 1951                else
 1952                {
 01953                    orderedItems = sortOrder == SortOrder.Descending
 01954                        ? orderedItems!.ThenByDescending(i => i, comparer)
 01955                        : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
 1956                }
 1957            }
 1958
 01959            return orderedItems ?? items;
 1960        }
 1961
 1962        /// <summary>
 1963        /// Gets the comparer.
 1964        /// </summary>
 1965        /// <param name="name">The name.</param>
 1966        /// <param name="user">The user.</param>
 1967        /// <returns>IBaseItemComparer.</returns>
 1968        private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
 1969        {
 11970            var comparer = Comparers.FirstOrDefault(c => name == c.Type);
 1971
 1972            // If it requires a user, create a new one, and assign the user
 11973            if (comparer is IUserBaseItemComparer)
 1974            {
 01975                var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null fo
 1976
 01977                userComparer.User = user;
 01978                userComparer.UserManager = _userManager;
 01979                userComparer.UserDataManager = _userDataManager;
 1980
 01981                return userComparer;
 1982            }
 1983
 11984            return comparer;
 1985        }
 1986
 1987        /// <inheritdoc />
 1988        public void CreateItem(BaseItem item, BaseItem? parent)
 1989        {
 01990            CreateItems([item], parent, CancellationToken.None);
 01991        }
 1992
 1993        /// <inheritdoc />
 1994        public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
 1995        {
 21996            _itemRepository.SaveItems(items, cancellationToken);
 1997
 81998            foreach (var item in items)
 1999            {
 22000                RegisterItem(item);
 2001            }
 2002
 22003            if (parent is Folder folder)
 2004            {
 22005                folder.Children = null;
 22006                folder.UserData = null;
 2007            }
 2008
 22009            if (ItemAdded is not null)
 2010            {
 82011                foreach (var item in items)
 2012                {
 2013                    // With the live tv guide this just creates too much noise
 22014                    if (item.SourceType != SourceType.Library)
 2015                    {
 2016                        continue;
 2017                    }
 2018
 2019                    try
 2020                    {
 22021                        ItemAdded(
 22022                            this,
 22023                            new ItemChangeEventArgs
 22024                            {
 22025                                Item = item,
 22026                                Parent = parent ?? item.GetParent()
 22027                            });
 22028                    }
 02029                    catch (Exception ex)
 2030                    {
 02031                        _logger.LogError(ex, "Error in ItemAdded event handler");
 02032                    }
 2033                }
 2034            }
 22035        }
 2036
 2037        private bool ImageNeedsRefresh(ItemImageInfo image)
 2038        {
 02039            if (image.Path is not null && image.IsLocalFile)
 2040            {
 02041                if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
 2042                {
 02043                    return true;
 2044                }
 2045
 2046                try
 2047                {
 02048                    return image.DateModified.Subtract(_fileSystem.GetLastWriteTimeUtc(image.Path)).Duration().TotalSeco
 2049                }
 02050                catch (Exception ex)
 2051                {
 02052                    _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
 02053                    return false;
 2054                }
 2055            }
 2056
 02057            return image.Path is not null && !image.IsLocalFile;
 02058        }
 2059
 2060        /// <inheritdoc />
 2061        public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
 2062        {
 2063            ArgumentNullException.ThrowIfNull(item);
 2064
 2065            var outdated = forceUpdate
 2066                ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
 2067                : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
 2068            // Skip image processing if current or live tv source
 2069            if (outdated.Length == 0 || item.SourceType != SourceType.Library)
 2070            {
 2071                RegisterItem(item);
 2072                return;
 2073            }
 2074
 2075            foreach (var img in outdated)
 2076            {
 2077                var image = img;
 2078                if (!img.IsLocalFile)
 2079                {
 2080                    try
 2081                    {
 2082                        var index = item.GetImageIndex(img);
 2083                        image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
 2084                    }
 2085                    catch (ArgumentException)
 2086                    {
 2087                        _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
 2088                        continue;
 2089                    }
 2090                    catch (Exception ex) when (ex is InvalidOperationException or IOException)
 2091                    {
 2092                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
 2093                        continue;
 2094                    }
 2095                    catch (HttpRequestException ex)
 2096                    {
 2097                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", im
 2098                        continue;
 2099                    }
 2100                }
 2101
 2102                if (!File.Exists(image.Path))
 2103                {
 2104                    _logger.LogWarning("Image not found at {ImagePath}", image.Path);
 2105                    continue;
 2106                }
 2107
 2108                ImageDimensions size;
 2109                try
 2110                {
 2111                    size = _imageProcessor.GetImageDimensions(item, image);
 2112                    image.Width = size.Width;
 2113                    image.Height = size.Height;
 2114                }
 2115                catch (Exception ex)
 2116                {
 2117                    _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
 2118                    size = default;
 2119                    image.Width = 0;
 2120                    image.Height = 0;
 2121                }
 2122
 2123                try
 2124                {
 2125                    var blurhash = _imageProcessor.GetImageBlurHash(image.Path, size);
 2126                    image.BlurHash = blurhash;
 2127                }
 2128                catch (Exception ex)
 2129                {
 2130                    _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
 2131                    image.BlurHash = string.Empty;
 2132                }
 2133
 2134                try
 2135                {
 2136                    var modifiedDate = _fileSystem.GetLastWriteTimeUtc(image.Path);
 2137                    image.DateModified = modifiedDate;
 2138                }
 2139                catch (Exception ex)
 2140                {
 2141                    _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
 2142                }
 2143            }
 2144
 2145            item.ValidateImages();
 2146
 2147            await _itemRepository.SaveImagesAsync(item).ConfigureAwait(false);
 2148
 2149            RegisterItem(item);
 2150        }
 2151
 2152        /// <inheritdoc />
 2153        public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, 
 2154        {
 2155            foreach (var item in items)
 2156            {
 2157                item.DateLastSaved = DateTime.UtcNow;
 2158                await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
 2159
 2160                // Modify again, so saved value is after write time of externally saved metadata
 2161                item.DateLastSaved = DateTime.UtcNow;
 2162            }
 2163
 2164            _itemRepository.SaveItems(items, cancellationToken);
 2165
 2166            if (parent is Folder folder)
 2167            {
 2168                folder.Children = null;
 2169                folder.UserData = null;
 2170            }
 2171
 2172            if (ItemUpdated is not null)
 2173            {
 2174                foreach (var item in items)
 2175                {
 2176                    // With the live tv guide this just creates too much noise
 2177                    if (item.SourceType != SourceType.Library)
 2178                    {
 2179                        continue;
 2180                    }
 2181
 2182                    try
 2183                    {
 2184                        ItemUpdated(
 2185                            this,
 2186                            new ItemChangeEventArgs
 2187                            {
 2188                                Item = item,
 2189                                Parent = parent,
 2190                                UpdateReason = updateReason
 2191                            });
 2192                    }
 2193                    catch (Exception ex)
 2194                    {
 2195                        _logger.LogError(ex, "Error in ItemUpdated event handler");
 2196                    }
 2197                }
 2198            }
 2199        }
 2200
 2201        /// <inheritdoc />
 2202        public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance
 1112203            => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
 2204
 2205        public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
 2206        {
 2207            if (item.IsFileProtocol)
 2208            {
 2209                await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
 2210            }
 2211
 2212            await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
 2213        }
 2214
 2215        /// <summary>
 2216        /// Reports the item removed.
 2217        /// </summary>
 2218        /// <param name="item">The item.</param>
 2219        /// <param name="parent">The parent item.</param>
 2220        public void ReportItemRemoved(BaseItem item, BaseItem parent)
 2221        {
 02222            if (ItemRemoved is not null)
 2223            {
 2224                try
 2225                {
 02226                    ItemRemoved(
 02227                        this,
 02228                        new ItemChangeEventArgs
 02229                        {
 02230                            Item = item,
 02231                            Parent = parent
 02232                        });
 02233                }
 02234                catch (Exception ex)
 2235                {
 02236                    _logger.LogError(ex, "Error in ItemRemoved event handler");
 02237                }
 2238            }
 02239        }
 2240
 2241        /// <summary>
 2242        /// Retrieves the item.
 2243        /// </summary>
 2244        /// <param name="id">The id.</param>
 2245        /// <returns>BaseItem.</returns>
 2246        public BaseItem RetrieveItem(Guid id)
 2247        {
 1032248            return _itemRepository.RetrieveItem(id);
 2249        }
 2250
 2251        public List<Folder> GetCollectionFolders(BaseItem item)
 2252        {
 7972253            return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
 2254        }
 2255
 2256        public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2257        {
 8312258            while (item is not null)
 2259            {
 8312260                var parent = item.GetParent();
 2261
 8312262                if (parent is AggregateFolder)
 2263                {
 2264                    break;
 2265                }
 2266
 7382267                if (parent is null)
 2268                {
 7042269                    var owner = item.GetOwner();
 2270
 7042271                    if (owner is null)
 2272                    {
 2273                        break;
 2274                    }
 2275
 02276                    item = owner;
 2277                }
 2278                else
 2279                {
 342280                    item = parent;
 2281                }
 2282            }
 2283
 7972284            if (item is null)
 2285            {
 02286                return new List<Folder>();
 2287            }
 2288
 7972289            return GetCollectionFoldersInternal(item, allUserRootChildren);
 2290        }
 2291
 2292        private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2293        {
 7972294            return allUserRootChildren
 7972295                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 7972296                .ToList();
 2297        }
 2298
 2299        public LibraryOptions GetLibraryOptions(BaseItem item)
 2300        {
 4982301            if (item is CollectionFolder collectionFolder)
 2302            {
 502303                return collectionFolder.GetLibraryOptions();
 2304            }
 2305
 2306            // List.Find is more performant than FirstOrDefault due to enumerator allocation
 4482307            return GetCollectionFolders(item)
 4482308                .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
 4482309                ? collectionFolder2.GetLibraryOptions()
 4482310                : new LibraryOptions();
 2311        }
 2312
 2313        public CollectionType? GetContentType(BaseItem item)
 2314        {
 602315            var configuredContentType = GetConfiguredContentType(item, false);
 602316            if (configuredContentType is not null)
 2317            {
 02318                return configuredContentType;
 2319            }
 2320
 602321            configuredContentType = GetConfiguredContentType(item, true);
 602322            if (configuredContentType is not null)
 2323            {
 02324                return configuredContentType;
 2325            }
 2326
 602327            return GetInheritedContentType(item);
 2328        }
 2329
 2330        public CollectionType? GetInheritedContentType(BaseItem item)
 2331        {
 602332            var type = GetTopFolderContentType(item);
 2333
 602334            if (type is not null)
 2335            {
 02336                return type;
 2337            }
 2338
 602339            return item.GetParents()
 602340                .Select(GetConfiguredContentType)
 602341                .LastOrDefault(i => i is not null);
 2342        }
 2343
 2344        public CollectionType? GetConfiguredContentType(BaseItem item)
 2345        {
 02346            return GetConfiguredContentType(item, false);
 2347        }
 2348
 2349        public CollectionType? GetConfiguredContentType(string path)
 2350        {
 02351            return GetContentTypeOverride(path, false);
 2352        }
 2353
 2354        public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
 2355        {
 1202356            if (item is ICollectionFolder collectionFolder)
 2357            {
 02358                return collectionFolder.CollectionType;
 2359            }
 2360
 1202361            return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
 2362        }
 2363
 2364        private CollectionType? GetContentTypeOverride(string path, bool inherit)
 2365        {
 1372366            var nameValuePair = _configurationManager.Configuration.ContentTypes
 1372367                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
 1372368                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
 1372369                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
 1372370            if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
 2371            {
 02372                return collectionType;
 2373            }
 2374
 1372375            return null;
 2376        }
 2377
 2378        private CollectionType? GetTopFolderContentType(BaseItem item)
 2379        {
 602380            if (item is null)
 2381            {
 02382                return null;
 2383            }
 2384
 602385            while (!item.ParentId.IsEmpty())
 2386            {
 02387                var parent = item.GetParent();
 02388                if (parent is null || parent is AggregateFolder)
 2389                {
 2390                    break;
 2391                }
 2392
 02393                item = parent;
 2394            }
 2395
 602396            return GetUserRootFolder().Children
 602397                .OfType<ICollectionFolder>()
 602398                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 602399                .Select(i => i.CollectionType)
 602400                .FirstOrDefault(i => i is not null);
 2401        }
 2402
 2403        public UserView GetNamedView(
 2404            User user,
 2405            string name,
 2406            CollectionType? viewType,
 2407            string sortName)
 2408        {
 02409            return GetNamedView(user, name, Guid.Empty, viewType, sortName);
 2410        }
 2411
 2412        public UserView GetNamedView(
 2413            string name,
 2414            CollectionType viewType,
 2415            string sortName)
 2416        {
 02417            var path = Path.Combine(
 02418                _configurationManager.ApplicationPaths.InternalMetadataPath,
 02419                "views",
 02420                _fileSystem.GetValidFilename(viewType.ToString()));
 2421
 02422            var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 2423
 02424            var item = GetItemById(id) as UserView;
 2425
 02426            var refresh = false;
 2427
 02428            if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
 2429            {
 02430                var info = Directory.CreateDirectory(path);
 02431                item = new UserView
 02432                {
 02433                    Path = path,
 02434                    Id = id,
 02435                    DateCreated = info.CreationTimeUtc,
 02436                    DateModified = info.LastWriteTimeUtc,
 02437                    Name = name,
 02438                    ViewType = viewType,
 02439                    ForcedSortName = sortName
 02440                };
 2441
 02442                CreateItem(item, null);
 2443
 02444                refresh = true;
 2445            }
 2446
 02447            if (refresh)
 2448            {
 02449                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu
 02450                ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref
 2451            }
 2452
 02453            return item;
 2454        }
 2455
 2456        public UserView GetNamedView(
 2457            User user,
 2458            string name,
 2459            Guid parentId,
 2460            CollectionType? viewType,
 2461            string sortName)
 2462        {
 02463            var parentIdString = parentId.IsEmpty()
 02464                ? null
 02465                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02466            var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin
 2467
 02468            var id = GetNewItemId(idValues, typeof(UserView));
 2469
 02470            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2471
 02472            var item = GetItemById(id) as UserView;
 2473
 02474            var isNew = false;
 2475
 02476            if (item is null)
 2477            {
 02478                var info = Directory.CreateDirectory(path);
 02479                item = new UserView
 02480                {
 02481                    Path = path,
 02482                    Id = id,
 02483                    DateCreated = info.CreationTimeUtc,
 02484                    DateModified = info.LastWriteTimeUtc,
 02485                    Name = name,
 02486                    ViewType = viewType,
 02487                    ForcedSortName = sortName,
 02488                    UserId = user.Id,
 02489                    DisplayParentId = parentId
 02490                };
 2491
 02492                CreateItem(item, null);
 2493
 02494                isNew = true;
 2495            }
 2496
 02497            var lastRefreshedUtc = item.DateLastRefreshed;
 02498            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2499
 02500            if (!refresh && !item.DisplayParentId.IsEmpty())
 2501            {
 02502                var displayParent = GetItemById(item.DisplayParentId);
 02503                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2504            }
 2505
 02506            if (refresh)
 2507            {
 02508                ProviderManager.QueueRefresh(
 02509                    item.Id,
 02510                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02511                    {
 02512                        // Need to force save to increment DateLastSaved
 02513                        ForceSave = true
 02514                    },
 02515                    RefreshPriority.Normal);
 2516            }
 2517
 02518            return item;
 2519        }
 2520
 2521        public UserView GetShadowView(
 2522            BaseItem parent,
 2523            CollectionType? viewType,
 2524            string sortName)
 2525        {
 02526            ArgumentNullException.ThrowIfNull(parent);
 2527
 02528            var name = parent.Name;
 02529            var parentId = parent.Id;
 2530
 02531            var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
 2532
 02533            var id = GetNewItemId(idValues, typeof(UserView));
 2534
 02535            var path = parent.Path;
 2536
 02537            var item = GetItemById(id) as UserView;
 2538
 02539            var isNew = false;
 2540
 02541            if (item is null)
 2542            {
 02543                var info = Directory.CreateDirectory(path);
 02544                item = new UserView
 02545                {
 02546                    Path = path,
 02547                    Id = id,
 02548                    DateCreated = info.CreationTimeUtc,
 02549                    DateModified = info.LastWriteTimeUtc,
 02550                    Name = name,
 02551                    ViewType = viewType,
 02552                    ForcedSortName = sortName,
 02553                    DisplayParentId = parentId
 02554                };
 2555
 02556                CreateItem(item, null);
 2557
 02558                isNew = true;
 2559            }
 2560
 02561            var lastRefreshedUtc = item.DateLastRefreshed;
 02562            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2563
 02564            if (!refresh && !item.DisplayParentId.IsEmpty())
 2565            {
 02566                var displayParent = GetItemById(item.DisplayParentId);
 02567                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2568            }
 2569
 02570            if (refresh)
 2571            {
 02572                ProviderManager.QueueRefresh(
 02573                    item.Id,
 02574                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02575                    {
 02576                        // Need to force save to increment DateLastSaved
 02577                        ForceSave = true
 02578                    },
 02579                    RefreshPriority.Normal);
 2580            }
 2581
 02582            return item;
 2583        }
 2584
 2585        public UserView GetNamedView(
 2586            string name,
 2587            Guid parentId,
 2588            CollectionType? viewType,
 2589            string sortName,
 2590            string uniqueId)
 2591        {
 02592            ArgumentException.ThrowIfNullOrEmpty(name);
 2593
 02594            var parentIdString = parentId.IsEmpty()
 02595                ? null
 02596                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02597            var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E
 02598            if (!string.IsNullOrEmpty(uniqueId))
 2599            {
 02600                idValues += uniqueId;
 2601            }
 2602
 02603            var id = GetNewItemId(idValues, typeof(UserView));
 2604
 02605            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2606
 02607            var item = GetItemById(id) as UserView;
 2608
 02609            var isNew = false;
 2610
 02611            if (item is null)
 2612            {
 02613                var info = Directory.CreateDirectory(path);
 02614                item = new UserView
 02615                {
 02616                    Path = path,
 02617                    Id = id,
 02618                    DateCreated = info.CreationTimeUtc,
 02619                    DateModified = info.LastWriteTimeUtc,
 02620                    Name = name,
 02621                    ViewType = viewType,
 02622                    ForcedSortName = sortName,
 02623                    DisplayParentId = parentId
 02624                };
 2625
 02626                CreateItem(item, null);
 2627
 02628                isNew = true;
 2629            }
 2630
 02631            if (viewType != item.ViewType)
 2632            {
 02633                item.ViewType = viewType;
 02634                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult
 2635            }
 2636
 02637            var lastRefreshedUtc = item.DateLastRefreshed;
 02638            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2639
 02640            if (!refresh && !item.DisplayParentId.IsEmpty())
 2641            {
 02642                var displayParent = GetItemById(item.DisplayParentId);
 02643                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2644            }
 2645
 02646            if (refresh)
 2647            {
 02648                ProviderManager.QueueRefresh(
 02649                    item.Id,
 02650                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02651                    {
 02652                        // Need to force save to increment DateLastSaved
 02653                        ForceSave = true
 02654                    },
 02655                    RefreshPriority.Normal);
 2656            }
 2657
 02658            return item;
 2659        }
 2660
 2661        public BaseItem GetParentItem(Guid? parentId, Guid? userId)
 2662        {
 32663            if (parentId.HasValue)
 2664            {
 02665                return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}"
 2666            }
 2667
 32668            if (!userId.IsNullOrEmpty())
 2669            {
 32670                return GetUserRootFolder();
 2671            }
 2672
 02673            return RootFolder;
 2674        }
 2675
 2676        /// <inheritdoc />
 2677        public void QueueLibraryScan()
 2678        {
 02679            _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
 02680        }
 2681
 2682        /// <inheritdoc />
 2683        public int? GetSeasonNumberFromPath(string path, Guid? parentId)
 2684        {
 02685            var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
 02686            return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
 2687        }
 2688
 2689        /// <inheritdoc />
 2690        public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
 2691        {
 02692            var series = episode.Series;
 02693            bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis
 02694            if (!isAbsoluteNaming.Value)
 2695            {
 2696                // In other words, no filter applied
 02697                isAbsoluteNaming = null;
 2698            }
 2699
 02700            var resolver = new EpisodeResolver(_namingOptions);
 2701
 02702            var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
 2703
 02704            EpisodeInfo? episodeInfo = null;
 02705            if (episode.IsFileProtocol)
 2706            {
 02707                episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
 2708                // Resolve from parent folder if it's not the Season folder
 02709                var parent = episode.GetParent();
 02710                if (episodeInfo is null && parent.GetType() == typeof(Folder))
 2711                {
 02712                    episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
 02713                    if (episodeInfo is not null)
 2714                    {
 2715                        // add the container
 02716                        episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
 2717                    }
 2718                }
 2719            }
 2720
 02721            var changed = false;
 02722            if (episodeInfo is null)
 2723            {
 02724                return changed;
 2725            }
 2726
 02727            if (episodeInfo.IsByDate)
 2728            {
 02729                if (episode.IndexNumber.HasValue)
 2730                {
 02731                    episode.IndexNumber = null;
 02732                    changed = true;
 2733                }
 2734
 02735                if (episode.IndexNumberEnd.HasValue)
 2736                {
 02737                    episode.IndexNumberEnd = null;
 02738                    changed = true;
 2739                }
 2740
 02741                if (!episode.PremiereDate.HasValue)
 2742                {
 02743                    if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
 2744                    {
 02745                        episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo
 2746                    }
 2747
 02748                    if (episode.PremiereDate.HasValue)
 2749                    {
 02750                        changed = true;
 2751                    }
 2752                }
 2753
 02754                if (!episode.ProductionYear.HasValue)
 2755                {
 02756                    episode.ProductionYear = episodeInfo.Year;
 2757
 02758                    if (episode.ProductionYear.HasValue)
 2759                    {
 02760                        changed = true;
 2761                    }
 2762                }
 2763            }
 2764            else
 2765            {
 02766                if (!episode.IndexNumber.HasValue || forceRefresh)
 2767                {
 02768                    if (episode.IndexNumber != episodeInfo.EpisodeNumber)
 2769                    {
 02770                        changed = true;
 2771                    }
 2772
 02773                    episode.IndexNumber = episodeInfo.EpisodeNumber;
 2774                }
 2775
 02776                if (!episode.IndexNumberEnd.HasValue || forceRefresh)
 2777                {
 02778                    if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
 2779                    {
 02780                        changed = true;
 2781                    }
 2782
 02783                    episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
 2784                }
 2785
 02786                if (!episode.ParentIndexNumber.HasValue || forceRefresh)
 2787                {
 02788                    if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
 2789                    {
 02790                        changed = true;
 2791                    }
 2792
 02793                    episode.ParentIndexNumber = episodeInfo.SeasonNumber;
 2794                }
 2795            }
 2796
 02797            if (!episode.ParentIndexNumber.HasValue)
 2798            {
 02799                var season = episode.Season;
 2800
 02801                if (season is not null)
 2802                {
 02803                    episode.ParentIndexNumber = season.IndexNumber;
 2804                }
 2805
 02806                if (episode.ParentIndexNumber.HasValue)
 2807                {
 02808                    changed = true;
 2809                }
 2810            }
 2811
 02812            return changed;
 2813        }
 2814
 2815        public ItemLookupInfo ParseName(string name)
 2816        {
 02817            var namingOptions = _namingOptions;
 02818            var result = VideoResolver.CleanDateTime(name, namingOptions);
 2819
 02820            return new ItemLookupInfo
 02821            {
 02822                Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name
 02823                Year = result.Year
 02824            };
 2825        }
 2826
 2827        public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID
 2828        {
 2829            // Apply .ignore rules
 2830            var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
 2831            var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co
 2832            if (ownerVideoInfo is null)
 2833            {
 2834                yield break;
 2835            }
 2836
 2837            var count = filtered.Count;
 2838            for (var i = 0; i < count; i++)
 2839            {
 2840                var current = filtered[i];
 2841                if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
 2842                {
 2843                    var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
 2844                    var filesInSubFolderList = filesInSubFolder.ToList();
 2845
 2846                    bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
 2847
 2848                    foreach (var file in filesInSubFolderList)
 2849                    {
 2850                        if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
 2851                        {
 2852                            continue;
 2853                        }
 2854
 2855                        var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
 2856                        if (extra is not null)
 2857                        {
 2858                            yield return extra;
 2859                        }
 2860                    }
 2861                }
 2862                else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo
 2863                {
 2864                    var extra = GetExtra(current, extraType.Value, false);
 2865                    if (extra is not null)
 2866                    {
 2867                        yield return extra;
 2868                    }
 2869                }
 2870            }
 2871
 2872            BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
 2873            {
 2874                var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso
 2875                if (extra is not Video && extra is not Audio)
 2876                {
 2877                    return null;
 2878                }
 2879
 2880                // Try to retrieve it from the db. If we don't find it, use the resolved version
 2881                var itemById = GetItemById(extra.Id);
 2882                if (itemById is not null)
 2883                {
 2884                    extra = itemById;
 2885                }
 2886
 2887                // Only update extra type if it is more specific then the currently known extra type
 2888                if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
 2889                {
 2890                    extra.ExtraType = extraType;
 2891                }
 2892
 2893                extra.ParentId = Guid.Empty;
 2894                extra.OwnerId = owner.Id;
 2895                extra.IsInMixedFolder = isInMixedFolder;
 2896                return extra;
 2897            }
 2898        }
 2899
 2900        public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
 2901        {
 122902            foreach (var map in _configurationManager.Configuration.PathSubstitutions)
 2903            {
 02904                if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
 2905                {
 02906                    return newPath;
 2907                }
 2908            }
 2909
 62910            return path;
 2911        }
 2912
 2913        public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
 2914        {
 02915            return _peopleRepository.GetPeople(query);
 2916        }
 2917
 2918        public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
 2919        {
 62920            if (item.SupportsPeople)
 2921            {
 02922                var people = GetPeople(new InternalPeopleQuery
 02923                {
 02924                    ItemId = item.Id
 02925                });
 2926
 02927                if (people.Count > 0)
 2928                {
 02929                    return people;
 2930                }
 2931            }
 2932
 62933            return [];
 2934        }
 2935
 2936        public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
 2937        {
 02938            return _peopleRepository.GetPeopleNames(query)
 02939            .Select(i =>
 02940            {
 02941                try
 02942                {
 02943                    return GetPerson(i);
 02944                }
 02945                catch (Exception ex)
 02946                {
 02947                    _logger.LogError(ex, "Error getting person");
 02948                    return null;
 02949                }
 02950            })
 02951            .Where(i => i is not null)
 02952            .Where(i => query.User is null || i!.IsVisible(query.User))
 02953            .ToList()!; // null values are filtered out
 2954        }
 2955
 2956        public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
 2957        {
 02958            return _peopleRepository.GetPeopleNames(query);
 2959        }
 2960
 2961        public void UpdatePeople(BaseItem item, List<PersonInfo> people)
 2962        {
 02963            UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
 02964        }
 2965
 2966        /// <inheritdoc />
 2967        public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat
 2968        {
 2969            if (!item.SupportsPeople)
 2970            {
 2971                return;
 2972            }
 2973
 2974            if (people is not null)
 2975            {
 2976                people = people.Where(e => e is not null).ToArray();
 2977                _peopleRepository.UpdatePeople(item.Id, people);
 2978                await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
 2979            }
 2980        }
 2981
 2982        public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re
 2983        {
 2984            foreach (var url in image.Path.Split('|'))
 2985            {
 2986                try
 2987                {
 2988                    _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
 2989
 2990                    await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure
 2991
 2992                    await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai
 2993
 2994                    return item.GetImageInfo(image.Type, imageIndex);
 2995                }
 2996                catch (HttpRequestException ex)
 2997                {
 2998                    if (ex.StatusCode.HasValue
 2999                        && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb
 3000                    {
 3001                        _logger.LogDebug(ex, "Error downloading image {Url}", url);
 3002                        continue;
 3003                    }
 3004
 3005                    throw;
 3006                }
 3007            }
 3008
 3009            if (removeOnFailure)
 3010            {
 3011                // Remove this image to prevent it from retrying over and over
 3012                item.RemoveImage(image);
 3013                await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa
 3014            }
 3015
 3016            throw new InvalidOperationException("Unable to convert any images to local");
 3017        }
 3018
 3019        public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b
 3020        {
 3021            if (string.IsNullOrWhiteSpace(name))
 3022            {
 3023                throw new ArgumentNullException(nameof(name));
 3024            }
 3025
 3026            name = _fileSystem.GetValidFilename(name.Trim());
 3027
 3028            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3029
 3030            var existingNameCount = 1; // first numbered name will be 2
 3031            var virtualFolderPath = Path.Combine(rootFolderPath, name);
 3032            var originalName = name;
 3033            while (Directory.Exists(virtualFolderPath))
 3034            {
 3035                existingNameCount++;
 3036                name = originalName + existingNameCount;
 3037                virtualFolderPath = Path.Combine(rootFolderPath, name);
 3038            }
 3039
 3040            var mediaPathInfos = options.PathInfos;
 3041            if (mediaPathInfos is not null)
 3042            {
 3043                var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
 3044                if (invalidpath is not null)
 3045                {
 3046                    throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
 3047                }
 3048            }
 3049
 3050            LibraryMonitor.Stop();
 3051
 3052            try
 3053            {
 3054                Directory.CreateDirectory(virtualFolderPath);
 3055
 3056                if (collectionType is not null)
 3057                {
 3058                    var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect
 3059
 3060                    FileHelper.CreateEmpty(path);
 3061                }
 3062
 3063                CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
 3064
 3065                if (mediaPathInfos is not null)
 3066                {
 3067                    foreach (var path in mediaPathInfos)
 3068                    {
 3069                        AddMediaPathInternal(name, path, false);
 3070                    }
 3071                }
 3072            }
 3073            finally
 3074            {
 3075                await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
 3076
 3077                if (refreshLibrary)
 3078                {
 3079                    StartScanInBackground();
 3080                }
 3081                else
 3082                {
 3083                    // Need to add a delay here or directory watchers may still pick up the changes
 3084                    await Task.Delay(1000).ConfigureAwait(false);
 3085                    LibraryMonitor.Start();
 3086                }
 3087            }
 3088        }
 3089
 3090        private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
 3091        {
 3092            foreach (var person in people)
 3093            {
 3094                cancellationToken.ThrowIfCancellationRequested();
 3095
 3096                var itemUpdateType = ItemUpdateType.MetadataDownload;
 3097                var saveEntity = false;
 3098                var createEntity = false;
 3099                var personEntity = GetPerson(person.Name);
 3100
 3101                if (personEntity is null)
 3102                {
 3103                    try
 3104                    {
 3105                        var path = Person.GetPath(person.Name);
 3106                        var info = Directory.CreateDirectory(path);
 3107                        personEntity = new Person()
 3108                        {
 3109                            Name = person.Name,
 3110                            Id = GetItemByNameId<Person>(path),
 3111                            DateCreated = info.CreationTimeUtc,
 3112                            DateModified = info.LastWriteTimeUtc,
 3113                            Path = path
 3114                        };
 3115
 3116                        personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
 3117                        saveEntity = true;
 3118                        createEntity = true;
 3119                    }
 3120                    catch (Exception ex)
 3121                    {
 3122                        _logger.LogWarning(ex, "Failed to create person {Name}", person.Name);
 3123                        continue;
 3124                    }
 3125                }
 3126
 3127                foreach (var id in person.ProviderIds)
 3128                {
 3129                    if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)
 3130                    {
 3131                        personEntity.SetProviderId(id.Key, id.Value);
 3132                        saveEntity = true;
 3133                    }
 3134                }
 3135
 3136                if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
 3137                {
 3138                    personEntity.SetImage(
 3139                        new ItemImageInfo
 3140                        {
 3141                            Path = person.ImageUrl,
 3142                            Type = ImageType.Primary
 3143                        },
 3144                        0);
 3145
 3146                    saveEntity = true;
 3147                    itemUpdateType = ItemUpdateType.ImageUpdate;
 3148                }
 3149
 3150                if (saveEntity)
 3151                {
 3152                    if (createEntity)
 3153                    {
 3154                        CreateItems([personEntity], null, CancellationToken.None);
 3155                    }
 3156
 3157                    await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
 3158                    personEntity.DateLastSaved = DateTime.UtcNow;
 3159
 3160                    CreateItems([personEntity], null, CancellationToken.None);
 3161                }
 3162            }
 3163        }
 3164
 3165        private void StartScanInBackground()
 3166        {
 33167            Task.Run(() =>
 33168            {
 33169                // No need to start if scanning the library because it will handle it
 33170                ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
 33171            });
 33172        }
 3173
 3174        public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3175        {
 13176            AddMediaPathInternal(virtualFolderName, mediaPath, true);
 03177        }
 3178
 3179        private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
 3180        {
 13181            ArgumentNullException.ThrowIfNull(pathInfo);
 3182
 13183            var path = pathInfo.Path;
 3184
 13185            if (string.IsNullOrWhiteSpace(path))
 3186            {
 03187                throw new ArgumentException(nameof(path));
 3188            }
 3189
 13190            if (!Directory.Exists(path))
 3191            {
 13192                throw new FileNotFoundException("The path does not exist.");
 3193            }
 3194
 03195            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03196            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3197
 03198            var shortcutFilename = Path.GetFileNameWithoutExtension(path);
 3199
 03200            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3201
 03202            while (File.Exists(lnk))
 3203            {
 03204                shortcutFilename += "1";
 03205                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3206            }
 3207
 03208            _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
 3209
 03210            RemoveContentTypeOverrides(path);
 3211
 03212            if (saveLibraryOptions)
 3213            {
 03214                var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3215
 03216                libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
 3217
 03218                SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3219
 03220                CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 3221            }
 03222        }
 3223
 3224        public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3225        {
 03226            ArgumentNullException.ThrowIfNull(mediaPath);
 3227
 03228            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03229            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3230
 03231            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3232
 03233            SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3234
 03235            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03236        }
 3237
 3238        private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
 3239        {
 03240            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 03241            var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
 3242
 03243            if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
 3244            {
 03245                var list = options.PathInfos.ToList();
 3246
 03247                foreach (var location in info.Locations)
 3248                {
 03249                    if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
 3250                    {
 03251                        list.Add(new MediaPathInfo(location));
 3252                    }
 3253                }
 3254
 03255                options.PathInfos = list.ToArray();
 3256            }
 03257        }
 3258
 3259        public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
 3260        {
 3261            if (string.IsNullOrWhiteSpace(name))
 3262            {
 3263                throw new ArgumentNullException(nameof(name));
 3264            }
 3265
 3266            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3267
 3268            var path = Path.Combine(rootFolderPath, name);
 3269
 3270            if (!Directory.Exists(path))
 3271            {
 3272                throw new FileNotFoundException("The media folder does not exist");
 3273            }
 3274
 3275            LibraryMonitor.Stop();
 3276
 3277            try
 3278            {
 3279                Directory.Delete(path, true);
 3280            }
 3281            finally
 3282            {
 3283                CollectionFolder.OnCollectionFolderChange();
 3284
 3285                if (refreshLibrary)
 3286                {
 3287                    await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
 3288
 3289                    StartScanInBackground();
 3290                }
 3291                else
 3292                {
 3293                    // Need to add a delay here or directory watchers may still pick up the changes
 3294                    await Task.Delay(1000).ConfigureAwait(false);
 3295                    LibraryMonitor.Start();
 3296                }
 3297            }
 3298        }
 3299
 3300        private void RemoveContentTypeOverrides(string path)
 3301        {
 03302            if (string.IsNullOrWhiteSpace(path))
 3303            {
 03304                throw new ArgumentNullException(nameof(path));
 3305            }
 3306
 03307            List<NameValuePair>? removeList = null;
 3308
 03309            foreach (var contentType in _configurationManager.Configuration.ContentTypes)
 3310            {
 03311                if (string.IsNullOrWhiteSpace(contentType.Name)
 03312                    || _fileSystem.AreEqual(path, contentType.Name)
 03313                    || _fileSystem.ContainsSubPath(path, contentType.Name))
 3314                {
 03315                    (removeList ??= new()).Add(contentType);
 3316                }
 3317            }
 3318
 03319            if (removeList is not null)
 3320            {
 03321                _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
 03322                    .Except(removeList)
 03323                    .ToArray();
 3324
 03325                _configurationManager.SaveConfiguration();
 3326            }
 03327        }
 3328
 3329        public void RemoveMediaPath(string virtualFolderName, string mediaPath)
 3330        {
 13331            ArgumentException.ThrowIfNullOrEmpty(mediaPath);
 3332
 13333            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 13334            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3335
 13336            if (!Directory.Exists(virtualFolderPath))
 3337            {
 13338                throw new FileNotFoundException(
 13339                    string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder
 3340            }
 3341
 03342            var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
 03343                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 03344                .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String
 3345
 03346            if (!string.IsNullOrEmpty(shortcut))
 3347            {
 03348                _fileSystem.DeleteFile(shortcut);
 3349            }
 3350
 03351            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3352
 03353            libraryOptions.PathInfos = libraryOptions
 03354                .PathInfos
 03355                .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
 03356                .ToArray();
 3357
 03358            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03359        }
 3360
 3361        private static bool ItemIsVisible(BaseItem? item, User? user)
 3362        {
 213363            if (item is null)
 3364            {
 213365                return false;
 3366            }
 3367
 03368            if (user is null)
 3369            {
 03370                return true;
 3371            }
 3372
 03373            return item is UserRootFolder || item.IsVisibleStandalone(user);
 3374        }
 3375    }
 3376}

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)
DeleteItemsUnsafeFast(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions,MediaBrowser.Controller.Entities.BaseItem,System.Boolean)
DeleteItemPath(MediaBrowser.Controller.Entities.BaseItem,System.Boolean,MediaBrowser.Model.IO.FileSystemMetadata)
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)
GetArtists(System.Collections.Generic.IReadOnlyList`1<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)
GetItemCounts(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)