< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Library.LibraryManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Library/LibraryManager.cs
Line coverage
39%
Covered lines: 427
Uncovered lines: 658
Coverable lines: 1085
Total lines: 3290
Line coverage: 39.3%
Branch coverage
32%
Covered branches: 200
Total branches: 616
Branch coverage: 32.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_RootFolder()100%44100%
get_LibraryMonitor()100%11100%
get_ProviderManager()100%11100%
get_UserViewManager()100%11100%
AddParts(...)100%11100%
RecordConfigurationValues(...)100%11100%
ConfigurationUpdated(...)100%22100%
RegisterItem(...)50%191055.55%
DeleteItem(...)100%210%
DeleteItem(...)0%620%
DeleteItem(...)25%10204825%
IsInternalItem(...)50%741844.44%
GetMetadataPaths(...)50%2275%
GetInternalMetadataPaths(...)12.5%20842.85%
ResolveItem(...)100%44100%
Resolve(...)100%1140%
GetNewItemId(...)100%11100%
GetNewItemIdInternal(...)100%66100%
ResolvePath(...)100%22100%
ResolvePath(...)70%242078.12%
IgnoreFile(...)100%11100%
NormalizeRootPathList(...)50%2291.66%
ResolvePaths(...)100%11100%
ResolvePaths(...)58.33%221258.33%
CreateRootFolder()71.42%141488.46%
GetUserRootFolder()80%111079.16%
FindByPath(...)100%210%
GetPerson(...)50%2280%
GetStudio(...)100%210%
GetStudioId(...)100%210%
GetGenreId(...)100%210%
GetMusicGenreId(...)100%210%
GetGenre(...)100%210%
GetMusicGenre(...)100%210%
GetYear(...)0%620%
GetArtist(...)100%210%
GetArtist(...)100%210%
CreateItemByName(...)0%7280%
GetItemByNameId(...)100%11100%
ValidatePeopleAsync(...)100%210%
ValidateMediaLibrary(...)100%11100%
GetVirtualFolders()100%11100%
GetVirtualFolders(...)100%22100%
GetVirtualFolderInfo(...)70%101097.14%
GetCollectionType(...)50%6450%
GetItemById(...)66.66%7675%
GetItemById(...)100%22100%
GetItemById(...)50%22100%
GetItemById(...)50%22100%
GetItemList(...)100%1010100%
GetItemList(...)100%11100%
GetCount(...)0%7280%
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(...)90%101083.33%
ImageNeedsRefresh(...)0%156120%
UpdateItemAsync(...)100%11100%
ReportItemRemoved(...)100%2276.92%
RetrieveItem(...)100%11100%
GetCollectionFolders(...)100%11100%
GetCollectionFolders(...)80%111081.81%
GetCollectionFoldersInternal(...)100%11100%
GetLibraryOptions(...)75%44100%
GetContentType(...)50%4471.42%
GetInheritedContentType(...)50%2283.33%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)50%2266.66%
GetContentTypeOverride(...)50%4485.71%
GetTopFolderContentType(...)50%11863.63%
GetNamedView(...)100%210%
GetNamedView(...)0%4260%
GetNamedView(...)0%420200%
GetShadowView(...)0%272160%
GetNamedView(...)0%600240%
GetParentItem(...)33.33%8660%
QueueLibraryScan()100%210%
GetSeasonNumberFromPath(...)0%2040%
FillMissingEpisodeNumbersFromPath(...)0%3192560%
ParseName(...)0%620%
GetPathAfterNetworkSubstitution(...)25%6450%
GetPeople(...)100%210%
GetPeople(...)50%11425%
GetPeopleItems(...)100%210%
GetPeopleNames(...)100%210%
UpdatePeople(...)100%210%
StartScanInBackground()100%11100%
AddMediaPath(...)100%1150%
AddMediaPathInternal(...)25%36823.8%
UpdateMediaPath(...)100%210%
SyncLibraryOptionsToLocations(...)0%7280%
RemoveContentTypeOverrides(...)0%210140%
RemoveMediaPath(...)25%9433.33%
ItemIsVisible(...)16.66%14640%

File(s)

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

#LineLine coverage
 1#pragma warning disable CS1591
 2#pragma warning disable CA5394
 3
 4using System;
 5using System.Collections.Generic;
 6using System.Globalization;
 7using System.IO;
 8using System.Linq;
 9using System.Net;
 10using System.Net.Http;
 11using System.Threading;
 12using System.Threading.Tasks;
 13using BitFaster.Caching.Lru;
 14using Emby.Naming.Common;
 15using Emby.Naming.TV;
 16using Emby.Server.Implementations.Library.Resolvers;
 17using Emby.Server.Implementations.Library.Validators;
 18using Emby.Server.Implementations.Playlists;
 19using Emby.Server.Implementations.ScheduledTasks.Tasks;
 20using Emby.Server.Implementations.Sorting;
 21using Jellyfin.Data;
 22using Jellyfin.Data.Enums;
 23using Jellyfin.Database.Implementations.Entities;
 24using Jellyfin.Database.Implementations.Enums;
 25using Jellyfin.Extensions;
 26using MediaBrowser.Common.Extensions;
 27using MediaBrowser.Controller;
 28using MediaBrowser.Controller.Configuration;
 29using MediaBrowser.Controller.Drawing;
 30using MediaBrowser.Controller.Dto;
 31using MediaBrowser.Controller.Entities;
 32using MediaBrowser.Controller.Entities.Audio;
 33using MediaBrowser.Controller.IO;
 34using MediaBrowser.Controller.Library;
 35using MediaBrowser.Controller.LiveTv;
 36using MediaBrowser.Controller.MediaEncoding;
 37using MediaBrowser.Controller.MediaSegments;
 38using MediaBrowser.Controller.Persistence;
 39using MediaBrowser.Controller.Providers;
 40using MediaBrowser.Controller.Resolvers;
 41using MediaBrowser.Controller.Sorting;
 42using MediaBrowser.Controller.Trickplay;
 43using MediaBrowser.Model.Configuration;
 44using MediaBrowser.Model.Dlna;
 45using MediaBrowser.Model.Drawing;
 46using MediaBrowser.Model.Dto;
 47using MediaBrowser.Model.Entities;
 48using MediaBrowser.Model.IO;
 49using MediaBrowser.Model.Library;
 50using MediaBrowser.Model.Querying;
 51using MediaBrowser.Model.Tasks;
 52using Microsoft.Extensions.Logging;
 53using Episode = MediaBrowser.Controller.Entities.TV.Episode;
 54using EpisodeInfo = Emby.Naming.TV.EpisodeInfo;
 55using Genre = MediaBrowser.Controller.Entities.Genre;
 56using Person = MediaBrowser.Controller.Entities.Person;
 57using VideoResolver = Emby.Naming.Video.VideoResolver;
 58
 59namespace Emby.Server.Implementations.Library
 60{
 61    /// <summary>
 62    /// Class LibraryManager.
 63    /// </summary>
 64    public class LibraryManager : ILibraryManager
 65    {
 66        private const string ShortcutFileExtension = ".mblink";
 67
 68        private readonly ILogger<LibraryManager> _logger;
 69        private readonly ITaskManager _taskManager;
 70        private readonly IUserManager _userManager;
 71        private readonly IUserDataManager _userDataManager;
 72        private readonly IServerConfigurationManager _configurationManager;
 73        private readonly Lazy<ILibraryMonitor> _libraryMonitorFactory;
 74        private readonly Lazy<IProviderManager> _providerManagerFactory;
 75        private readonly Lazy<IUserViewManager> _userViewManagerFactory;
 76        private readonly IServerApplicationHost _appHost;
 77        private readonly IMediaEncoder _mediaEncoder;
 78        private readonly IFileSystem _fileSystem;
 79        private readonly IItemRepository _itemRepository;
 80        private readonly IImageProcessor _imageProcessor;
 81        private readonly NamingOptions _namingOptions;
 82        private readonly IPeopleRepository _peopleRepository;
 83        private readonly ExtraResolver _extraResolver;
 84        private readonly IPathManager _pathManager;
 85        private readonly FastConcurrentLru<Guid, BaseItem> _cache;
 86
 87        /// <summary>
 88        /// The _root folder sync lock.
 89        /// </summary>
 2890        private readonly Lock _rootFolderSyncLock = new();
 2891        private readonly Lock _userRootFolderSyncLock = new();
 92
 2893        private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
 94
 95        /// <summary>
 96        /// The _root folder.
 97        /// </summary>
 98        private volatile AggregateFolder? _rootFolder;
 99        private volatile UserRootFolder? _userRootFolder;
 100
 101        private bool _wizardCompleted;
 102
 103        /// <summary>
 104        /// Initializes a new instance of the <see cref="LibraryManager" /> class.
 105        /// </summary>
 106        /// <param name="appHost">The application host.</param>
 107        /// <param name="loggerFactory">The logger factory.</param>
 108        /// <param name="taskManager">The task manager.</param>
 109        /// <param name="userManager">The user manager.</param>
 110        /// <param name="configurationManager">The configuration manager.</param>
 111        /// <param name="userDataManager">The user data manager.</param>
 112        /// <param name="libraryMonitorFactory">The library monitor.</param>
 113        /// <param name="fileSystem">The file system.</param>
 114        /// <param name="providerManagerFactory">The provider manager.</param>
 115        /// <param name="userViewManagerFactory">The user view manager.</param>
 116        /// <param name="mediaEncoder">The media encoder.</param>
 117        /// <param name="itemRepository">The item repository.</param>
 118        /// <param name="imageProcessor">The image processor.</param>
 119        /// <param name="namingOptions">The naming options.</param>
 120        /// <param name="directoryService">The directory service.</param>
 121        /// <param name="peopleRepository">The people repository.</param>
 122        /// <param name="pathManager">The path manager.</param>
 123        public LibraryManager(
 124            IServerApplicationHost appHost,
 125            ILoggerFactory loggerFactory,
 126            ITaskManager taskManager,
 127            IUserManager userManager,
 128            IServerConfigurationManager configurationManager,
 129            IUserDataManager userDataManager,
 130            Lazy<ILibraryMonitor> libraryMonitorFactory,
 131            IFileSystem fileSystem,
 132            Lazy<IProviderManager> providerManagerFactory,
 133            Lazy<IUserViewManager> userViewManagerFactory,
 134            IMediaEncoder mediaEncoder,
 135            IItemRepository itemRepository,
 136            IImageProcessor imageProcessor,
 137            NamingOptions namingOptions,
 138            IDirectoryService directoryService,
 139            IPeopleRepository peopleRepository,
 140            IPathManager pathManager)
 141        {
 28142            _appHost = appHost;
 28143            _logger = loggerFactory.CreateLogger<LibraryManager>();
 28144            _taskManager = taskManager;
 28145            _userManager = userManager;
 28146            _configurationManager = configurationManager;
 28147            _userDataManager = userDataManager;
 28148            _libraryMonitorFactory = libraryMonitorFactory;
 28149            _fileSystem = fileSystem;
 28150            _providerManagerFactory = providerManagerFactory;
 28151            _userViewManagerFactory = userViewManagerFactory;
 28152            _mediaEncoder = mediaEncoder;
 28153            _itemRepository = itemRepository;
 28154            _imageProcessor = imageProcessor;
 155
 28156            _cache = new FastConcurrentLru<Guid, BaseItem>(_configurationManager.Configuration.CacheSize);
 157
 28158            _namingOptions = namingOptions;
 28159            _peopleRepository = peopleRepository;
 28160            _pathManager = pathManager;
 28161            _extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryServ
 162
 28163            _configurationManager.ConfigurationUpdated += ConfigurationUpdated;
 164
 28165            RecordConfigurationValues(_configurationManager.Configuration);
 28166        }
 167
 168        /// <summary>
 169        /// Occurs when [item added].
 170        /// </summary>
 171        public event EventHandler<ItemChangeEventArgs>? ItemAdded;
 172
 173        /// <summary>
 174        /// Occurs when [item updated].
 175        /// </summary>
 176        public event EventHandler<ItemChangeEventArgs>? ItemUpdated;
 177
 178        /// <summary>
 179        /// Occurs when [item removed].
 180        /// </summary>
 181        public event EventHandler<ItemChangeEventArgs>? ItemRemoved;
 182
 183        /// <summary>
 184        /// Gets the root folder.
 185        /// </summary>
 186        /// <value>The root folder.</value>
 187        public AggregateFolder RootFolder
 188        {
 189            get
 190            {
 150191                if (_rootFolder is null)
 21192                {
 193                    lock (_rootFolderSyncLock)
 194                    {
 21195                        _rootFolder ??= CreateRootFolder();
 21196                    }
 197                }
 198
 150199                return _rootFolder;
 200            }
 201        }
 202
 41203        private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
 204
 86205        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        {
 156296            ArgumentNullException.ThrowIfNull(item);
 297
 156298            if (item is IItemByName)
 299            {
 0300                if (item is not MusicArtist)
 301                {
 0302                    return;
 303                }
 304            }
 156305            else if (!item.IsFolder)
 306            {
 0307                if (item is not Video && item is not LiveTvChannel)
 308                {
 0309                    return;
 310                }
 311            }
 312
 156313            _cache.AddOrUpdate(item.Id, item);
 156314        }
 315
 316        public void DeleteItem(BaseItem item, DeleteOptions options)
 317        {
 0318            DeleteItem(item, options, false);
 0319        }
 320
 321        public void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem)
 322        {
 0323            ArgumentNullException.ThrowIfNull(item);
 324
 0325            var parent = item.GetOwner() ?? item.GetParent();
 326
 0327            DeleteItem(item, options, parent, notifyParentItem);
 0328        }
 329
 330        public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem)
 331        {
 2332            ArgumentNullException.ThrowIfNull(item);
 333
 2334            if (item.SourceType == SourceType.Channel)
 335            {
 0336                if (options.DeleteFromExternalProvider)
 337                {
 338                    try
 339                    {
 0340                        BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult();
 0341                    }
 0342                    catch (ArgumentException)
 343                    {
 344                        // channel no longer installed
 0345                    }
 346                }
 347
 0348                options.DeleteFileLocation = false;
 349            }
 350
 2351            if (item is LiveTvProgram)
 352            {
 0353                _logger.LogDebug(
 0354                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0355                    item.GetType().Name,
 0356                    item.Name ?? "Unknown name",
 0357                    item.Path ?? string.Empty,
 0358                    item.Id);
 359            }
 360            else
 361            {
 2362                _logger.LogInformation(
 2363                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 2364                    item.GetType().Name,
 2365                    item.Name ?? "Unknown name",
 2366                    item.Path ?? string.Empty,
 2367                    item.Id);
 368            }
 369
 2370            var children = item.IsFolder
 2371                ? ((Folder)item).GetRecursiveChildren(false)
 2372                : [];
 373
 8374            foreach (var metadataPath in GetMetadataPaths(item, children))
 375            {
 2376                if (!Directory.Exists(metadataPath))
 377                {
 378                    continue;
 379                }
 380
 0381                _logger.LogDebug(
 0382                    "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0383                    item.GetType().Name,
 0384                    item.Name ?? "Unknown name",
 0385                    metadataPath,
 0386                    item.Id);
 387
 388                try
 389                {
 0390                    Directory.Delete(metadataPath, true);
 0391                }
 0392                catch (Exception ex)
 393                {
 0394                    _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0395                }
 396            }
 397
 2398            if ((options.DeleteFileLocation && item.IsFileProtocol) || IsInternalItem(item))
 399            {
 400                // Assume only the first is required
 401                // Add this flag to GetDeletePaths if required in the future
 0402                var isRequiredForDelete = true;
 403
 0404                foreach (var fileSystemInfo in item.GetDeletePaths())
 405                {
 0406                    if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
 407                    {
 408                        try
 409                        {
 0410                            _logger.LogInformation(
 0411                                "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0412                                item.GetType().Name,
 0413                                item.Name ?? "Unknown name",
 0414                                fileSystemInfo.FullName,
 0415                                item.Id);
 416
 0417                            if (fileSystemInfo.IsDirectory)
 418                            {
 0419                                Directory.Delete(fileSystemInfo.FullName, true);
 420                            }
 421                            else
 422                            {
 0423                                File.Delete(fileSystemInfo.FullName);
 424                            }
 0425                        }
 0426                        catch (DirectoryNotFoundException)
 427                        {
 0428                            _logger.LogInformation(
 0429                                "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Pa
 0430                                item.GetType().Name,
 0431                                item.Name ?? "Unknown name",
 0432                                fileSystemInfo.FullName,
 0433                                item.Id);
 0434                        }
 0435                        catch (FileNotFoundException)
 436                        {
 0437                            _logger.LogInformation(
 0438                                "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, 
 0439                                item.GetType().Name,
 0440                                item.Name ?? "Unknown name",
 0441                                fileSystemInfo.FullName,
 0442                                item.Id);
 0443                        }
 0444                        catch (IOException)
 445                        {
 0446                            if (isRequiredForDelete)
 447                            {
 0448                                throw;
 449                            }
 0450                        }
 0451                        catch (UnauthorizedAccessException)
 452                        {
 0453                            if (isRequiredForDelete)
 454                            {
 0455                                throw;
 456                            }
 0457                        }
 458                    }
 459
 0460                    isRequiredForDelete = false;
 461                }
 462            }
 463
 2464            item.SetParent(null);
 465
 2466            _itemRepository.DeleteItem(item.Id);
 2467            _cache.TryRemove(item.Id, out _);
 4468            foreach (var child in children)
 469            {
 0470                _itemRepository.DeleteItem(child.Id);
 0471                _cache.TryRemove(child.Id, out _);
 472            }
 473
 2474            ReportItemRemoved(item, parent);
 2475        }
 476
 477        private bool IsInternalItem(BaseItem item)
 478        {
 2479            if (!item.IsFileProtocol)
 480            {
 0481                return false;
 482            }
 483
 2484            var pathToCheck = item switch
 2485            {
 0486                Genre => _configurationManager.ApplicationPaths.GenrePath,
 0487                MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath,
 0488                MusicGenre => _configurationManager.ApplicationPaths.GenrePath,
 0489                Person => _configurationManager.ApplicationPaths.PeoplePath,
 0490                Studio => _configurationManager.ApplicationPaths.StudioPath,
 0491                Year => _configurationManager.ApplicationPaths.YearPath,
 2492                _ => null
 2493            };
 494
 2495            var itemPath = item.Path;
 2496            if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath))
 497            {
 0498                var cleanPath = _fileSystem.GetValidFilename(itemPath);
 0499                var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck);
 500
 0501                return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal);
 502            }
 503
 2504            return false;
 505        }
 506
 507        private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
 508        {
 2509            var list = GetInternalMetadataPaths(item);
 4510            foreach (var child in children)
 511            {
 0512                list.AddRange(GetInternalMetadataPaths(child));
 513            }
 514
 2515            return list;
 516        }
 517
 518        private List<string> GetInternalMetadataPaths(BaseItem item)
 519        {
 2520            var list = new List<string>
 2521            {
 2522                item.GetInternalMetadataPath()
 2523            };
 524
 2525            if (item is Video video)
 526            {
 527                // Trickplay
 0528                list.Add(_pathManager.GetTrickplayDirectory(video));
 529
 530                // Subtitles and attachments
 0531                foreach (var mediaSource in item.GetMediaSources(false))
 532                {
 0533                    var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id);
 0534                    if (subtitleFolder is not null)
 535                    {
 0536                        list.Add(subtitleFolder);
 537                    }
 538
 0539                    var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0540                    if (attachmentFolder is not null)
 541                    {
 0542                        list.Add(attachmentFolder);
 543                    }
 544                }
 545            }
 546
 2547            return list;
 548        }
 549
 550        /// <summary>
 551        /// Resolves the item.
 552        /// </summary>
 553        /// <param name="args">The args.</param>
 554        /// <param name="resolvers">The resolvers.</param>
 555        /// <returns>BaseItem.</returns>
 556        private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers)
 557        {
 79558            var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r))
 79559                .FirstOrDefault(i => i is not null);
 560
 79561            if (item is not null)
 562            {
 68563                ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
 564            }
 565
 79566            return item;
 567        }
 568
 569        private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver)
 570        {
 571            try
 572            {
 324573                return resolver.ResolvePath(args);
 574            }
 0575            catch (Exception ex)
 576            {
 0577                _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path);
 0578                return null;
 579            }
 324580        }
 581
 582        public Guid GetNewItemId(string key, Type type)
 583        {
 131584            return GetNewItemIdInternal(key, type, false);
 585        }
 586
 587        private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
 588        {
 132589            ArgumentException.ThrowIfNullOrEmpty(key);
 132590            ArgumentNullException.ThrowIfNull(type);
 591
 132592            string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
 132593            if (key.StartsWith(programDataPath, StringComparison.Ordinal))
 594            {
 595                // Try to normalize paths located underneath program-data in an attempt to make them more portable
 115596                key = key.Substring(programDataPath.Length)
 115597                    .TrimStart('/', '\\')
 115598                    .Replace('/', '\\');
 599            }
 600
 132601            if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
 602            {
 1603                key = key.ToLowerInvariant();
 604            }
 605
 132606            key = type.FullName + key;
 607
 132608            return key.GetMD5();
 609        }
 610
 611        public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directorySer
 42612            => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent);
 613
 614        private BaseItem? ResolvePath(
 615            FileSystemMetadata fileInfo,
 616            IDirectoryService directoryService,
 617            IItemResolver[]? resolvers,
 618            Folder? parent = null,
 619            CollectionType? collectionType = null,
 620            LibraryOptions? libraryOptions = null)
 621        {
 79622            ArgumentNullException.ThrowIfNull(fileInfo);
 623
 79624            var fullPath = fileInfo.FullName;
 625
 79626            if (collectionType is null && parent is not null)
 627            {
 20628                collectionType = GetContentTypeOverride(fullPath, true);
 629            }
 630
 79631            var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this)
 79632            {
 79633                Parent = parent,
 79634                FileInfo = fileInfo,
 79635                CollectionType = collectionType,
 79636                LibraryOptions = libraryOptions
 79637            };
 638
 639            // Return null if ignore rules deem that we should do so
 79640            if (IgnoreFile(args.FileInfo, args.Parent))
 641            {
 0642                return null;
 643            }
 644
 645            // Gather child folder and files
 79646            if (args.IsDirectory)
 647            {
 51648                var isPhysicalRoot = args.IsPhysicalRoot;
 649
 650                // When resolving the root, we need it's grandchildren (children of user views)
 51651                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
 652
 653                FileSystemMetadata[] files;
 51654                var isVf = args.IsVf;
 655
 656                try
 657                {
 51658                    files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l
 51659                }
 0660                catch (Exception ex)
 661                {
 0662                    if (parent is not null && parent.IsPhysicalRoot)
 663                    {
 0664                        _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPh
 665
 0666                        files = [];
 667                    }
 668                    else
 669                    {
 0670                        throw;
 671                    }
 0672                }
 673
 674                // Need to remove sub-paths that may have been resolved from shortcuts
 675                // Example: if \\server\movies exists, then strip out \\server\movies\action
 51676                if (isPhysicalRoot)
 677                {
 21678                    files = NormalizeRootPathList(files).ToArray();
 679                }
 680
 51681                args.FileSystemChildren = files;
 682            }
 683
 684            // Filter content based on ignore rules
 79685            if (args.IsDirectory)
 686            {
 51687                var filtered = args.GetActualFileSystemChildren().ToArray();
 51688                args.FileSystemChildren = filtered ?? [];
 689            }
 690
 79691            return ResolveItem(args, resolvers);
 692        }
 693
 694        public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
 109695            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 696
 697        public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
 698        {
 67699            var originalList = paths.ToList();
 700
 67701            var list = originalList.Where(i => i.IsDirectory)
 67702                .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
 67703                .Distinct()
 67704                .ToList();
 705
 67706            var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS
 67707                .ToList();
 708
 134709            foreach (var dupe in dupes)
 710            {
 0711                _logger.LogInformation("Found duplicate path: {0}", dupe);
 712            }
 713
 67714            var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
 67715            newList.AddRange(originalList.Where(i => !i.IsDirectory));
 67716            return newList;
 717        }
 718
 719        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ
 720        {
 39721            return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
 722        }
 723
 724        public IEnumerable<BaseItem> ResolvePaths(
 725            IEnumerable<FileSystemMetadata> files,
 726            IDirectoryService directoryService,
 727            Folder parent,
 728            LibraryOptions libraryOptions,
 729            CollectionType? collectionType,
 730            IItemResolver[] resolvers)
 731        {
 39732            var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
 733
 39734            if (parent is not null)
 735            {
 39736                var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>()
 737
 234738                foreach (var resolver in multiItemResolvers)
 739                {
 78740                    var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
 741
 78742                    if (result?.Items.Count > 0)
 743                    {
 0744                        var items = result.Items;
 0745                        items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryServic
 0746                        items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, reso
 0747                        return items;
 748                    }
 749                }
 750            }
 751
 39752            return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
 0753        }
 754
 755        private IEnumerable<BaseItem> ResolveFileList(
 756            IReadOnlyList<FileSystemMetadata> fileList,
 757            IDirectoryService directoryService,
 758            Folder? parent,
 759            CollectionType? collectionType,
 760            IItemResolver[]? resolvers,
 761            LibraryOptions libraryOptions)
 762        {
 763            // Given that fileList is a list we can save enumerator allocations by indexing
 764            for (var i = 0; i < fileList.Count; i++)
 765            {
 766                var file = fileList[i];
 767                BaseItem? result = null;
 768                try
 769                {
 770                    result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
 771                }
 772                catch (Exception ex)
 773                {
 774                    _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
 775                }
 776
 777                if (result is not null)
 778                {
 779                    yield return result;
 780                }
 781            }
 782        }
 783
 784        /// <summary>
 785        /// Creates the root media folder.
 786        /// </summary>
 787        /// <returns>AggregateFolder.</returns>
 788        /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</except
 789        public AggregateFolder CreateRootFolder()
 790        {
 21791            var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
 792
 21793            var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
 21794                             (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOp
 21795                             .DeepCopy<Folder, AggregateFolder>();
 796
 797            // In case program data folder was moved
 21798            if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
 799            {
 0800                _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
 0801                rootFolder.Path = rootFolderPath;
 802            }
 803
 804            // Add in the plug-in folders
 21805            var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
 806
 21807            var info = Directory.CreateDirectory(path);
 21808            Folder folder = new PlaylistsFolder
 21809            {
 21810                Path = path,
 21811                DateCreated = info.CreationTimeUtc,
 21812                DateModified = info.LastWriteTimeUtc,
 21813            };
 814
 21815            if (folder.Id.IsEmpty())
 816            {
 21817                folder.Id = GetNewItemId(folder.Path, folder.GetType());
 818            }
 819
 21820            var dbItem = GetItemById(folder.Id) as BasePluginFolder;
 821
 21822            if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
 823            {
 0824                folder = dbItem;
 825            }
 826
 21827            if (!folder.ParentId.Equals(rootFolder.Id))
 828            {
 21829                folder.ParentId = rootFolder.Id;
 21830                folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetRe
 831            }
 832
 21833            rootFolder.AddVirtualChild(folder);
 834
 21835            RegisterItem(folder);
 836
 21837            return rootFolder;
 838        }
 839
 840        public Folder GetUserRootFolder()
 841        {
 758842            if (_userRootFolder is null)
 21843            {
 844                lock (_userRootFolderSyncLock)
 845                {
 21846                    if (_userRootFolder is null)
 847                    {
 21848                        var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 849
 21850                        _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
 21851                        Directory.CreateDirectory(userRootPath);
 852
 21853                        var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
 21854                        UserRootFolder? tmpItem = null;
 855                        try
 856                        {
 21857                            tmpItem = GetItemById(newItemId) as UserRootFolder;
 21858                        }
 0859                        catch (Exception ex)
 860                        {
 0861                            _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
 0862                        }
 863
 21864                        if (tmpItem is null)
 865                        {
 21866                            _logger.LogDebug("Creating new userRootFolder with DeepCopy");
 21867                            tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new In
 21868                                        .DeepCopy<Folder, UserRootFolder>();
 869                        }
 870
 871                        // In case program data folder was moved
 21872                        if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
 873                        {
 0874                            _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
 0875                            tmpItem.Path = userRootPath;
 876                        }
 877
 21878                        _userRootFolder = tmpItem;
 21879                        _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
 880                    }
 21881                }
 882            }
 883
 758884            return _userRootFolder;
 885        }
 886
 887        /// <inheritdoc />
 888        public BaseItem? FindByPath(string path, bool? isFolder)
 889        {
 890            // If this returns multiple items it could be tricky figuring out which one is correct.
 891            // In most cases, the newest one will be and the others obsolete but not yet cleaned up
 0892            ArgumentException.ThrowIfNullOrEmpty(path);
 893
 0894            var query = new InternalItemsQuery
 0895            {
 0896                Path = path,
 0897                IsFolder = isFolder,
 0898                OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
 0899                Limit = 1,
 0900                DtoOptions = new DtoOptions(true)
 0901            };
 902
 0903            return GetItemList(query)
 0904                .FirstOrDefault();
 905        }
 906
 907        /// <inheritdoc />
 908        public Person? GetPerson(string name)
 909        {
 1910            var path = Person.GetPath(name);
 1911            var id = GetItemByNameId<Person>(path);
 1912            if (GetItemById(id) is Person item)
 913            {
 0914                return item;
 915            }
 916
 1917            return null;
 918        }
 919
 920        /// <summary>
 921        /// Gets the studio.
 922        /// </summary>
 923        /// <param name="name">The name.</param>
 924        /// <returns>Task{Studio}.</returns>
 925        public Studio GetStudio(string name)
 926        {
 0927            return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
 928        }
 929
 930        public Guid GetStudioId(string name)
 931        {
 0932            return GetItemByNameId<Studio>(Studio.GetPath(name));
 933        }
 934
 935        public Guid GetGenreId(string name)
 936        {
 0937            return GetItemByNameId<Genre>(Genre.GetPath(name));
 938        }
 939
 940        public Guid GetMusicGenreId(string name)
 941        {
 0942            return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
 943        }
 944
 945        /// <summary>
 946        /// Gets the genre.
 947        /// </summary>
 948        /// <param name="name">The name.</param>
 949        /// <returns>Task{Genre}.</returns>
 950        public Genre GetGenre(string name)
 951        {
 0952            return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
 953        }
 954
 955        /// <summary>
 956        /// Gets the music genre.
 957        /// </summary>
 958        /// <param name="name">The name.</param>
 959        /// <returns>Task{MusicGenre}.</returns>
 960        public MusicGenre GetMusicGenre(string name)
 961        {
 0962            return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
 963        }
 964
 965        /// <summary>
 966        /// Gets the year.
 967        /// </summary>
 968        /// <param name="value">The value.</param>
 969        /// <returns>Task{Year}.</returns>
 970        public Year GetYear(int value)
 971        {
 0972            if (value <= 0)
 973            {
 0974                throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
 975            }
 976
 0977            var name = value.ToString(CultureInfo.InvariantCulture);
 978
 0979            return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
 980        }
 981
 982        /// <summary>
 983        /// Gets a Genre.
 984        /// </summary>
 985        /// <param name="name">The name.</param>
 986        /// <returns>Task{Genre}.</returns>
 987        public MusicArtist GetArtist(string name)
 988        {
 0989            return GetArtist(name, new DtoOptions(true));
 990        }
 991
 992        public MusicArtist GetArtist(string name, DtoOptions options)
 993        {
 0994            return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
 995        }
 996
 997        private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
 998            where T : BaseItem, new()
 999        {
 01000            if (typeof(T) == typeof(MusicArtist))
 1001            {
 01002                var existing = GetItemList(new InternalItemsQuery
 01003                {
 01004                    IncludeItemTypes = [BaseItemKind.MusicArtist],
 01005                    Name = name,
 01006                    DtoOptions = options
 01007                }).Cast<MusicArtist>()
 01008                .OrderBy(i => i.IsAccessedByName ? 1 : 0)
 01009                .Cast<T>()
 01010                .FirstOrDefault();
 1011
 01012                if (existing is not null)
 1013                {
 01014                    return existing;
 1015                }
 1016            }
 1017
 01018            var path = getPathFn(name);
 01019            var id = GetItemByNameId<T>(path);
 01020            var item = GetItemById(id) as T;
 01021            if (item is null)
 1022            {
 01023                var info = Directory.CreateDirectory(path);
 01024                item = new T
 01025                {
 01026                    Name = name,
 01027                    Id = id,
 01028                    DateCreated = info.CreationTimeUtc,
 01029                    DateModified = info.LastWriteTimeUtc,
 01030                    Path = path
 01031                };
 1032
 01033                CreateItem(item, null);
 1034            }
 1035
 01036            return item;
 1037        }
 1038
 1039        private Guid GetItemByNameId<T>(string path)
 1040              where T : BaseItem, new()
 1041        {
 11042            var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
 11043            return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
 1044        }
 1045
 1046        /// <inheritdoc />
 1047        public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
 1048        {
 1049            // Ensure the location is available.
 01050            Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
 1051
 01052            return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
 1053        }
 1054
 1055        /// <summary>
 1056        /// Reloads the root media folder.
 1057        /// </summary>
 1058        /// <param name="progress">The progress.</param>
 1059        /// <param name="cancellationToken">The cancellation token.</param>
 1060        /// <returns>Task.</returns>
 1061        public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
 1062        {
 1063            // Just run the scheduled task so that the user can see it
 31064            _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
 1065
 31066            return Task.CompletedTask;
 1067        }
 1068
 1069        /// <summary>
 1070        /// Validates the media library internal.
 1071        /// </summary>
 1072        /// <param name="progress">The progress.</param>
 1073        /// <param name="cancellationToken">The cancellation token.</param>
 1074        /// <returns>Task.</returns>
 1075        public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
 1076        {
 1077            IsScanRunning = true;
 1078            LibraryMonitor.Stop();
 1079
 1080            try
 1081            {
 1082                await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
 1083            }
 1084            finally
 1085            {
 1086                LibraryMonitor.Start();
 1087                IsScanRunning = false;
 1088            }
 1089        }
 1090
 1091        public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
 1092        {
 1093            await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1094
 1095            // Start by just validating the children of the root, but go no further
 1096            await RootFolder.ValidateChildren(
 1097                new Progress<double>(),
 1098                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1099                recursive: false,
 1100                allowRemoveRoot: removeRoot,
 1101                cancellationToken: cancellationToken).ConfigureAwait(false);
 1102
 1103            await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1104
 1105            await GetUserRootFolder().ValidateChildren(
 1106                new Progress<double>(),
 1107                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1108                recursive: false,
 1109                allowRemoveRoot: removeRoot,
 1110                cancellationToken: cancellationToken).ConfigureAwait(false);
 1111
 1112            // Quickly scan CollectionFolders for changes
 1113            foreach (var child in GetUserRootFolder().Children.OfType<Folder>())
 1114            {
 1115                // If the user has somehow deleted the collection directory, remove the metadata from the database.
 1116                if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
 1117                {
 1118                    _itemRepository.DeleteItem(collectionFolder.Id);
 1119                }
 1120                else
 1121                {
 1122                    await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1123                }
 1124            }
 1125        }
 1126
 1127        private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
 1128        {
 1129            _logger.LogInformation("Validating media library");
 1130
 1131            await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
 1132
 1133            var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
 1134
 1135            // Validate the entire media library
 1136            await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem
 1137
 1138            progress.Report(96);
 1139
 1140            innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
 1141
 1142            await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
 1143
 1144            progress.Report(100);
 1145        }
 1146
 1147        /// <summary>
 1148        /// Runs the post scan tasks.
 1149        /// </summary>
 1150        /// <param name="progress">The progress.</param>
 1151        /// <param name="cancellationToken">The cancellation token.</param>
 1152        /// <returns>Task.</returns>
 1153        private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
 1154        {
 1155            var tasks = PostScanTasks.ToList();
 1156
 1157            var numComplete = 0;
 1158            var numTasks = tasks.Count;
 1159
 1160            foreach (var task in tasks)
 1161            {
 1162                // Prevent access to modified closure
 1163                var currentNumComplete = numComplete;
 1164
 1165                var innerProgress = new Progress<double>(pct =>
 1166                {
 1167                    double innerPercent = pct;
 1168                    innerPercent /= 100;
 1169                    innerPercent += currentNumComplete;
 1170
 1171                    innerPercent /= numTasks;
 1172                    innerPercent *= 100;
 1173
 1174                    progress.Report(innerPercent);
 1175                });
 1176
 1177                _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
 1178
 1179                try
 1180                {
 1181                    await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
 1182                }
 1183                catch (OperationCanceledException)
 1184                {
 1185                    _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
 1186                    throw;
 1187                }
 1188                catch (Exception ex)
 1189                {
 1190                    _logger.LogError(ex, "Error running post-scan task");
 1191                }
 1192
 1193                numComplete++;
 1194                double percent = numComplete;
 1195                percent /= numTasks;
 1196                progress.Report(percent * 100);
 1197            }
 1198
 1199            _itemRepository.UpdateInheritedValues();
 1200
 1201            progress.Report(100);
 1202        }
 1203
 1204        /// <summary>
 1205        /// Gets the default view.
 1206        /// </summary>
 1207        /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
 1208        public List<VirtualFolderInfo> GetVirtualFolders()
 1209        {
 231210            return GetVirtualFolders(false);
 1211        }
 1212
 1213        public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
 1214        {
 241215            _logger.LogDebug("Getting topLibraryFolders");
 241216            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 1217
 241218            _logger.LogDebug("Getting refreshQueue");
 241219            var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
 1220
 241221            return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
 241222                .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
 241223                .ToList();
 1224        }
 1225
 1226        private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? r
 1227        {
 11228            var info = new VirtualFolderInfo
 11229            {
 11230                Name = Path.GetFileName(dir),
 11231
 11232                Locations = _fileSystem.GetFilePaths(dir, false)
 11233                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 11234                    .Select(i =>
 11235                    {
 11236                        try
 11237                        {
 11238                            return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
 11239                        }
 11240                        catch (Exception ex)
 11241                        {
 11242                            _logger.LogError(ex, "Error resolving shortcut file {File}", i);
 11243                            return null;
 11244                        }
 11245                    })
 11246                    .Where(i => i is not null)
 11247                    .Order()
 11248                    .ToArray(),
 11249
 11250                CollectionType = GetCollectionType(dir)
 11251            };
 1252
 11253            var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.Ord
 11254            if (libraryFolder is not null)
 1255            {
 11256                var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
 11257                info.ItemId = libraryFolderId;
 11258                if (libraryFolder.HasImage(ImageType.Primary))
 1259                {
 01260                    info.PrimaryImageItemId = libraryFolderId;
 1261                }
 1262
 11263                info.LibraryOptions = GetLibraryOptions(libraryFolder);
 1264
 11265                if (refreshQueue is not null)
 1266                {
 11267                    info.RefreshProgress = libraryFolder.GetRefreshProgress();
 1268
 11269                    info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.
 1270                }
 1271            }
 1272
 11273            return info;
 1274        }
 1275
 1276        private CollectionTypeOptions? GetCollectionType(string path)
 1277        {
 11278            var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
 21279            foreach (ReadOnlySpan<char> file in files)
 1280            {
 01281                if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
 1282                {
 01283                    return res;
 1284                }
 1285            }
 1286
 11287            return null;
 01288        }
 1289
 1290        /// <inheritdoc />
 1291        public BaseItem? GetItemById(Guid id)
 1292        {
 8731293            if (id.IsEmpty())
 1294            {
 01295                throw new ArgumentException("Guid can't be empty", nameof(id));
 1296            }
 1297
 8731298            if (_cache.TryGet(id, out var item))
 1299            {
 6401300                return item;
 1301            }
 1302
 2331303            item = RetrieveItem(id);
 1304
 2331305            if (item is not null)
 1306            {
 01307                RegisterItem(item);
 1308            }
 1309
 2331310            return item;
 1311        }
 1312
 1313        /// <inheritdoc />
 1314        public T? GetItemById<T>(Guid id)
 1315            where T : BaseItem
 1316        {
 231317            var item = GetItemById(id);
 231318            if (item is T typedItem)
 1319            {
 11320                return typedItem;
 1321            }
 1322
 221323            return null;
 1324        }
 1325
 1326        /// <inheritdoc />
 1327        public T? GetItemById<T>(Guid id, Guid userId)
 1328            where T : BaseItem
 1329        {
 11330            var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
 11331            return GetItemById<T>(id, user);
 1332        }
 1333
 1334        /// <inheritdoc />
 1335        public T? GetItemById<T>(Guid id, User? user)
 1336            where T : BaseItem
 1337        {
 211338            var item = GetItemById<T>(id);
 211339            return ItemIsVisible(item, user) ? item : null;
 1340        }
 1341
 1342        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
 1343        {
 891344            if (query.Recursive && !query.ParentId.IsEmpty())
 1345            {
 381346                var parent = GetItemById(query.ParentId);
 381347                if (parent is not null)
 1348                {
 381349                    SetTopParentIdsOrAncestors(query, [parent]);
 1350                }
 1351            }
 1352
 891353            if (query.User is not null)
 1354            {
 11355                AddUserToQuery(query, query.User, allowExternalContent);
 1356            }
 1357
 891358            var itemList = _itemRepository.GetItemList(query);
 891359            var user = query.User;
 891360            if (user is not null)
 1361            {
 11362                return itemList.Where(i => i.IsVisible(user)).ToList();
 1363            }
 1364
 881365            return itemList;
 1366        }
 1367
 1368        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 1369        {
 891370            return GetItemList(query, true);
 1371        }
 1372
 1373        public int GetCount(InternalItemsQuery query)
 1374        {
 01375            if (query.Recursive && !query.ParentId.IsEmpty())
 1376            {
 01377                var parent = GetItemById(query.ParentId);
 01378                if (parent is not null)
 1379                {
 01380                    SetTopParentIdsOrAncestors(query, [parent]);
 1381                }
 1382            }
 1383
 01384            if (query.User is not null)
 1385            {
 01386                AddUserToQuery(query, query.User);
 1387            }
 1388
 01389            return _itemRepository.GetCount(query);
 1390        }
 1391
 1392        public ItemCounts GetItemCounts(InternalItemsQuery query)
 1393        {
 01394            if (query.Recursive && !query.ParentId.IsEmpty())
 1395            {
 01396                var parent = GetItemById(query.ParentId);
 01397                if (parent is not null)
 1398                {
 01399                    SetTopParentIdsOrAncestors(query, [parent]);
 1400                }
 1401            }
 1402
 01403            if (query.User is not null)
 1404            {
 01405                AddUserToQuery(query, query.User);
 1406            }
 1407
 01408            return _itemRepository.GetItemCounts(query);
 1409        }
 1410
 1411        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
 1412        {
 01413            SetTopParentIdsOrAncestors(query, parents);
 1414
 01415            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1416            {
 01417                if (query.User is not null)
 1418                {
 01419                    AddUserToQuery(query, query.User);
 1420                }
 1421            }
 1422
 01423            return _itemRepository.GetItemList(query);
 1424        }
 1425
 1426        public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, Coll
 1427        {
 01428            SetTopParentIdsOrAncestors(query, parents);
 1429
 01430            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1431            {
 01432                if (query.User is not null)
 1433                {
 01434                    AddUserToQuery(query, query.User);
 1435                }
 1436            }
 1437
 01438            return _itemRepository.GetLatestItemList(query, collectionType);
 1439        }
 1440
 1441        public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents
 1442        {
 01443            SetTopParentIdsOrAncestors(query, parents);
 1444
 01445            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1446            {
 01447                if (query.User is not null)
 1448                {
 01449                    AddUserToQuery(query, query.User);
 1450                }
 1451            }
 1452
 01453            return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
 1454        }
 1455
 1456        public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
 1457        {
 01458            if (query.User is not null)
 1459            {
 01460                AddUserToQuery(query, query.User);
 1461            }
 1462
 01463            if (query.EnableTotalRecordCount)
 1464            {
 01465                return _itemRepository.GetItems(query);
 1466            }
 1467
 01468            return new QueryResult<BaseItem>(
 01469                query.StartIndex,
 01470                null,
 01471                _itemRepository.GetItemList(query));
 1472        }
 1473
 1474        public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
 1475        {
 91476            if (query.User is not null)
 1477            {
 01478                AddUserToQuery(query, query.User);
 1479            }
 1480
 91481            return _itemRepository.GetItemIdsList(query);
 1482        }
 1483
 1484        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
 1485        {
 01486            if (query.User is not null)
 1487            {
 01488                AddUserToQuery(query, query.User);
 1489            }
 1490
 01491            SetTopParentOrAncestorIds(query);
 01492            return _itemRepository.GetStudios(query);
 1493        }
 1494
 1495        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
 1496        {
 01497            if (query.User is not null)
 1498            {
 01499                AddUserToQuery(query, query.User);
 1500            }
 1501
 01502            SetTopParentOrAncestorIds(query);
 01503            return _itemRepository.GetGenres(query);
 1504        }
 1505
 1506        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
 1507        {
 01508            if (query.User is not null)
 1509            {
 01510                AddUserToQuery(query, query.User);
 1511            }
 1512
 01513            SetTopParentOrAncestorIds(query);
 01514            return _itemRepository.GetMusicGenres(query);
 1515        }
 1516
 1517        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
 1518        {
 01519            if (query.User is not null)
 1520            {
 01521                AddUserToQuery(query, query.User);
 1522            }
 1523
 01524            SetTopParentOrAncestorIds(query);
 01525            return _itemRepository.GetAllArtists(query);
 1526        }
 1527
 1528        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
 1529        {
 01530            if (query.User is not null)
 1531            {
 01532                AddUserToQuery(query, query.User);
 1533            }
 1534
 01535            SetTopParentOrAncestorIds(query);
 01536            return _itemRepository.GetArtists(query);
 1537        }
 1538
 1539        private void SetTopParentOrAncestorIds(InternalItemsQuery query)
 1540        {
 01541            var ancestorIds = query.AncestorIds;
 01542            int len = ancestorIds.Length;
 01543            if (len == 0)
 1544            {
 01545                return;
 1546            }
 1547
 01548            var parents = new BaseItem[len];
 01549            for (int i = 0; i < len; i++)
 1550            {
 01551                parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id:
 01552                if (parents[i] is not (ICollectionFolder or UserView))
 1553                {
 01554                    return;
 1555                }
 1556            }
 1557
 1558            // Optimize by querying against top level views
 01559            query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 01560            query.AncestorIds = [];
 1561
 1562            // Prevent searching in all libraries due to empty filter
 01563            if (query.TopParentIds.Length == 0)
 1564            {
 01565                query.TopParentIds = [Guid.NewGuid()];
 1566            }
 01567        }
 1568
 1569        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
 1570        {
 01571            if (query.User is not null)
 1572            {
 01573                AddUserToQuery(query, query.User);
 1574            }
 1575
 01576            SetTopParentOrAncestorIds(query);
 01577            return _itemRepository.GetAlbumArtists(query);
 1578        }
 1579
 1580        public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
 1581        {
 171582            if (query.Recursive && !query.ParentId.IsEmpty())
 1583            {
 161584                var parent = GetItemById(query.ParentId);
 161585                if (parent is not null)
 1586                {
 161587                    SetTopParentIdsOrAncestors(query, [parent]);
 1588                }
 1589            }
 1590
 171591            if (query.User is not null)
 1592            {
 11593                AddUserToQuery(query, query.User);
 1594            }
 1595
 171596            if (query.EnableTotalRecordCount)
 1597            {
 11598                return _itemRepository.GetItems(query);
 1599            }
 1600
 161601            return new QueryResult<BaseItem>(
 161602                query.StartIndex,
 161603                null,
 161604                _itemRepository.GetItemList(query));
 1605        }
 1606
 1607        private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
 1608        {
 541609            if (parents.All(i => i is ICollectionFolder || i is UserView))
 1610            {
 1611                // Optimize by querying against top level views
 161612                query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 1613
 1614                // Prevent searching in all libraries due to empty filter
 161615                if (query.TopParentIds.Length == 0)
 1616                {
 161617                    query.TopParentIds = [Guid.NewGuid()];
 1618                }
 1619            }
 1620            else
 1621            {
 1622                // We need to be able to query from any arbitrary ancestor up the tree
 381623                query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
 1624
 1625                // Prevent searching in all libraries due to empty filter
 381626                if (query.AncestorIds.Length == 0)
 1627                {
 01628                    query.AncestorIds = [Guid.NewGuid()];
 1629                }
 1630            }
 1631
 541632            query.Parent = null;
 541633        }
 1634
 1635        private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
 1636        {
 21637            if (query.AncestorIds.Length == 0 &&
 21638                query.ParentId.IsEmpty() &&
 21639                query.ChannelIds.Count == 0 &&
 21640                query.TopParentIds.Length == 0 &&
 21641                string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
 21642                string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
 21643                query.ItemIds.Length == 0)
 1644            {
 11645                var userViews = UserViewManager.GetUserViews(new UserViewQuery
 11646                {
 11647                    User = user,
 11648                    IncludeHidden = true,
 11649                    IncludeExternalContent = allowExternalContent
 11650                });
 1651
 11652                query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
 1653
 1654                // Prevent searching in all libraries due to empty filter
 11655                if (query.TopParentIds.Length == 0)
 1656                {
 11657                    query.TopParentIds = [Guid.NewGuid()];
 1658                }
 1659            }
 21660        }
 1661
 1662        private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
 1663        {
 161664            if (item is UserView view)
 1665            {
 01666                if (view.ViewType == CollectionType.livetv)
 1667                {
 01668                    return [view.Id];
 1669                }
 1670
 1671                // Translate view into folders
 01672                if (!view.DisplayParentId.IsEmpty())
 1673                {
 01674                    var displayParent = GetItemById(view.DisplayParentId);
 01675                    if (displayParent is not null)
 1676                    {
 01677                        return GetTopParentIdsForQuery(displayParent, user);
 1678                    }
 1679
 01680                    return [];
 1681                }
 1682
 01683                if (!view.ParentId.IsEmpty())
 1684                {
 01685                    var displayParent = GetItemById(view.ParentId);
 01686                    if (displayParent is not null)
 1687                    {
 01688                        return GetTopParentIdsForQuery(displayParent, user);
 1689                    }
 1690
 01691                    return [];
 1692                }
 1693
 1694                // Handle grouping
 01695                if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.V
 01696                    && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
 1697                {
 01698                    return GetUserRootFolder()
 01699                        .GetChildren(user, true)
 01700                        .OfType<CollectionFolder>()
 01701                        .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
 01702                        .Where(i => user.IsFolderGrouped(i.Id))
 01703                        .SelectMany(i => GetTopParentIdsForQuery(i, user));
 1704                }
 1705
 01706                return [];
 1707            }
 1708
 161709            if (item is CollectionFolder collectionFolder)
 1710            {
 161711                return collectionFolder.PhysicalFolderIds;
 1712            }
 1713
 01714            var topParent = item.GetTopParent();
 01715            if (topParent is not null)
 1716            {
 01717                return [topParent.Id];
 1718            }
 1719
 01720            return [];
 1721        }
 1722
 1723        /// <summary>
 1724        /// Gets the intros.
 1725        /// </summary>
 1726        /// <param name="item">The item.</param>
 1727        /// <param name="user">The user.</param>
 1728        /// <returns>IEnumerable{System.String}.</returns>
 1729        public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
 1730        {
 1731            if (IntroProviders.Length == 0)
 1732            {
 1733                return [];
 1734            }
 1735
 1736            var tasks = IntroProviders
 1737                .Select(i => GetIntros(i, item, user));
 1738
 1739            var items = await Task.WhenAll(tasks).ConfigureAwait(false);
 1740
 1741            return items
 1742                .SelectMany(i => i)
 1743                .Select(ResolveIntro)
 1744                .Where(i => i is not null)!; // null values got filtered out
 1745        }
 1746
 1747        /// <summary>
 1748        /// Gets the intros.
 1749        /// </summary>
 1750        /// <param name="provider">The provider.</param>
 1751        /// <param name="item">The item.</param>
 1752        /// <param name="user">The user.</param>
 1753        /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
 1754        private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
 1755        {
 1756            try
 1757            {
 1758                return await provider.GetIntros(item, user).ConfigureAwait(false);
 1759            }
 1760            catch (Exception ex)
 1761            {
 1762                _logger.LogError(ex, "Error getting intros");
 1763
 1764                return [];
 1765            }
 1766        }
 1767
 1768        /// <summary>
 1769        /// Resolves the intro.
 1770        /// </summary>
 1771        /// <param name="info">The info.</param>
 1772        /// <returns>Video.</returns>
 1773        private Video? ResolveIntro(IntroInfo info)
 1774        {
 01775            Video? video = null;
 1776
 01777            if (info.ItemId.HasValue)
 1778            {
 1779                // Get an existing item by Id
 01780                video = GetItemById(info.ItemId.Value) as Video;
 1781
 01782                if (video is null)
 1783                {
 01784                    _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
 1785                }
 1786            }
 01787            else if (!string.IsNullOrEmpty(info.Path))
 1788            {
 1789                try
 1790                {
 1791                    // Try to resolve the path into a video
 01792                    video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
 1793
 01794                    if (video is null)
 1795                    {
 01796                        _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
 1797                    }
 1798                    else
 1799                    {
 1800                        // Pull the saved db item that will include metadata
 01801                        var dbItem = GetItemById(video.Id) as Video;
 1802
 01803                        if (dbItem is not null)
 1804                        {
 01805                            video = dbItem;
 1806                        }
 1807                        else
 1808                        {
 01809                            return null;
 1810                        }
 1811                    }
 01812                }
 01813                catch (Exception ex)
 1814                {
 01815                    _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
 01816                }
 1817            }
 1818            else
 1819            {
 01820                _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
 1821            }
 1822
 01823            return video;
 01824        }
 1825
 1826        /// <inheritdoc />
 1827        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortO
 1828        {
 11829            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1830
 41831            foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
 1832            {
 11833                if (orderBy is RandomComparer)
 1834                {
 01835                    var randomItems = items.ToArray();
 01836                    Random.Shared.Shuffle(randomItems);
 01837                    items = randomItems;
 1838                    // Items are no longer ordered at this point, so set orderedItems back to null
 01839                    orderedItems = null;
 1840                }
 11841                else if (orderedItems is null)
 1842                {
 11843                    orderedItems = sortOrder == SortOrder.Descending
 11844                        ? items.OrderByDescending(i => i, orderBy)
 11845                        : items.OrderBy(i => i, orderBy);
 1846                }
 1847                else
 1848                {
 01849                    orderedItems = sortOrder == SortOrder.Descending
 01850                        ? orderedItems!.ThenByDescending(i => i, orderBy)
 01851                        : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
 1852                }
 1853            }
 1854
 11855            return orderedItems ?? items;
 1856        }
 1857
 1858        /// <inheritdoc />
 1859        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, Sort
 1860        {
 01861            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1862
 01863            foreach (var (name, sortOrder) in orderBy)
 1864            {
 01865                var comparer = GetComparer(name, user);
 01866                if (comparer is null)
 1867                {
 1868                    continue;
 1869                }
 1870
 01871                if (comparer is RandomComparer)
 1872                {
 01873                    var randomItems = items.ToArray();
 01874                    Random.Shared.Shuffle(randomItems);
 01875                    items = randomItems;
 1876                    // Items are no longer ordered at this point, so set orderedItems back to null
 01877                    orderedItems = null;
 1878                }
 01879                else if (orderedItems is null)
 1880                {
 01881                    orderedItems = sortOrder == SortOrder.Descending
 01882                        ? items.OrderByDescending(i => i, comparer)
 01883                        : items.OrderBy(i => i, comparer);
 1884                }
 1885                else
 1886                {
 01887                    orderedItems = sortOrder == SortOrder.Descending
 01888                        ? orderedItems!.ThenByDescending(i => i, comparer)
 01889                        : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
 1890                }
 1891            }
 1892
 01893            return orderedItems ?? items;
 1894        }
 1895
 1896        /// <summary>
 1897        /// Gets the comparer.
 1898        /// </summary>
 1899        /// <param name="name">The name.</param>
 1900        /// <param name="user">The user.</param>
 1901        /// <returns>IBaseItemComparer.</returns>
 1902        private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
 1903        {
 11904            var comparer = Comparers.FirstOrDefault(c => name == c.Type);
 1905
 1906            // If it requires a user, create a new one, and assign the user
 11907            if (comparer is IUserBaseItemComparer)
 1908            {
 01909                var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null fo
 1910
 01911                userComparer.User = user;
 01912                userComparer.UserManager = _userManager;
 01913                userComparer.UserDataManager = _userDataManager;
 1914
 01915                return userComparer;
 1916            }
 1917
 11918            return comparer;
 1919        }
 1920
 1921        /// <inheritdoc />
 1922        public void CreateItem(BaseItem item, BaseItem? parent)
 1923        {
 01924            CreateItems([item], parent, CancellationToken.None);
 01925        }
 1926
 1927        /// <inheritdoc />
 1928        public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
 1929        {
 21930            _itemRepository.SaveItems(items, cancellationToken);
 1931
 81932            foreach (var item in items)
 1933            {
 21934                RegisterItem(item);
 1935            }
 1936
 21937            if (ItemAdded is not null)
 1938            {
 81939                foreach (var item in items)
 1940                {
 1941                    // With the live tv guide this just creates too much noise
 21942                    if (item.SourceType != SourceType.Library)
 1943                    {
 1944                        continue;
 1945                    }
 1946
 1947                    try
 1948                    {
 21949                        ItemAdded(
 21950                            this,
 21951                            new ItemChangeEventArgs
 21952                            {
 21953                                Item = item,
 21954                                Parent = parent ?? item.GetParent()
 21955                            });
 21956                    }
 01957                    catch (Exception ex)
 1958                    {
 01959                        _logger.LogError(ex, "Error in ItemAdded event handler");
 01960                    }
 1961                }
 1962            }
 21963        }
 1964
 1965        private bool ImageNeedsRefresh(ItemImageInfo image)
 1966        {
 01967            if (image.Path is not null && image.IsLocalFile)
 1968            {
 01969                if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
 1970                {
 01971                    return true;
 1972                }
 1973
 1974                try
 1975                {
 01976                    return image.DateModified.Subtract(_fileSystem.GetLastWriteTimeUtc(image.Path)).Duration().TotalSeco
 1977                }
 01978                catch (Exception ex)
 1979                {
 01980                    _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
 01981                    return false;
 1982                }
 1983            }
 1984
 01985            return image.Path is not null && !image.IsLocalFile;
 01986        }
 1987
 1988        /// <inheritdoc />
 1989        public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
 1990        {
 1991            ArgumentNullException.ThrowIfNull(item);
 1992
 1993            var outdated = forceUpdate
 1994                ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
 1995                : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
 1996            // Skip image processing if current or live tv source
 1997            if (outdated.Length == 0 || item.SourceType != SourceType.Library)
 1998            {
 1999                RegisterItem(item);
 2000                return;
 2001            }
 2002
 2003            foreach (var img in outdated)
 2004            {
 2005                var image = img;
 2006                if (!img.IsLocalFile)
 2007                {
 2008                    try
 2009                    {
 2010                        var index = item.GetImageIndex(img);
 2011                        image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
 2012                    }
 2013                    catch (ArgumentException)
 2014                    {
 2015                        _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
 2016                        continue;
 2017                    }
 2018                    catch (Exception ex) when (ex is InvalidOperationException or IOException)
 2019                    {
 2020                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
 2021                        continue;
 2022                    }
 2023                    catch (HttpRequestException ex)
 2024                    {
 2025                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", im
 2026                        continue;
 2027                    }
 2028                }
 2029
 2030                ImageDimensions size;
 2031                try
 2032                {
 2033                    size = _imageProcessor.GetImageDimensions(item, image);
 2034                    image.Width = size.Width;
 2035                    image.Height = size.Height;
 2036                }
 2037                catch (Exception ex)
 2038                {
 2039                    _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
 2040                    size = default;
 2041                    image.Width = 0;
 2042                    image.Height = 0;
 2043                }
 2044
 2045                try
 2046                {
 2047                    var blurhash = _imageProcessor.GetImageBlurHash(image.Path, size);
 2048                    image.BlurHash = blurhash;
 2049                }
 2050                catch (Exception ex)
 2051                {
 2052                    _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
 2053                    image.BlurHash = string.Empty;
 2054                }
 2055
 2056                try
 2057                {
 2058                    var modifiedDate = _fileSystem.GetLastWriteTimeUtc(image.Path);
 2059                    image.DateModified = modifiedDate;
 2060                }
 2061                catch (Exception ex)
 2062                {
 2063                    _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
 2064                }
 2065            }
 2066
 2067            _itemRepository.SaveImages(item);
 2068
 2069            RegisterItem(item);
 2070        }
 2071
 2072        /// <inheritdoc />
 2073        public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, 
 2074        {
 2075            foreach (var item in items)
 2076            {
 2077                item.DateLastSaved = DateTime.UtcNow;
 2078                await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
 2079
 2080                // Modify again, so saved value is after write time of externally saved metadata
 2081                item.DateLastSaved = DateTime.UtcNow;
 2082            }
 2083
 2084            _itemRepository.SaveItems(items, cancellationToken);
 2085
 2086            if (ItemUpdated is not null)
 2087            {
 2088                foreach (var item in items)
 2089                {
 2090                    // With the live tv guide this just creates too much noise
 2091                    if (item.SourceType != SourceType.Library)
 2092                    {
 2093                        continue;
 2094                    }
 2095
 2096                    try
 2097                    {
 2098                        ItemUpdated(
 2099                            this,
 2100                            new ItemChangeEventArgs
 2101                            {
 2102                                Item = item,
 2103                                Parent = parent,
 2104                                UpdateReason = updateReason
 2105                            });
 2106                    }
 2107                    catch (Exception ex)
 2108                    {
 2109                        _logger.LogError(ex, "Error in ItemUpdated event handler");
 2110                    }
 2111                }
 2112            }
 2113        }
 2114
 2115        /// <inheritdoc />
 2116        public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance
 852117            => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
 2118
 2119        public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
 2120        {
 2121            if (item.IsFileProtocol)
 2122            {
 2123                await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
 2124            }
 2125
 2126            await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
 2127        }
 2128
 2129        /// <summary>
 2130        /// Reports the item removed.
 2131        /// </summary>
 2132        /// <param name="item">The item.</param>
 2133        /// <param name="parent">The parent item.</param>
 2134        public void ReportItemRemoved(BaseItem item, BaseItem parent)
 2135        {
 22136            if (ItemRemoved is not null)
 2137            {
 2138                try
 2139                {
 22140                    ItemRemoved(
 22141                        this,
 22142                        new ItemChangeEventArgs
 22143                        {
 22144                            Item = item,
 22145                            Parent = parent
 22146                        });
 22147                }
 02148                catch (Exception ex)
 2149                {
 02150                    _logger.LogError(ex, "Error in ItemRemoved event handler");
 02151                }
 2152            }
 22153        }
 2154
 2155        /// <summary>
 2156        /// Retrieves the item.
 2157        /// </summary>
 2158        /// <param name="id">The id.</param>
 2159        /// <returns>BaseItem.</returns>
 2160        public BaseItem RetrieveItem(Guid id)
 2161        {
 2332162            return _itemRepository.RetrieveItem(id);
 2163        }
 2164
 2165        public List<Folder> GetCollectionFolders(BaseItem item)
 2166        {
 6362167            return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
 2168        }
 2169
 2170        public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2171        {
 6882172            while (item is not null)
 2173            {
 6882174                var parent = item.GetParent();
 2175
 6882176                if (parent is AggregateFolder)
 2177                {
 2178                    break;
 2179                }
 2180
 6662181                if (parent is null)
 2182                {
 6142183                    var owner = item.GetOwner();
 2184
 6142185                    if (owner is null)
 2186                    {
 2187                        break;
 2188                    }
 2189
 02190                    item = owner;
 2191                }
 2192                else
 2193                {
 522194                    item = parent;
 2195                }
 2196            }
 2197
 6362198            if (item is null)
 2199            {
 02200                return new List<Folder>();
 2201            }
 2202
 6362203            return GetCollectionFoldersInternal(item, allUserRootChildren);
 2204        }
 2205
 2206        private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2207        {
 6362208            return allUserRootChildren
 6362209                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 6362210                .ToList();
 2211        }
 2212
 2213        public LibraryOptions GetLibraryOptions(BaseItem item)
 2214        {
 4212215            if (item is CollectionFolder collectionFolder)
 2216            {
 742217                return collectionFolder.GetLibraryOptions();
 2218            }
 2219
 2220            // List.Find is more performant than FirstOrDefault due to enumerator allocation
 3472221            return GetCollectionFolders(item)
 3472222                .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
 3472223                ? collectionFolder2.GetLibraryOptions()
 3472224                : new LibraryOptions();
 2225        }
 2226
 2227        public CollectionType? GetContentType(BaseItem item)
 2228        {
 392229            var configuredContentType = GetConfiguredContentType(item, false);
 392230            if (configuredContentType is not null)
 2231            {
 02232                return configuredContentType;
 2233            }
 2234
 392235            configuredContentType = GetConfiguredContentType(item, true);
 392236            if (configuredContentType is not null)
 2237            {
 02238                return configuredContentType;
 2239            }
 2240
 392241            return GetInheritedContentType(item);
 2242        }
 2243
 2244        public CollectionType? GetInheritedContentType(BaseItem item)
 2245        {
 392246            var type = GetTopFolderContentType(item);
 2247
 392248            if (type is not null)
 2249            {
 02250                return type;
 2251            }
 2252
 392253            return item.GetParents()
 392254                .Select(GetConfiguredContentType)
 392255                .LastOrDefault(i => i is not null);
 2256        }
 2257
 2258        public CollectionType? GetConfiguredContentType(BaseItem item)
 2259        {
 02260            return GetConfiguredContentType(item, false);
 2261        }
 2262
 2263        public CollectionType? GetConfiguredContentType(string path)
 2264        {
 02265            return GetContentTypeOverride(path, false);
 2266        }
 2267
 2268        public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
 2269        {
 782270            if (item is ICollectionFolder collectionFolder)
 2271            {
 02272                return collectionFolder.CollectionType;
 2273            }
 2274
 782275            return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
 2276        }
 2277
 2278        private CollectionType? GetContentTypeOverride(string path, bool inherit)
 2279        {
 982280            var nameValuePair = _configurationManager.Configuration.ContentTypes
 982281                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
 982282                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
 982283                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
 982284            if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
 2285            {
 02286                return collectionType;
 2287            }
 2288
 982289            return null;
 2290        }
 2291
 2292        private CollectionType? GetTopFolderContentType(BaseItem item)
 2293        {
 392294            if (item is null)
 2295            {
 02296                return null;
 2297            }
 2298
 392299            while (!item.ParentId.IsEmpty())
 2300            {
 02301                var parent = item.GetParent();
 02302                if (parent is null || parent is AggregateFolder)
 2303                {
 2304                    break;
 2305                }
 2306
 02307                item = parent;
 2308            }
 2309
 392310            return GetUserRootFolder().Children
 392311                .OfType<ICollectionFolder>()
 392312                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 392313                .Select(i => i.CollectionType)
 392314                .FirstOrDefault(i => i is not null);
 2315        }
 2316
 2317        public UserView GetNamedView(
 2318            User user,
 2319            string name,
 2320            CollectionType? viewType,
 2321            string sortName)
 2322        {
 02323            return GetNamedView(user, name, Guid.Empty, viewType, sortName);
 2324        }
 2325
 2326        public UserView GetNamedView(
 2327            string name,
 2328            CollectionType viewType,
 2329            string sortName)
 2330        {
 02331            var path = Path.Combine(
 02332                _configurationManager.ApplicationPaths.InternalMetadataPath,
 02333                "views",
 02334                _fileSystem.GetValidFilename(viewType.ToString()));
 2335
 02336            var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 2337
 02338            var item = GetItemById(id) as UserView;
 2339
 02340            var refresh = false;
 2341
 02342            if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
 2343            {
 02344                var info = Directory.CreateDirectory(path);
 02345                item = new UserView
 02346                {
 02347                    Path = path,
 02348                    Id = id,
 02349                    DateCreated = info.CreationTimeUtc,
 02350                    DateModified = info.LastWriteTimeUtc,
 02351                    Name = name,
 02352                    ViewType = viewType,
 02353                    ForcedSortName = sortName
 02354                };
 2355
 02356                CreateItem(item, null);
 2357
 02358                refresh = true;
 2359            }
 2360
 02361            if (refresh)
 2362            {
 02363                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu
 02364                ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref
 2365            }
 2366
 02367            return item;
 2368        }
 2369
 2370        public UserView GetNamedView(
 2371            User user,
 2372            string name,
 2373            Guid parentId,
 2374            CollectionType? viewType,
 2375            string sortName)
 2376        {
 02377            var parentIdString = parentId.IsEmpty()
 02378                ? null
 02379                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02380            var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin
 2381
 02382            var id = GetNewItemId(idValues, typeof(UserView));
 2383
 02384            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2385
 02386            var item = GetItemById(id) as UserView;
 2387
 02388            var isNew = false;
 2389
 02390            if (item is null)
 2391            {
 02392                var info = Directory.CreateDirectory(path);
 02393                item = new UserView
 02394                {
 02395                    Path = path,
 02396                    Id = id,
 02397                    DateCreated = info.CreationTimeUtc,
 02398                    DateModified = info.LastWriteTimeUtc,
 02399                    Name = name,
 02400                    ViewType = viewType,
 02401                    ForcedSortName = sortName,
 02402                    UserId = user.Id,
 02403                    DisplayParentId = parentId
 02404                };
 2405
 02406                CreateItem(item, null);
 2407
 02408                isNew = true;
 2409            }
 2410
 02411            var lastRefreshedUtc = item.DateLastRefreshed;
 02412            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2413
 02414            if (!refresh && !item.DisplayParentId.IsEmpty())
 2415            {
 02416                var displayParent = GetItemById(item.DisplayParentId);
 02417                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2418            }
 2419
 02420            if (refresh)
 2421            {
 02422                ProviderManager.QueueRefresh(
 02423                    item.Id,
 02424                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02425                    {
 02426                        // Need to force save to increment DateLastSaved
 02427                        ForceSave = true
 02428                    },
 02429                    RefreshPriority.Normal);
 2430            }
 2431
 02432            return item;
 2433        }
 2434
 2435        public UserView GetShadowView(
 2436            BaseItem parent,
 2437            CollectionType? viewType,
 2438            string sortName)
 2439        {
 02440            ArgumentNullException.ThrowIfNull(parent);
 2441
 02442            var name = parent.Name;
 02443            var parentId = parent.Id;
 2444
 02445            var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
 2446
 02447            var id = GetNewItemId(idValues, typeof(UserView));
 2448
 02449            var path = parent.Path;
 2450
 02451            var item = GetItemById(id) as UserView;
 2452
 02453            var isNew = false;
 2454
 02455            if (item is null)
 2456            {
 02457                var info = Directory.CreateDirectory(path);
 02458                item = new UserView
 02459                {
 02460                    Path = path,
 02461                    Id = id,
 02462                    DateCreated = info.CreationTimeUtc,
 02463                    DateModified = info.LastWriteTimeUtc,
 02464                    Name = name,
 02465                    ViewType = viewType,
 02466                    ForcedSortName = sortName,
 02467                    DisplayParentId = parentId
 02468                };
 2469
 02470                CreateItem(item, null);
 2471
 02472                isNew = true;
 2473            }
 2474
 02475            var lastRefreshedUtc = item.DateLastRefreshed;
 02476            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2477
 02478            if (!refresh && !item.DisplayParentId.IsEmpty())
 2479            {
 02480                var displayParent = GetItemById(item.DisplayParentId);
 02481                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2482            }
 2483
 02484            if (refresh)
 2485            {
 02486                ProviderManager.QueueRefresh(
 02487                    item.Id,
 02488                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02489                    {
 02490                        // Need to force save to increment DateLastSaved
 02491                        ForceSave = true
 02492                    },
 02493                    RefreshPriority.Normal);
 2494            }
 2495
 02496            return item;
 2497        }
 2498
 2499        public UserView GetNamedView(
 2500            string name,
 2501            Guid parentId,
 2502            CollectionType? viewType,
 2503            string sortName,
 2504            string uniqueId)
 2505        {
 02506            ArgumentException.ThrowIfNullOrEmpty(name);
 2507
 02508            var parentIdString = parentId.IsEmpty()
 02509                ? null
 02510                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02511            var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E
 02512            if (!string.IsNullOrEmpty(uniqueId))
 2513            {
 02514                idValues += uniqueId;
 2515            }
 2516
 02517            var id = GetNewItemId(idValues, typeof(UserView));
 2518
 02519            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2520
 02521            var item = GetItemById(id) as UserView;
 2522
 02523            var isNew = false;
 2524
 02525            if (item is null)
 2526            {
 02527                var info = Directory.CreateDirectory(path);
 02528                item = new UserView
 02529                {
 02530                    Path = path,
 02531                    Id = id,
 02532                    DateCreated = info.CreationTimeUtc,
 02533                    DateModified = info.LastWriteTimeUtc,
 02534                    Name = name,
 02535                    ViewType = viewType,
 02536                    ForcedSortName = sortName,
 02537                    DisplayParentId = parentId
 02538                };
 2539
 02540                CreateItem(item, null);
 2541
 02542                isNew = true;
 2543            }
 2544
 02545            if (viewType != item.ViewType)
 2546            {
 02547                item.ViewType = viewType;
 02548                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult
 2549            }
 2550
 02551            var lastRefreshedUtc = item.DateLastRefreshed;
 02552            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2553
 02554            if (!refresh && !item.DisplayParentId.IsEmpty())
 2555            {
 02556                var displayParent = GetItemById(item.DisplayParentId);
 02557                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2558            }
 2559
 02560            if (refresh)
 2561            {
 02562                ProviderManager.QueueRefresh(
 02563                    item.Id,
 02564                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02565                    {
 02566                        // Need to force save to increment DateLastSaved
 02567                        ForceSave = true
 02568                    },
 02569                    RefreshPriority.Normal);
 2570            }
 2571
 02572            return item;
 2573        }
 2574
 2575        public BaseItem GetParentItem(Guid? parentId, Guid? userId)
 2576        {
 32577            if (parentId.HasValue)
 2578            {
 02579                return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}"
 2580            }
 2581
 32582            if (!userId.IsNullOrEmpty())
 2583            {
 32584                return GetUserRootFolder();
 2585            }
 2586
 02587            return RootFolder;
 2588        }
 2589
 2590        /// <inheritdoc />
 2591        public void QueueLibraryScan()
 2592        {
 02593            _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
 02594        }
 2595
 2596        /// <inheritdoc />
 2597        public int? GetSeasonNumberFromPath(string path, Guid? parentId)
 2598        {
 02599            var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
 02600            return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
 2601        }
 2602
 2603        /// <inheritdoc />
 2604        public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
 2605        {
 02606            var series = episode.Series;
 02607            bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis
 02608            if (!isAbsoluteNaming.Value)
 2609            {
 2610                // In other words, no filter applied
 02611                isAbsoluteNaming = null;
 2612            }
 2613
 02614            var resolver = new EpisodeResolver(_namingOptions);
 2615
 02616            var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
 2617
 02618            EpisodeInfo? episodeInfo = null;
 02619            if (episode.IsFileProtocol)
 2620            {
 02621                episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
 2622                // Resolve from parent folder if it's not the Season folder
 02623                var parent = episode.GetParent();
 02624                if (episodeInfo is null && parent.GetType() == typeof(Folder))
 2625                {
 02626                    episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
 02627                    if (episodeInfo is not null)
 2628                    {
 2629                        // add the container
 02630                        episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
 2631                    }
 2632                }
 2633            }
 2634
 02635            var changed = false;
 02636            if (episodeInfo is null)
 2637            {
 02638                return changed;
 2639            }
 2640
 02641            if (episodeInfo.IsByDate)
 2642            {
 02643                if (episode.IndexNumber.HasValue)
 2644                {
 02645                    episode.IndexNumber = null;
 02646                    changed = true;
 2647                }
 2648
 02649                if (episode.IndexNumberEnd.HasValue)
 2650                {
 02651                    episode.IndexNumberEnd = null;
 02652                    changed = true;
 2653                }
 2654
 02655                if (!episode.PremiereDate.HasValue)
 2656                {
 02657                    if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
 2658                    {
 02659                        episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo
 2660                    }
 2661
 02662                    if (episode.PremiereDate.HasValue)
 2663                    {
 02664                        changed = true;
 2665                    }
 2666                }
 2667
 02668                if (!episode.ProductionYear.HasValue)
 2669                {
 02670                    episode.ProductionYear = episodeInfo.Year;
 2671
 02672                    if (episode.ProductionYear.HasValue)
 2673                    {
 02674                        changed = true;
 2675                    }
 2676                }
 2677            }
 2678            else
 2679            {
 02680                if (!episode.IndexNumber.HasValue || forceRefresh)
 2681                {
 02682                    if (episode.IndexNumber != episodeInfo.EpisodeNumber)
 2683                    {
 02684                        changed = true;
 2685                    }
 2686
 02687                    episode.IndexNumber = episodeInfo.EpisodeNumber;
 2688                }
 2689
 02690                if (!episode.IndexNumberEnd.HasValue || forceRefresh)
 2691                {
 02692                    if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
 2693                    {
 02694                        changed = true;
 2695                    }
 2696
 02697                    episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
 2698                }
 2699
 02700                if (!episode.ParentIndexNumber.HasValue || forceRefresh)
 2701                {
 02702                    if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
 2703                    {
 02704                        changed = true;
 2705                    }
 2706
 02707                    episode.ParentIndexNumber = episodeInfo.SeasonNumber;
 2708                }
 2709            }
 2710
 02711            if (!episode.ParentIndexNumber.HasValue)
 2712            {
 02713                var season = episode.Season;
 2714
 02715                if (season is not null)
 2716                {
 02717                    episode.ParentIndexNumber = season.IndexNumber;
 2718                }
 2719
 02720                if (episode.ParentIndexNumber.HasValue)
 2721                {
 02722                    changed = true;
 2723                }
 2724            }
 2725
 02726            return changed;
 2727        }
 2728
 2729        public ItemLookupInfo ParseName(string name)
 2730        {
 02731            var namingOptions = _namingOptions;
 02732            var result = VideoResolver.CleanDateTime(name, namingOptions);
 2733
 02734            return new ItemLookupInfo
 02735            {
 02736                Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name
 02737                Year = result.Year
 02738            };
 2739        }
 2740
 2741        public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID
 2742        {
 2743            // Apply .ignore rules
 2744            var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
 2745            var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co
 2746            if (ownerVideoInfo is null)
 2747            {
 2748                yield break;
 2749            }
 2750
 2751            var count = filtered.Count;
 2752            for (var i = 0; i < count; i++)
 2753            {
 2754                var current = filtered[i];
 2755                if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
 2756                {
 2757                    var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
 2758                    var filesInSubFolderList = filesInSubFolder.ToList();
 2759
 2760                    bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
 2761
 2762                    foreach (var file in filesInSubFolderList)
 2763                    {
 2764                        if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
 2765                        {
 2766                            continue;
 2767                        }
 2768
 2769                        var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
 2770                        if (extra is not null)
 2771                        {
 2772                            yield return extra;
 2773                        }
 2774                    }
 2775                }
 2776                else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo
 2777                {
 2778                    var extra = GetExtra(current, extraType.Value, false);
 2779                    if (extra is not null)
 2780                    {
 2781                        yield return extra;
 2782                    }
 2783                }
 2784            }
 2785
 2786            BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
 2787            {
 2788                var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso
 2789                if (extra is not Video && extra is not Audio)
 2790                {
 2791                    return null;
 2792                }
 2793
 2794                // Try to retrieve it from the db. If we don't find it, use the resolved version
 2795                var itemById = GetItemById(extra.Id);
 2796                if (itemById is not null)
 2797                {
 2798                    extra = itemById;
 2799                }
 2800
 2801                // Only update extra type if it is more specific then the currently known extra type
 2802                if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
 2803                {
 2804                    extra.ExtraType = extraType;
 2805                }
 2806
 2807                extra.ParentId = Guid.Empty;
 2808                extra.OwnerId = owner.Id;
 2809                extra.IsInMixedFolder = isInMixedFolder;
 2810                return extra;
 2811            }
 2812        }
 2813
 2814        public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
 2815        {
 122816            foreach (var map in _configurationManager.Configuration.PathSubstitutions)
 2817            {
 02818                if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
 2819                {
 02820                    return newPath;
 2821                }
 2822            }
 2823
 62824            return path;
 2825        }
 2826
 2827        public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
 2828        {
 02829            return _peopleRepository.GetPeople(query);
 2830        }
 2831
 2832        public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
 2833        {
 62834            if (item.SupportsPeople)
 2835            {
 02836                var people = GetPeople(new InternalPeopleQuery
 02837                {
 02838                    ItemId = item.Id
 02839                });
 2840
 02841                if (people.Count > 0)
 2842                {
 02843                    return people;
 2844                }
 2845            }
 2846
 62847            return [];
 2848        }
 2849
 2850        public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
 2851        {
 02852            return _peopleRepository.GetPeopleNames(query)
 02853            .Select(i =>
 02854            {
 02855                try
 02856                {
 02857                    return GetPerson(i);
 02858                }
 02859                catch (Exception ex)
 02860                {
 02861                    _logger.LogError(ex, "Error getting person");
 02862                    return null;
 02863                }
 02864            })
 02865            .Where(i => i is not null)
 02866            .Where(i => query.User is null || i!.IsVisible(query.User))
 02867            .ToList()!; // null values are filtered out
 2868        }
 2869
 2870        public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
 2871        {
 02872            return _peopleRepository.GetPeopleNames(query);
 2873        }
 2874
 2875        public void UpdatePeople(BaseItem item, List<PersonInfo> people)
 2876        {
 02877            UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
 02878        }
 2879
 2880        /// <inheritdoc />
 2881        public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat
 2882        {
 2883            if (!item.SupportsPeople)
 2884            {
 2885                return;
 2886            }
 2887
 2888            if (people is not null)
 2889            {
 2890                people = people.Where(e => e is not null).ToArray();
 2891                _peopleRepository.UpdatePeople(item.Id, people);
 2892                await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
 2893            }
 2894        }
 2895
 2896        public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re
 2897        {
 2898            foreach (var url in image.Path.Split('|'))
 2899            {
 2900                try
 2901                {
 2902                    _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
 2903
 2904                    await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure
 2905
 2906                    await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai
 2907
 2908                    return item.GetImageInfo(image.Type, imageIndex);
 2909                }
 2910                catch (HttpRequestException ex)
 2911                {
 2912                    if (ex.StatusCode.HasValue
 2913                        && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb
 2914                    {
 2915                        _logger.LogDebug(ex, "Error downloading image {Url}", url);
 2916                        continue;
 2917                    }
 2918
 2919                    throw;
 2920                }
 2921            }
 2922
 2923            if (removeOnFailure)
 2924            {
 2925                // Remove this image to prevent it from retrying over and over
 2926                item.RemoveImage(image);
 2927                await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa
 2928            }
 2929
 2930            throw new InvalidOperationException("Unable to convert any images to local");
 2931        }
 2932
 2933        public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b
 2934        {
 2935            if (string.IsNullOrWhiteSpace(name))
 2936            {
 2937                throw new ArgumentNullException(nameof(name));
 2938            }
 2939
 2940            name = _fileSystem.GetValidFilename(name.Trim());
 2941
 2942            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 2943
 2944            var existingNameCount = 1; // first numbered name will be 2
 2945            var virtualFolderPath = Path.Combine(rootFolderPath, name);
 2946            var originalName = name;
 2947            while (Directory.Exists(virtualFolderPath))
 2948            {
 2949                existingNameCount++;
 2950                name = originalName + existingNameCount;
 2951                virtualFolderPath = Path.Combine(rootFolderPath, name);
 2952            }
 2953
 2954            var mediaPathInfos = options.PathInfos;
 2955            if (mediaPathInfos is not null)
 2956            {
 2957                var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
 2958                if (invalidpath is not null)
 2959                {
 2960                    throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
 2961                }
 2962            }
 2963
 2964            LibraryMonitor.Stop();
 2965
 2966            try
 2967            {
 2968                Directory.CreateDirectory(virtualFolderPath);
 2969
 2970                if (collectionType is not null)
 2971                {
 2972                    var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect
 2973
 2974                    FileHelper.CreateEmpty(path);
 2975                }
 2976
 2977                CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
 2978
 2979                if (mediaPathInfos is not null)
 2980                {
 2981                    foreach (var path in mediaPathInfos)
 2982                    {
 2983                        AddMediaPathInternal(name, path, false);
 2984                    }
 2985                }
 2986            }
 2987            finally
 2988            {
 2989                if (refreshLibrary)
 2990                {
 2991                    await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
 2992
 2993                    StartScanInBackground();
 2994                }
 2995                else
 2996                {
 2997                    // Need to add a delay here or directory watchers may still pick up the changes
 2998                    await Task.Delay(1000).ConfigureAwait(false);
 2999                    LibraryMonitor.Start();
 3000                }
 3001            }
 3002        }
 3003
 3004        private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
 3005        {
 3006            foreach (var person in people)
 3007            {
 3008                cancellationToken.ThrowIfCancellationRequested();
 3009
 3010                var itemUpdateType = ItemUpdateType.MetadataDownload;
 3011                var saveEntity = false;
 3012                var createEntity = false;
 3013                var personEntity = GetPerson(person.Name);
 3014
 3015                if (personEntity is null)
 3016                {
 3017                    try
 3018                    {
 3019                        var path = Person.GetPath(person.Name);
 3020                        var info = Directory.CreateDirectory(path);
 3021                        personEntity = new Person()
 3022                        {
 3023                            Name = person.Name,
 3024                            Id = GetItemByNameId<Person>(path),
 3025                            DateCreated = info.CreationTimeUtc,
 3026                            DateModified = info.LastWriteTimeUtc,
 3027                            Path = path
 3028                        };
 3029
 3030                        personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
 3031                        saveEntity = true;
 3032                        createEntity = true;
 3033                    }
 3034                    catch (Exception ex)
 3035                    {
 3036                        _logger.LogWarning(ex, "Failed to create person {Name}", person.Name);
 3037                        continue;
 3038                    }
 3039                }
 3040
 3041                foreach (var id in person.ProviderIds)
 3042                {
 3043                    if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)
 3044                    {
 3045                        personEntity.SetProviderId(id.Key, id.Value);
 3046                        saveEntity = true;
 3047                    }
 3048                }
 3049
 3050                if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
 3051                {
 3052                    personEntity.SetImage(
 3053                        new ItemImageInfo
 3054                        {
 3055                            Path = person.ImageUrl,
 3056                            Type = ImageType.Primary
 3057                        },
 3058                        0);
 3059
 3060                    saveEntity = true;
 3061                    itemUpdateType = ItemUpdateType.ImageUpdate;
 3062                }
 3063
 3064                if (saveEntity)
 3065                {
 3066                    if (createEntity)
 3067                    {
 3068                        CreateItems([personEntity], null, CancellationToken.None);
 3069                    }
 3070
 3071                    await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
 3072                    personEntity.DateLastSaved = DateTime.UtcNow;
 3073
 3074                    CreateItems([personEntity], null, CancellationToken.None);
 3075                }
 3076            }
 3077        }
 3078
 3079        private void StartScanInBackground()
 3080        {
 33081            Task.Run(() =>
 33082            {
 33083                // No need to start if scanning the library because it will handle it
 33084                ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
 33085            });
 33086        }
 3087
 3088        public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3089        {
 13090            AddMediaPathInternal(virtualFolderName, mediaPath, true);
 03091        }
 3092
 3093        private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
 3094        {
 13095            ArgumentNullException.ThrowIfNull(pathInfo);
 3096
 13097            var path = pathInfo.Path;
 3098
 13099            if (string.IsNullOrWhiteSpace(path))
 3100            {
 03101                throw new ArgumentException(nameof(path));
 3102            }
 3103
 13104            if (!Directory.Exists(path))
 3105            {
 13106                throw new FileNotFoundException("The path does not exist.");
 3107            }
 3108
 03109            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03110            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3111
 03112            var shortcutFilename = Path.GetFileNameWithoutExtension(path);
 3113
 03114            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3115
 03116            while (File.Exists(lnk))
 3117            {
 03118                shortcutFilename += "1";
 03119                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3120            }
 3121
 03122            _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
 3123
 03124            RemoveContentTypeOverrides(path);
 3125
 03126            if (saveLibraryOptions)
 3127            {
 03128                var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3129
 03130                libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
 3131
 03132                SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3133
 03134                CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 3135            }
 03136        }
 3137
 3138        public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3139        {
 03140            ArgumentNullException.ThrowIfNull(mediaPath);
 3141
 03142            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03143            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3144
 03145            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3146
 03147            SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3148
 03149            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03150        }
 3151
 3152        private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
 3153        {
 03154            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 03155            var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
 3156
 03157            if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
 3158            {
 03159                var list = options.PathInfos.ToList();
 3160
 03161                foreach (var location in info.Locations)
 3162                {
 03163                    if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
 3164                    {
 03165                        list.Add(new MediaPathInfo(location));
 3166                    }
 3167                }
 3168
 03169                options.PathInfos = list.ToArray();
 3170            }
 03171        }
 3172
 3173        public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
 3174        {
 3175            if (string.IsNullOrWhiteSpace(name))
 3176            {
 3177                throw new ArgumentNullException(nameof(name));
 3178            }
 3179
 3180            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3181
 3182            var path = Path.Combine(rootFolderPath, name);
 3183
 3184            if (!Directory.Exists(path))
 3185            {
 3186                throw new FileNotFoundException("The media folder does not exist");
 3187            }
 3188
 3189            LibraryMonitor.Stop();
 3190
 3191            try
 3192            {
 3193                Directory.Delete(path, true);
 3194            }
 3195            finally
 3196            {
 3197                CollectionFolder.OnCollectionFolderChange();
 3198
 3199                if (refreshLibrary)
 3200                {
 3201                    await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
 3202
 3203                    StartScanInBackground();
 3204                }
 3205                else
 3206                {
 3207                    // Need to add a delay here or directory watchers may still pick up the changes
 3208                    await Task.Delay(1000).ConfigureAwait(false);
 3209                    LibraryMonitor.Start();
 3210                }
 3211            }
 3212        }
 3213
 3214        private void RemoveContentTypeOverrides(string path)
 3215        {
 03216            if (string.IsNullOrWhiteSpace(path))
 3217            {
 03218                throw new ArgumentNullException(nameof(path));
 3219            }
 3220
 03221            List<NameValuePair>? removeList = null;
 3222
 03223            foreach (var contentType in _configurationManager.Configuration.ContentTypes)
 3224            {
 03225                if (string.IsNullOrWhiteSpace(contentType.Name)
 03226                    || _fileSystem.AreEqual(path, contentType.Name)
 03227                    || _fileSystem.ContainsSubPath(path, contentType.Name))
 3228                {
 03229                    (removeList ??= new()).Add(contentType);
 3230                }
 3231            }
 3232
 03233            if (removeList is not null)
 3234            {
 03235                _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
 03236                    .Except(removeList)
 03237                    .ToArray();
 3238
 03239                _configurationManager.SaveConfiguration();
 3240            }
 03241        }
 3242
 3243        public void RemoveMediaPath(string virtualFolderName, string mediaPath)
 3244        {
 13245            ArgumentException.ThrowIfNullOrEmpty(mediaPath);
 3246
 13247            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 13248            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3249
 13250            if (!Directory.Exists(virtualFolderPath))
 3251            {
 13252                throw new FileNotFoundException(
 13253                    string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder
 3254            }
 3255
 03256            var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
 03257                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 03258                .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String
 3259
 03260            if (!string.IsNullOrEmpty(shortcut))
 3261            {
 03262                _fileSystem.DeleteFile(shortcut);
 3263            }
 3264
 03265            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3266
 03267            libraryOptions.PathInfos = libraryOptions
 03268                .PathInfos
 03269                .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
 03270                .ToArray();
 3271
 03272            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03273        }
 3274
 3275        private static bool ItemIsVisible(BaseItem? item, User? user)
 3276        {
 213277            if (item is null)
 3278            {
 213279                return false;
 3280            }
 3281
 03282            if (user is null)
 3283            {
 03284                return true;
 3285            }
 3286
 03287            return item is UserRootFolder || item.IsVisibleStandalone(user);
 3288        }
 3289    }
 3290}

Methods/Properties

.ctor(MediaBrowser.Controller.IServerApplicationHost,Microsoft.Extensions.Logging.ILoggerFactory,MediaBrowser.Model.Tasks.ITaskManager,MediaBrowser.Controller.Library.IUserManager,MediaBrowser.Controller.Configuration.IServerConfigurationManager,MediaBrowser.Controller.Library.IUserDataManager,System.Lazy`1<MediaBrowser.Controller.Library.ILibraryMonitor>,MediaBrowser.Model.IO.IFileSystem,System.Lazy`1<MediaBrowser.Controller.Providers.IProviderManager>,System.Lazy`1<MediaBrowser.Controller.Library.IUserViewManager>,MediaBrowser.Controller.MediaEncoding.IMediaEncoder,MediaBrowser.Controller.Persistence.IItemRepository,MediaBrowser.Controller.Drawing.IImageProcessor,Emby.Naming.Common.NamingOptions,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Persistence.IPeopleRepository,MediaBrowser.Controller.IO.IPathManager)
get_RootFolder()
get_LibraryMonitor()
get_ProviderManager()
get_UserViewManager()
AddParts(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Resolvers.IResolverIgnoreRule>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Resolvers.IItemResolver>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Library.IIntroProvider>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Sorting.IBaseItemComparer>,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Library.ILibraryPostScanTask>)
RecordConfigurationValues(MediaBrowser.Model.Configuration.ServerConfiguration)
ConfigurationUpdated(System.Object,System.EventArgs)
RegisterItem(MediaBrowser.Controller.Entities.BaseItem)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions,System.Boolean)
DeleteItem(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Library.DeleteOptions,MediaBrowser.Controller.Entities.BaseItem,System.Boolean)
IsInternalItem(MediaBrowser.Controller.Entities.BaseItem)
GetMetadataPaths(MediaBrowser.Controller.Entities.BaseItem,System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.BaseItem>)
GetInternalMetadataPaths(MediaBrowser.Controller.Entities.BaseItem)
ResolveItem(MediaBrowser.Controller.Library.ItemResolveArgs,MediaBrowser.Controller.Resolvers.IItemResolver[])
Resolve(MediaBrowser.Controller.Library.ItemResolveArgs,MediaBrowser.Controller.Resolvers.IItemResolver)
GetNewItemId(System.String,System.Type)
GetNewItemIdInternal(System.String,System.Type,System.Boolean)
ResolvePath(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Controller.Providers.IDirectoryService)
ResolvePath(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Resolvers.IItemResolver[],MediaBrowser.Controller.Entities.Folder,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,MediaBrowser.Model.Configuration.LibraryOptions)
IgnoreFile(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Controller.Entities.BaseItem)
NormalizeRootPathList(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>)
ResolvePaths(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Model.Configuration.LibraryOptions,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>)
ResolvePaths(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.IO.FileSystemMetadata>,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Entities.Folder,MediaBrowser.Model.Configuration.LibraryOptions,System.Nullable`1<Jellyfin.Data.Enums.CollectionType>,MediaBrowser.Controller.Resolvers.IItemResolver[])
CreateRootFolder()
GetUserRootFolder()
FindByPath(System.String,System.Nullable`1<System.Boolean>)
GetPerson(System.String)
GetStudio(System.String)
GetStudioId(System.String)
GetGenreId(System.String)
GetMusicGenreId(System.String)
GetGenre(System.String)
GetMusicGenre(System.String)
GetYear(System.Int32)
GetArtist(System.String)
GetArtist(System.String,MediaBrowser.Controller.Dto.DtoOptions)
CreateItemByName(System.Func`2<System.String,System.String>,System.String,MediaBrowser.Controller.Dto.DtoOptions)
GetItemByNameId(System.String)
ValidatePeopleAsync(System.IProgress`1<System.Double>,System.Threading.CancellationToken)
ValidateMediaLibrary(System.IProgress`1<System.Double>,System.Threading.CancellationToken)
GetVirtualFolders()
GetVirtualFolders(System.Boolean)
GetVirtualFolderInfo(System.String,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.BaseItem>,System.Collections.Generic.HashSet`1<System.Guid>)
GetCollectionType(System.String)
GetItemById(System.Guid)
GetItemById(System.Guid)
GetItemById(System.Guid,System.Guid)
GetItemById(System.Guid,Jellyfin.Database.Implementations.Entities.User)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Boolean)
GetItemList(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetCount(MediaBrowser.Controller.Entities.InternalItemsQuery)
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)