< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Library.LibraryManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Library/LibraryManager.cs
Line coverage
34%
Covered lines: 383
Uncovered lines: 735
Coverable lines: 1118
Total lines: 3389
Line coverage: 34.2%
Branch coverage
28%
Covered branches: 177
Total branches: 630
Branch coverage: 28%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 10/12/2025 - 12:11:07 AM Line coverage: 34.3% (380/1107) Branch coverage: 27.9% (175/626) Total lines: 335711/18/2025 - 12:11:25 AM Line coverage: 34.4% (383/1113) Branch coverage: 28% (177/630) Total lines: 337512/29/2025 - 12:13:19 AM Line coverage: 34.3% (383/1114) Branch coverage: 28% (177/630) Total lines: 33761/19/2026 - 12:13:54 AM Line coverage: 34.2% (383/1118) Branch coverage: 28% (177/630) Total lines: 3389 10/12/2025 - 12:11:07 AM Line coverage: 34.3% (380/1107) Branch coverage: 27.9% (175/626) Total lines: 335711/18/2025 - 12:11:25 AM Line coverage: 34.4% (383/1113) Branch coverage: 28% (177/630) Total lines: 337512/29/2025 - 12:13:19 AM Line coverage: 34.3% (383/1114) Branch coverage: 28% (177/630) Total lines: 33761/19/2026 - 12:13:54 AM Line coverage: 34.2% (383/1118) Branch coverage: 28% (177/630) Total lines: 3389

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_RootFolder()100%44100%
get_LibraryMonitor()100%11100%
get_ProviderManager()100%11100%
get_UserViewManager()100%11100%
AddParts(...)100%11100%
RecordConfigurationValues(...)100%11100%
ConfigurationUpdated(...)100%22100%
RegisterItem(...)50%191055.55%
DeleteItem(...)100%210%
DeleteItem(...)0%620%
DeleteItemsUnsafeFast(...)0%110100%
DeleteItem(...)0%1190340%
DeleteItemPath(...)0%272160%
IsInternalItem(...)0%342180%
GetMetadataPaths(...)0%620%
GetInternalMetadataPaths(...)0%7280%
ResolveItem(...)100%44100%
Resolve(...)100%1140%
GetNewItemId(...)100%11100%
GetNewItemIdInternal(...)100%66100%
ResolvePath(...)100%22100%
ResolvePath(...)70%242078.12%
IgnoreFile(...)100%11100%
NormalizeRootPathList(...)50%2291.66%
ResolvePaths(...)100%11100%
ResolvePaths(...)58.33%221258.33%
CreateRootFolder()71.42%141488.88%
GetUserRootFolder()80%111079.16%
FindByPath(...)100%210%
GetPerson(...)50%2280%
GetStudio(...)100%210%
GetStudioId(...)100%210%
GetGenreId(...)100%210%
GetMusicGenreId(...)100%210%
GetGenre(...)100%210%
GetMusicGenre(...)100%210%
GetYear(...)0%620%
GetArtist(...)100%210%
GetArtists(...)100%210%
GetArtist(...)100%210%
CreateItemByName(...)0%7280%
GetItemByNameId(...)100%11100%
ValidatePeopleAsync(...)100%210%
ValidateMediaLibrary(...)100%11100%
GetVirtualFolders()100%11100%
GetVirtualFolders(...)100%22100%
GetVirtualFolderInfo(...)70%101097.14%
GetCollectionType(...)50%6450%
GetItemById(...)66.66%7675%
GetItemById(...)100%22100%
GetItemById(...)50%22100%
GetItemById(...)50%22100%
GetItemList(...)100%1010100%
GetItemList(...)100%11100%
GetCount(...)0%7280%
GetItemCounts(...)0%7280%
GetItemList(...)0%4260%
GetLatestItemList(...)0%4260%
GetNextUpSeriesKeys(...)0%4260%
QueryItems(...)0%2040%
GetItemIds(...)50%2266.66%
GetStudios(...)0%620%
GetGenres(...)0%620%
GetMusicGenres(...)0%620%
GetAllArtists(...)0%620%
GetArtists(...)0%620%
SetTopParentOrAncestorIds(...)0%210140%
GetAlbumArtists(...)0%620%
GetItemsResult(...)100%1010100%
SetTopParentIdsOrAncestors(...)83.33%6688.88%
AddUserToQuery(...)100%1616100%
GetTopParentIdsForQuery(...)8.33%4342410.71%
ResolveIntro(...)0%110100%
Sort(...)57.14%341453.33%
Sort(...)0%210140%
GetComparer(...)50%3237.5%
CreateItem(...)100%210%
CreateItems(...)91.66%121285.71%
ImageNeedsRefresh(...)0%156120%
UpdateItemAsync(...)100%11100%
ReportItemRemoved(...)0%620%
RetrieveItem(...)100%11100%
GetCollectionFolders(...)100%11100%
GetCollectionFolders(...)80%111081.81%
GetCollectionFoldersInternal(...)100%11100%
GetLibraryOptions(...)75%44100%
GetContentType(...)50%4471.42%
GetInheritedContentType(...)50%2283.33%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)100%210%
GetConfiguredContentType(...)50%2266.66%
GetContentTypeOverride(...)50%4485.71%
GetTopFolderContentType(...)50%11863.63%
GetNamedView(...)100%210%
GetNamedView(...)0%4260%
GetNamedView(...)0%420200%
GetShadowView(...)0%272160%
GetNamedView(...)0%600240%
GetParentItem(...)33.33%8660%
QueueLibraryScan()100%210%
GetSeasonNumberFromPath(...)0%2040%
FillMissingEpisodeNumbersFromPath(...)0%3192560%
ParseName(...)0%620%
GetPathAfterNetworkSubstitution(...)25%6450%
GetPeople(...)100%210%
GetPeople(...)50%11425%
GetPeopleItems(...)100%210%
GetPeopleNames(...)100%210%
UpdatePeople(...)100%210%
StartScanInBackground()100%11100%
AddMediaPath(...)100%1150%
AddMediaPathInternal(...)33.33%17633.33%
UpdateMediaPath(...)100%210%
SyncLibraryOptionsToLocations(...)0%7280%
RemoveContentTypeOverrides(...)0%210140%
RemoveMediaPath(...)25%9433.33%
ItemIsVisible(...)16.66%14640%
CreateShortcut(...)0%620%

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            {
 175191                if (_rootFolder is null)
 21192                {
 193                    lock (_rootFolderSyncLock)
 194                    {
 21195                        _rootFolder ??= CreateRootFolder();
 21196                    }
 197                }
 198
 175199                return _rootFolder;
 200            }
 201        }
 202
 41203        private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
 204
 108205        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        {
 178296            ArgumentNullException.ThrowIfNull(item);
 297
 178298            if (item is IItemByName)
 299            {
 0300                if (item is not MusicArtist)
 301                {
 0302                    return;
 303                }
 304            }
 178305            else if (!item.IsFolder)
 306            {
 0307                if (item is not Video && item is not LiveTvChannel)
 308                {
 0309                    return;
 310                }
 311            }
 312
 178313            _cache.AddOrUpdate(item.Id, item);
 178314        }
 315
 316        public void DeleteItem(BaseItem item, DeleteOptions options)
 317        {
 0318            DeleteItem(item, options, false);
 0319        }
 320
 321        public void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem)
 322        {
 0323            ArgumentNullException.ThrowIfNull(item);
 324
 0325            var parent = item.GetOwner() ?? item.GetParent();
 326
 0327            DeleteItem(item, options, parent, notifyParentItem);
 0328        }
 329
 330        public void DeleteItemsUnsafeFast(IEnumerable<BaseItem> items)
 331        {
 0332            var pathMaps = items.Select(e => (Item: e, InternalPath: GetInternalMetadataPaths(e), DeletePaths: e.GetDele
 333
 0334            foreach (var (item, internalPaths, pathsToDelete) in pathMaps)
 335            {
 0336                foreach (var metadataPath in internalPaths)
 337                {
 0338                    if (!Directory.Exists(metadataPath))
 339                    {
 340                        continue;
 341                    }
 342
 0343                    _logger.LogDebug(
 0344                        "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0345                        item.GetType().Name,
 0346                        item.Name ?? "Unknown name",
 0347                        metadataPath,
 0348                        item.Id);
 349
 350                    try
 351                    {
 0352                        Directory.Delete(metadataPath, true);
 0353                    }
 0354                    catch (Exception ex)
 355                    {
 0356                        _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0357                    }
 358                }
 359
 0360                foreach (var fileSystemInfo in pathsToDelete)
 361                {
 0362                    DeleteItemPath(item, false, fileSystemInfo);
 363                }
 364            }
 365
 0366            _itemRepository.DeleteItem([.. pathMaps.Select(f => f.Item.Id)]);
 0367        }
 368
 369        public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem)
 370        {
 0371            ArgumentNullException.ThrowIfNull(item);
 372
 0373            if (item.SourceType == SourceType.Channel)
 374            {
 0375                if (options.DeleteFromExternalProvider)
 376                {
 377                    try
 378                    {
 0379                        BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult();
 0380                    }
 0381                    catch (ArgumentException)
 382                    {
 383                        // channel no longer installed
 0384                    }
 385                }
 386
 0387                options.DeleteFileLocation = false;
 388            }
 389
 0390            if (item is LiveTvProgram)
 391            {
 0392                _logger.LogDebug(
 0393                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0394                    item.GetType().Name,
 0395                    item.Name ?? "Unknown name",
 0396                    item.Path ?? string.Empty,
 0397                    item.Id);
 398            }
 399            else
 400            {
 0401                _logger.LogInformation(
 0402                    "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0403                    item.GetType().Name,
 0404                    item.Name ?? "Unknown name",
 0405                    item.Path ?? string.Empty,
 0406                    item.Id);
 407            }
 408
 0409            var children = item.IsFolder
 0410                ? ((Folder)item).GetRecursiveChildren(false)
 0411                : [];
 412
 0413            foreach (var metadataPath in GetMetadataPaths(item, children))
 414            {
 0415                if (!Directory.Exists(metadataPath))
 416                {
 417                    continue;
 418                }
 419
 0420                _logger.LogDebug(
 0421                    "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0422                    item.GetType().Name,
 0423                    item.Name ?? "Unknown name",
 0424                    metadataPath,
 0425                    item.Id);
 426
 427                try
 428                {
 0429                    Directory.Delete(metadataPath, true);
 0430                }
 0431                catch (Exception ex)
 432                {
 0433                    _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
 0434                }
 435            }
 436
 0437            if ((options.DeleteFileLocation && item.IsFileProtocol) || IsInternalItem(item))
 438            {
 439                // Assume only the first is required
 440                // Add this flag to GetDeletePaths if required in the future
 0441                var isRequiredForDelete = true;
 442
 0443                foreach (var fileSystemInfo in item.GetDeletePaths())
 444                {
 0445                    DeleteItemPath(item, isRequiredForDelete, fileSystemInfo);
 446
 0447                    isRequiredForDelete = false;
 448                }
 449            }
 450
 0451            item.SetParent(null);
 452
 0453            _itemRepository.DeleteItem([item.Id, .. children.Select(f => f.Id)]);
 0454            _cache.TryRemove(item.Id, out _);
 0455            foreach (var child in children)
 456            {
 0457                _cache.TryRemove(child.Id, out _);
 458            }
 459
 0460            if (parent is Folder folder)
 461            {
 0462                folder.Children = null;
 0463                folder.UserData = null;
 464            }
 465
 0466            ReportItemRemoved(item, parent);
 0467        }
 468
 469        private void DeleteItemPath(BaseItem item, bool isRequiredForDelete, FileSystemMetadata fileSystemInfo)
 470        {
 0471            if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
 472            {
 473                try
 474                {
 0475                    _logger.LogInformation(
 0476                        "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
 0477                        item.GetType().Name,
 0478                        item.Name ?? "Unknown name",
 0479                        fileSystemInfo.FullName,
 0480                        item.Id);
 481
 0482                    if (fileSystemInfo.IsDirectory)
 483                    {
 0484                        Directory.Delete(fileSystemInfo.FullName, true);
 485                    }
 486                    else
 487                    {
 0488                        File.Delete(fileSystemInfo.FullName);
 489                    }
 0490                }
 0491                catch (DirectoryNotFoundException)
 492                {
 0493                    _logger.LogInformation(
 0494                        "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id:
 0495                        item.GetType().Name,
 0496                        item.Name ?? "Unknown name",
 0497                        fileSystemInfo.FullName,
 0498                        item.Id);
 0499                }
 0500                catch (FileNotFoundException)
 501                {
 0502                    _logger.LogInformation(
 0503                        "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}
 0504                        item.GetType().Name,
 0505                        item.Name ?? "Unknown name",
 0506                        fileSystemInfo.FullName,
 0507                        item.Id);
 0508                }
 0509                catch (IOException)
 510                {
 0511                    if (isRequiredForDelete)
 512                    {
 0513                        throw;
 514                    }
 0515                }
 0516                catch (UnauthorizedAccessException)
 517                {
 0518                    if (isRequiredForDelete)
 519                    {
 0520                        throw;
 521                    }
 0522                }
 523            }
 0524        }
 525
 526        private bool IsInternalItem(BaseItem item)
 527        {
 0528            if (!item.IsFileProtocol)
 529            {
 0530                return false;
 531            }
 532
 0533            var pathToCheck = item switch
 0534            {
 0535                Genre => _configurationManager.ApplicationPaths.GenrePath,
 0536                MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath,
 0537                MusicGenre => _configurationManager.ApplicationPaths.MusicGenrePath,
 0538                Person => _configurationManager.ApplicationPaths.PeoplePath,
 0539                Studio => _configurationManager.ApplicationPaths.StudioPath,
 0540                Year => _configurationManager.ApplicationPaths.YearPath,
 0541                _ => null
 0542            };
 543
 0544            var itemPath = item.Path;
 0545            if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath))
 546            {
 0547                var cleanPath = _fileSystem.GetValidFilename(itemPath);
 0548                var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck);
 549
 0550                return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal);
 551            }
 552
 0553            return false;
 554        }
 555
 556        private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
 557        {
 0558            var list = GetInternalMetadataPaths(item);
 0559            foreach (var child in children)
 560            {
 0561                list.AddRange(GetInternalMetadataPaths(child));
 562            }
 563
 0564            return list;
 565        }
 566
 567        private List<string> GetInternalMetadataPaths(BaseItem item)
 568        {
 0569            var list = new List<string>
 0570            {
 0571                item.GetInternalMetadataPath()
 0572            };
 573
 0574            if (item is Video video)
 575            {
 576                // Trickplay
 0577                list.Add(_pathManager.GetTrickplayDirectory(video));
 578
 579                // Subtitles and attachments
 0580                foreach (var mediaSource in item.GetMediaSources(false))
 581                {
 0582                    var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id);
 0583                    if (subtitleFolder is not null)
 584                    {
 0585                        list.Add(subtitleFolder);
 586                    }
 587
 0588                    var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id);
 0589                    if (attachmentFolder is not null)
 590                    {
 0591                        list.Add(attachmentFolder);
 592                    }
 593                }
 594            }
 595
 0596            return list;
 597        }
 598
 599        /// <summary>
 600        /// Resolves the item.
 601        /// </summary>
 602        /// <param name="args">The args.</param>
 603        /// <param name="resolvers">The resolvers.</param>
 604        /// <returns>BaseItem.</returns>
 605        private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers)
 606        {
 77607            var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r))
 77608                .FirstOrDefault(i => i is not null);
 609
 77610            if (item is not null)
 611            {
 67612                ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
 613            }
 614
 77615            return item;
 616        }
 617
 618        private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver)
 619        {
 620            try
 621            {
 307622                return resolver.ResolvePath(args);
 623            }
 0624            catch (Exception ex)
 625            {
 0626                _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path);
 0627                return null;
 628            }
 307629        }
 630
 631        public Guid GetNewItemId(string key, Type type)
 632        {
 130633            return GetNewItemIdInternal(key, type, false);
 634        }
 635
 636        private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
 637        {
 131638            ArgumentException.ThrowIfNullOrEmpty(key);
 131639            ArgumentNullException.ThrowIfNull(type);
 640
 131641            string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
 131642            if (key.StartsWith(programDataPath, StringComparison.Ordinal))
 643            {
 644                // Try to normalize paths located underneath program-data in an attempt to make them more portable
 114645                key = key.Substring(programDataPath.Length)
 114646                    .TrimStart('/', '\\')
 114647                    .Replace('/', '\\');
 648            }
 649
 131650            if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
 651            {
 1652                key = key.ToLowerInvariant();
 653            }
 654
 131655            key = type.FullName + key;
 656
 131657            return key.GetMD5();
 658        }
 659
 660        public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directorySer
 42661            => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent);
 662
 663        private BaseItem? ResolvePath(
 664            FileSystemMetadata fileInfo,
 665            IDirectoryService directoryService,
 666            IItemResolver[]? resolvers,
 667            Folder? parent = null,
 668            CollectionType? collectionType = null,
 669            LibraryOptions? libraryOptions = null)
 670        {
 77671            ArgumentNullException.ThrowIfNull(fileInfo);
 672
 77673            var fullPath = fileInfo.FullName;
 674
 77675            if (collectionType is null && parent is not null)
 676            {
 18677                collectionType = GetContentTypeOverride(fullPath, true);
 678            }
 679
 77680            var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this)
 77681            {
 77682                Parent = parent,
 77683                FileInfo = fileInfo,
 77684                CollectionType = collectionType,
 77685                LibraryOptions = libraryOptions
 77686            };
 687
 688            // Return null if ignore rules deem that we should do so
 77689            if (IgnoreFile(args.FileInfo, args.Parent))
 690            {
 0691                return null;
 692            }
 693
 694            // Gather child folder and files
 77695            if (args.IsDirectory)
 696            {
 50697                var isPhysicalRoot = args.IsPhysicalRoot;
 698
 699                // When resolving the root, we need it's grandchildren (children of user views)
 50700                var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
 701
 702                FileSystemMetadata[] files;
 50703                var isVf = args.IsVf;
 704
 705                try
 706                {
 50707                    files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l
 50708                }
 0709                catch (Exception ex)
 710                {
 0711                    if (parent is not null && parent.IsPhysicalRoot)
 712                    {
 0713                        _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPh
 714
 0715                        files = [];
 716                    }
 717                    else
 718                    {
 0719                        throw;
 720                    }
 0721                }
 722
 723                // Need to remove sub-paths that may have been resolved from shortcuts
 724                // Example: if \\server\movies exists, then strip out \\server\movies\action
 50725                if (isPhysicalRoot)
 726                {
 21727                    files = NormalizeRootPathList(files).ToArray();
 728                }
 729
 50730                args.FileSystemChildren = files;
 731            }
 732
 733            // Filter content based on ignore rules
 77734            if (args.IsDirectory)
 735            {
 50736                var filtered = args.GetActualFileSystemChildren().ToArray();
 50737                args.FileSystemChildren = filtered ?? [];
 738            }
 739
 77740            return ResolveItem(args, resolvers);
 741        }
 742
 743        public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
 103744            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 745
 746        public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
 747        {
 76748            var originalList = paths.ToList();
 749
 76750            var list = originalList.Where(i => i.IsDirectory)
 76751                .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
 76752                .Distinct()
 76753                .ToList();
 754
 76755            var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS
 76756                .ToList();
 757
 152758            foreach (var dupe in dupes)
 759            {
 0760                _logger.LogInformation("Found duplicate path: {0}", dupe);
 761            }
 762
 76763            var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList();
 76764            newList.AddRange(originalList.Where(i => !i.IsDirectory));
 76765            return newList;
 766        }
 767
 768        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ
 769        {
 52770            return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
 771        }
 772
 773        public IEnumerable<BaseItem> ResolvePaths(
 774            IEnumerable<FileSystemMetadata> files,
 775            IDirectoryService directoryService,
 776            Folder parent,
 777            LibraryOptions libraryOptions,
 778            CollectionType? collectionType,
 779            IItemResolver[] resolvers)
 780        {
 52781            var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
 782
 52783            if (parent is not null)
 784            {
 52785                var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>()
 786
 312787                foreach (var resolver in multiItemResolvers)
 788                {
 104789                    var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
 790
 104791                    if (result?.Items.Count > 0)
 792                    {
 0793                        var items = result.Items;
 0794                        items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryServic
 0795                        items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, reso
 0796                        return items;
 797                    }
 798                }
 799            }
 800
 52801            return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
 0802        }
 803
 804        private IEnumerable<BaseItem> ResolveFileList(
 805            IReadOnlyList<FileSystemMetadata> fileList,
 806            IDirectoryService directoryService,
 807            Folder? parent,
 808            CollectionType? collectionType,
 809            IItemResolver[]? resolvers,
 810            LibraryOptions libraryOptions)
 811        {
 812            // Given that fileList is a list we can save enumerator allocations by indexing
 813            for (var i = 0; i < fileList.Count; i++)
 814            {
 815                var file = fileList[i];
 816                BaseItem? result = null;
 817                try
 818                {
 819                    result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
 820                }
 821                catch (Exception ex)
 822                {
 823                    _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
 824                }
 825
 826                if (result is not null)
 827                {
 828                    yield return result;
 829                }
 830            }
 831        }
 832
 833        /// <summary>
 834        /// Creates the root media folder.
 835        /// </summary>
 836        /// <returns>AggregateFolder.</returns>
 837        /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</except
 838        public AggregateFolder CreateRootFolder()
 839        {
 21840            var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
 841
 21842            var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
 21843                             (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOp
 21844                             .DeepCopy<Folder, AggregateFolder>();
 845
 846            // In case program data folder was moved
 21847            if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
 848            {
 0849                _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
 0850                rootFolder.Path = rootFolderPath;
 851            }
 852
 853            // Add in the plug-in folders
 21854            var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
 855
 21856            var info = Directory.CreateDirectory(path);
 21857            Folder folder = new PlaylistsFolder
 21858            {
 21859                Path = path,
 21860                DateCreated = info.CreationTimeUtc,
 21861                DateModified = info.LastWriteTimeUtc,
 21862            };
 863
 21864            if (folder.Id.IsEmpty())
 865            {
 21866                folder.Id = GetNewItemId(folder.Path, folder.GetType());
 867            }
 868
 21869            var dbItem = GetItemById(folder.Id) as BasePluginFolder;
 870
 21871            if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
 872            {
 0873                folder = dbItem;
 874            }
 875
 21876            if (!folder.ParentId.Equals(rootFolder.Id))
 877            {
 21878                rootFolder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().G
 21879                folder.ParentId = rootFolder.Id;
 21880                folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetRe
 881            }
 882
 21883            rootFolder.AddVirtualChild(folder);
 884
 21885            RegisterItem(folder);
 886
 21887            return rootFolder;
 888        }
 889
 890        public Folder GetUserRootFolder()
 891        {
 871892            if (_userRootFolder is null)
 21893            {
 894                lock (_userRootFolderSyncLock)
 895                {
 21896                    if (_userRootFolder is null)
 897                    {
 21898                        var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 899
 21900                        _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
 21901                        Directory.CreateDirectory(userRootPath);
 902
 21903                        var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
 21904                        UserRootFolder? tmpItem = null;
 905                        try
 906                        {
 21907                            tmpItem = GetItemById(newItemId) as UserRootFolder;
 21908                        }
 0909                        catch (Exception ex)
 910                        {
 0911                            _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
 0912                        }
 913
 21914                        if (tmpItem is null)
 915                        {
 21916                            _logger.LogDebug("Creating new userRootFolder with DeepCopy");
 21917                            tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new In
 21918                                        .DeepCopy<Folder, UserRootFolder>();
 919                        }
 920
 921                        // In case program data folder was moved
 21922                        if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
 923                        {
 0924                            _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
 0925                            tmpItem.Path = userRootPath;
 926                        }
 927
 21928                        _userRootFolder = tmpItem;
 21929                        _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
 930                    }
 21931                }
 932            }
 933
 871934            return _userRootFolder;
 935        }
 936
 937        /// <inheritdoc />
 938        public BaseItem? FindByPath(string path, bool? isFolder)
 939        {
 940            // If this returns multiple items it could be tricky figuring out which one is correct.
 941            // In most cases, the newest one will be and the others obsolete but not yet cleaned up
 0942            ArgumentException.ThrowIfNullOrEmpty(path);
 943
 0944            var query = new InternalItemsQuery
 0945            {
 0946                Path = path,
 0947                IsFolder = isFolder,
 0948                OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)],
 0949                Limit = 1,
 0950                DtoOptions = new DtoOptions(true)
 0951            };
 952
 0953            return GetItemList(query)
 0954                .FirstOrDefault();
 955        }
 956
 957        /// <inheritdoc />
 958        public Person? GetPerson(string name)
 959        {
 1960            var path = Person.GetPath(name);
 1961            var id = GetItemByNameId<Person>(path);
 1962            if (GetItemById(id) is Person item)
 963            {
 0964                return item;
 965            }
 966
 1967            return null;
 968        }
 969
 970        /// <summary>
 971        /// Gets the studio.
 972        /// </summary>
 973        /// <param name="name">The name.</param>
 974        /// <returns>Task{Studio}.</returns>
 975        public Studio GetStudio(string name)
 976        {
 0977            return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
 978        }
 979
 980        public Guid GetStudioId(string name)
 981        {
 0982            return GetItemByNameId<Studio>(Studio.GetPath(name));
 983        }
 984
 985        public Guid GetGenreId(string name)
 986        {
 0987            return GetItemByNameId<Genre>(Genre.GetPath(name));
 988        }
 989
 990        public Guid GetMusicGenreId(string name)
 991        {
 0992            return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
 993        }
 994
 995        /// <summary>
 996        /// Gets the genre.
 997        /// </summary>
 998        /// <param name="name">The name.</param>
 999        /// <returns>Task{Genre}.</returns>
 1000        public Genre GetGenre(string name)
 1001        {
 01002            return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
 1003        }
 1004
 1005        /// <summary>
 1006        /// Gets the music genre.
 1007        /// </summary>
 1008        /// <param name="name">The name.</param>
 1009        /// <returns>Task{MusicGenre}.</returns>
 1010        public MusicGenre GetMusicGenre(string name)
 1011        {
 01012            return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
 1013        }
 1014
 1015        /// <summary>
 1016        /// Gets the year.
 1017        /// </summary>
 1018        /// <param name="value">The value.</param>
 1019        /// <returns>Task{Year}.</returns>
 1020        public Year GetYear(int value)
 1021        {
 01022            if (value <= 0)
 1023            {
 01024                throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
 1025            }
 1026
 01027            var name = value.ToString(CultureInfo.InvariantCulture);
 1028
 01029            return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
 1030        }
 1031
 1032        /// <summary>
 1033        /// Gets a Genre.
 1034        /// </summary>
 1035        /// <param name="name">The name.</param>
 1036        /// <returns>Task{Genre}.</returns>
 1037        public MusicArtist GetArtist(string name)
 1038        {
 01039            return GetArtist(name, new DtoOptions(true));
 1040        }
 1041
 1042        public IReadOnlyDictionary<string, MusicArtist[]> GetArtists(IReadOnlyList<string> names)
 1043        {
 01044            return _itemRepository.FindArtists(names);
 1045        }
 1046
 1047        public MusicArtist GetArtist(string name, DtoOptions options)
 1048        {
 01049            return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
 1050        }
 1051
 1052        private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
 1053            where T : BaseItem, new()
 1054        {
 01055            if (typeof(T) == typeof(MusicArtist))
 1056            {
 01057                var existing = GetItemList(new InternalItemsQuery
 01058                {
 01059                    IncludeItemTypes = [BaseItemKind.MusicArtist],
 01060                    Name = name,
 01061                    UseRawName = true,
 01062                    DtoOptions = options
 01063                }).Cast<MusicArtist>()
 01064                .OrderBy(i => i.IsAccessedByName ? 1 : 0)
 01065                .Cast<T>()
 01066                .FirstOrDefault();
 1067
 01068                if (existing is not null)
 1069                {
 01070                    return existing;
 1071                }
 1072            }
 1073
 01074            var path = getPathFn(name);
 01075            var id = GetItemByNameId<T>(path);
 01076            var item = GetItemById(id) as T;
 01077            if (item is null)
 1078            {
 01079                var info = Directory.CreateDirectory(path);
 01080                item = new T
 01081                {
 01082                    Name = name,
 01083                    Id = id,
 01084                    DateCreated = info.CreationTimeUtc,
 01085                    DateModified = info.LastWriteTimeUtc,
 01086                    Path = path
 01087                };
 1088
 01089                CreateItem(item, null);
 1090            }
 1091
 01092            return item;
 1093        }
 1094
 1095        private Guid GetItemByNameId<T>(string path)
 1096              where T : BaseItem, new()
 1097        {
 11098            var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
 11099            return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
 1100        }
 1101
 1102        /// <inheritdoc />
 1103        public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
 1104        {
 1105            // Ensure the location is available.
 01106            Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
 1107
 01108            return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
 1109        }
 1110
 1111        /// <summary>
 1112        /// Reloads the root media folder.
 1113        /// </summary>
 1114        /// <param name="progress">The progress.</param>
 1115        /// <param name="cancellationToken">The cancellation token.</param>
 1116        /// <returns>Task.</returns>
 1117        public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
 1118        {
 1119            // Just run the scheduled task so that the user can see it
 31120            _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
 1121
 31122            return Task.CompletedTask;
 1123        }
 1124
 1125        /// <summary>
 1126        /// Validates the media library internal.
 1127        /// </summary>
 1128        /// <param name="progress">The progress.</param>
 1129        /// <param name="cancellationToken">The cancellation token.</param>
 1130        /// <returns>Task.</returns>
 1131        public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
 1132        {
 1133            IsScanRunning = true;
 1134            LibraryMonitor.Stop();
 1135
 1136            try
 1137            {
 1138                await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
 1139            }
 1140            finally
 1141            {
 1142                LibraryMonitor.Start();
 1143                IsScanRunning = false;
 1144            }
 1145        }
 1146
 1147        public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
 1148        {
 1149            RootFolder.Children = null;
 1150            await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1151
 1152            // Start by just validating the children of the root, but go no further
 1153            await RootFolder.ValidateChildren(
 1154                new Progress<double>(),
 1155                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1156                recursive: false,
 1157                allowRemoveRoot: removeRoot,
 1158                cancellationToken: cancellationToken).ConfigureAwait(false);
 1159
 1160            var rootFolder = GetUserRootFolder();
 1161            rootFolder.Children = null;
 1162
 1163            await rootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1164
 1165            await rootFolder.ValidateChildren(
 1166                new Progress<double>(),
 1167                new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
 1168                recursive: false,
 1169                allowRemoveRoot: removeRoot,
 1170                cancellationToken: cancellationToken).ConfigureAwait(false);
 1171
 1172            // Quickly scan CollectionFolders for changes
 1173            var toDelete = new List<Guid>();
 1174            foreach (var child in rootFolder.Children!.OfType<Folder>())
 1175            {
 1176                // If the user has somehow deleted the collection directory, remove the metadata from the database.
 1177                if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
 1178                {
 1179                    toDelete.Add(collectionFolder.Id);
 1180                }
 1181                else
 1182                {
 1183                    await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 1184                }
 1185            }
 1186
 1187            if (toDelete.Count > 0)
 1188            {
 1189                _itemRepository.DeleteItem(toDelete.ToArray());
 1190            }
 1191        }
 1192
 1193        private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
 1194        {
 1195            _logger.LogInformation("Validating media library");
 1196
 1197            await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
 1198
 1199            var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
 1200
 1201            // Validate the entire media library
 1202            await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem
 1203
 1204            progress.Report(96);
 1205
 1206            innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
 1207
 1208            await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
 1209
 1210            progress.Report(100);
 1211        }
 1212
 1213        /// <summary>
 1214        /// Runs the post scan tasks.
 1215        /// </summary>
 1216        /// <param name="progress">The progress.</param>
 1217        /// <param name="cancellationToken">The cancellation token.</param>
 1218        /// <returns>Task.</returns>
 1219        private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
 1220        {
 1221            var tasks = PostScanTasks.ToList();
 1222
 1223            var numComplete = 0;
 1224            var numTasks = tasks.Count;
 1225
 1226            foreach (var task in tasks)
 1227            {
 1228                // Prevent access to modified closure
 1229                var currentNumComplete = numComplete;
 1230
 1231                var innerProgress = new Progress<double>(pct =>
 1232                {
 1233                    double innerPercent = pct;
 1234                    innerPercent /= 100;
 1235                    innerPercent += currentNumComplete;
 1236
 1237                    innerPercent /= numTasks;
 1238                    innerPercent *= 100;
 1239
 1240                    progress.Report(innerPercent);
 1241                });
 1242
 1243                _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
 1244
 1245                try
 1246                {
 1247                    await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
 1248                }
 1249                catch (OperationCanceledException)
 1250                {
 1251                    _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
 1252                    throw;
 1253                }
 1254                catch (Exception ex)
 1255                {
 1256                    _logger.LogError(ex, "Error running post-scan task");
 1257                }
 1258
 1259                numComplete++;
 1260                double percent = numComplete;
 1261                percent /= numTasks;
 1262                progress.Report(percent * 100);
 1263            }
 1264
 1265            _itemRepository.UpdateInheritedValues();
 1266
 1267            progress.Report(100);
 1268        }
 1269
 1270        /// <summary>
 1271        /// Gets the default view.
 1272        /// </summary>
 1273        /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
 1274        public List<VirtualFolderInfo> GetVirtualFolders()
 1275        {
 231276            return GetVirtualFolders(false);
 1277        }
 1278
 1279        public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
 1280        {
 241281            _logger.LogDebug("Getting topLibraryFolders");
 241282            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 1283
 241284            _logger.LogDebug("Getting refreshQueue");
 241285            var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
 1286
 241287            return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
 241288                .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
 241289                .ToList();
 1290        }
 1291
 1292        private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? r
 1293        {
 11294            var info = new VirtualFolderInfo
 11295            {
 11296                Name = Path.GetFileName(dir),
 11297
 11298                Locations = _fileSystem.GetFilePaths(dir, false)
 11299                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 11300                    .Select(i =>
 11301                    {
 11302                        try
 11303                        {
 11304                            return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
 11305                        }
 11306                        catch (Exception ex)
 11307                        {
 11308                            _logger.LogError(ex, "Error resolving shortcut file {File}", i);
 11309                            return null;
 11310                        }
 11311                    })
 11312                    .Where(i => i is not null)
 11313                    .Order()
 11314                    .ToArray(),
 11315
 11316                CollectionType = GetCollectionType(dir)
 11317            };
 1318
 11319            var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.Ord
 11320            if (libraryFolder is not null)
 1321            {
 11322                var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
 11323                info.ItemId = libraryFolderId;
 11324                if (libraryFolder.HasImage(ImageType.Primary))
 1325                {
 01326                    info.PrimaryImageItemId = libraryFolderId;
 1327                }
 1328
 11329                info.LibraryOptions = GetLibraryOptions(libraryFolder);
 1330
 11331                if (refreshQueue is not null)
 1332                {
 11333                    info.RefreshProgress = libraryFolder.GetRefreshProgress();
 1334
 11335                    info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.
 1336                }
 1337            }
 1338
 11339            return info;
 1340        }
 1341
 1342        private CollectionTypeOptions? GetCollectionType(string path)
 1343        {
 11344            var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
 21345            foreach (ReadOnlySpan<char> file in files)
 1346            {
 01347                if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
 1348                {
 01349                    return res;
 1350                }
 1351            }
 1352
 11353            return null;
 01354        }
 1355
 1356        /// <inheritdoc />
 1357        public BaseItem? GetItemById(Guid id)
 1358        {
 5651359            if (id.IsEmpty())
 1360            {
 01361                throw new ArgumentException("Guid can't be empty", nameof(id));
 1362            }
 1363
 5651364            if (_cache.TryGet(id, out var item))
 1365            {
 4621366                return item;
 1367            }
 1368
 1031369            item = RetrieveItem(id);
 1370
 1031371            if (item is not null)
 1372            {
 01373                RegisterItem(item);
 1374            }
 1375
 1031376            return item;
 1377        }
 1378
 1379        /// <inheritdoc />
 1380        public T? GetItemById<T>(Guid id)
 1381            where T : BaseItem
 1382        {
 231383            var item = GetItemById(id);
 231384            if (item is T typedItem)
 1385            {
 11386                return typedItem;
 1387            }
 1388
 221389            return null;
 1390        }
 1391
 1392        /// <inheritdoc />
 1393        public T? GetItemById<T>(Guid id, Guid userId)
 1394            where T : BaseItem
 1395        {
 11396            var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
 11397            return GetItemById<T>(id, user);
 1398        }
 1399
 1400        /// <inheritdoc />
 1401        public T? GetItemById<T>(Guid id, User? user)
 1402            where T : BaseItem
 1403        {
 211404            var item = GetItemById<T>(id);
 211405            return ItemIsVisible(item, user) ? item : null;
 1406        }
 1407
 1408        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
 1409        {
 1061410            if (query.Recursive && !query.ParentId.IsEmpty())
 1411            {
 431412                var parent = GetItemById(query.ParentId);
 431413                if (parent is not null)
 1414                {
 431415                    SetTopParentIdsOrAncestors(query, [parent]);
 1416                }
 1417            }
 1418
 1061419            if (query.User is not null)
 1420            {
 11421                AddUserToQuery(query, query.User, allowExternalContent);
 1422            }
 1423
 1061424            var itemList = _itemRepository.GetItemList(query);
 1061425            var user = query.User;
 1061426            if (user is not null)
 1427            {
 11428                return itemList.Where(i => i.IsVisible(user)).ToList();
 1429            }
 1430
 1051431            return itemList;
 1432        }
 1433
 1434        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
 1435        {
 1061436            return GetItemList(query, true);
 1437        }
 1438
 1439        public int GetCount(InternalItemsQuery query)
 1440        {
 01441            if (query.Recursive && !query.ParentId.IsEmpty())
 1442            {
 01443                var parent = GetItemById(query.ParentId);
 01444                if (parent is not null)
 1445                {
 01446                    SetTopParentIdsOrAncestors(query, [parent]);
 1447                }
 1448            }
 1449
 01450            if (query.User is not null)
 1451            {
 01452                AddUserToQuery(query, query.User);
 1453            }
 1454
 01455            return _itemRepository.GetCount(query);
 1456        }
 1457
 1458        public ItemCounts GetItemCounts(InternalItemsQuery query)
 1459        {
 01460            if (query.Recursive && !query.ParentId.IsEmpty())
 1461            {
 01462                var parent = GetItemById(query.ParentId);
 01463                if (parent is not null)
 1464                {
 01465                    SetTopParentIdsOrAncestors(query, [parent]);
 1466                }
 1467            }
 1468
 01469            if (query.User is not null)
 1470            {
 01471                AddUserToQuery(query, query.User);
 1472            }
 1473
 01474            return _itemRepository.GetItemCounts(query);
 1475        }
 1476
 1477        public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
 1478        {
 01479            SetTopParentIdsOrAncestors(query, parents);
 1480
 01481            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1482            {
 01483                if (query.User is not null)
 1484                {
 01485                    AddUserToQuery(query, query.User);
 1486                }
 1487            }
 1488
 01489            return _itemRepository.GetItemList(query);
 1490        }
 1491
 1492        public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, Coll
 1493        {
 01494            SetTopParentIdsOrAncestors(query, parents);
 1495
 01496            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1497            {
 01498                if (query.User is not null)
 1499                {
 01500                    AddUserToQuery(query, query.User);
 1501                }
 1502            }
 1503
 01504            return _itemRepository.GetLatestItemList(query, collectionType);
 1505        }
 1506
 1507        public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents
 1508        {
 01509            SetTopParentIdsOrAncestors(query, parents);
 1510
 01511            if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
 1512            {
 01513                if (query.User is not null)
 1514                {
 01515                    AddUserToQuery(query, query.User);
 1516                }
 1517            }
 1518
 01519            return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
 1520        }
 1521
 1522        public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
 1523        {
 01524            if (query.User is not null)
 1525            {
 01526                AddUserToQuery(query, query.User);
 1527            }
 1528
 01529            if (query.EnableTotalRecordCount)
 1530            {
 01531                return _itemRepository.GetItems(query);
 1532            }
 1533
 01534            return new QueryResult<BaseItem>(
 01535                query.StartIndex,
 01536                null,
 01537                _itemRepository.GetItemList(query));
 1538        }
 1539
 1540        public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
 1541        {
 131542            if (query.User is not null)
 1543            {
 01544                AddUserToQuery(query, query.User);
 1545            }
 1546
 131547            return _itemRepository.GetItemIdsList(query);
 1548        }
 1549
 1550        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
 1551        {
 01552            if (query.User is not null)
 1553            {
 01554                AddUserToQuery(query, query.User);
 1555            }
 1556
 01557            SetTopParentOrAncestorIds(query);
 01558            return _itemRepository.GetStudios(query);
 1559        }
 1560
 1561        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
 1562        {
 01563            if (query.User is not null)
 1564            {
 01565                AddUserToQuery(query, query.User);
 1566            }
 1567
 01568            SetTopParentOrAncestorIds(query);
 01569            return _itemRepository.GetGenres(query);
 1570        }
 1571
 1572        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
 1573        {
 01574            if (query.User is not null)
 1575            {
 01576                AddUserToQuery(query, query.User);
 1577            }
 1578
 01579            SetTopParentOrAncestorIds(query);
 01580            return _itemRepository.GetMusicGenres(query);
 1581        }
 1582
 1583        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
 1584        {
 01585            if (query.User is not null)
 1586            {
 01587                AddUserToQuery(query, query.User);
 1588            }
 1589
 01590            SetTopParentOrAncestorIds(query);
 01591            return _itemRepository.GetAllArtists(query);
 1592        }
 1593
 1594        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
 1595        {
 01596            if (query.User is not null)
 1597            {
 01598                AddUserToQuery(query, query.User);
 1599            }
 1600
 01601            SetTopParentOrAncestorIds(query);
 01602            return _itemRepository.GetArtists(query);
 1603        }
 1604
 1605        private void SetTopParentOrAncestorIds(InternalItemsQuery query)
 1606        {
 01607            var ancestorIds = query.AncestorIds;
 01608            int len = ancestorIds.Length;
 01609            if (len == 0)
 1610            {
 01611                return;
 1612            }
 1613
 01614            var parents = new BaseItem[len];
 01615            for (int i = 0; i < len; i++)
 1616            {
 01617                parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id:
 01618                if (parents[i] is not (ICollectionFolder or UserView))
 1619                {
 01620                    return;
 1621                }
 1622            }
 1623
 1624            // Optimize by querying against top level views
 01625            query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 01626            query.AncestorIds = [];
 1627
 1628            // Prevent searching in all libraries due to empty filter
 01629            if (query.TopParentIds.Length == 0)
 1630            {
 01631                query.TopParentIds = [Guid.NewGuid()];
 1632            }
 01633        }
 1634
 1635        public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
 1636        {
 01637            if (query.User is not null)
 1638            {
 01639                AddUserToQuery(query, query.User);
 1640            }
 1641
 01642            SetTopParentOrAncestorIds(query);
 01643            return _itemRepository.GetAlbumArtists(query);
 1644        }
 1645
 1646        public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
 1647        {
 141648            if (query.Recursive && !query.ParentId.IsEmpty())
 1649            {
 131650                var parent = GetItemById(query.ParentId);
 131651                if (parent is not null)
 1652                {
 131653                    SetTopParentIdsOrAncestors(query, [parent]);
 1654                }
 1655            }
 1656
 141657            if (query.User is not null)
 1658            {
 11659                AddUserToQuery(query, query.User);
 1660            }
 1661
 141662            if (query.EnableTotalRecordCount)
 1663            {
 11664                return _itemRepository.GetItems(query);
 1665            }
 1666
 131667            return new QueryResult<BaseItem>(
 131668                query.StartIndex,
 131669                null,
 131670                _itemRepository.GetItemList(query));
 1671        }
 1672
 1673        private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
 1674        {
 561675            if (parents.All(i => i is ICollectionFolder || i is UserView))
 1676            {
 1677                // Optimize by querying against top level views
 131678                query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
 1679
 1680                // Prevent searching in all libraries due to empty filter
 131681                if (query.TopParentIds.Length == 0)
 1682                {
 131683                    query.TopParentIds = [Guid.NewGuid()];
 1684                }
 1685            }
 1686            else
 1687            {
 1688                // We need to be able to query from any arbitrary ancestor up the tree
 431689                query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
 1690
 1691                // Prevent searching in all libraries due to empty filter
 431692                if (query.AncestorIds.Length == 0)
 1693                {
 01694                    query.AncestorIds = [Guid.NewGuid()];
 1695                }
 1696            }
 1697
 561698            query.Parent = null;
 561699        }
 1700
 1701        private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
 1702        {
 21703            if (query.AncestorIds.Length == 0 &&
 21704                query.ParentId.IsEmpty() &&
 21705                query.ChannelIds.Count == 0 &&
 21706                query.TopParentIds.Length == 0 &&
 21707                string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
 21708                string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
 21709                query.ItemIds.Length == 0)
 1710            {
 11711                var userViews = UserViewManager.GetUserViews(new UserViewQuery
 11712                {
 11713                    User = user,
 11714                    IncludeHidden = true,
 11715                    IncludeExternalContent = allowExternalContent
 11716                });
 1717
 11718                query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
 1719
 1720                // Prevent searching in all libraries due to empty filter
 11721                if (query.TopParentIds.Length == 0)
 1722                {
 11723                    query.TopParentIds = [Guid.NewGuid()];
 1724                }
 1725            }
 21726        }
 1727
 1728        private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
 1729        {
 131730            if (item is UserView view)
 1731            {
 01732                if (view.ViewType == CollectionType.livetv)
 1733                {
 01734                    return [view.Id];
 1735                }
 1736
 1737                // Translate view into folders
 01738                if (!view.DisplayParentId.IsEmpty())
 1739                {
 01740                    var displayParent = GetItemById(view.DisplayParentId);
 01741                    if (displayParent is not null)
 1742                    {
 01743                        return GetTopParentIdsForQuery(displayParent, user);
 1744                    }
 1745
 01746                    return [];
 1747                }
 1748
 01749                if (!view.ParentId.IsEmpty())
 1750                {
 01751                    var displayParent = GetItemById(view.ParentId);
 01752                    if (displayParent is not null)
 1753                    {
 01754                        return GetTopParentIdsForQuery(displayParent, user);
 1755                    }
 1756
 01757                    return [];
 1758                }
 1759
 1760                // Handle grouping
 01761                if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.V
 01762                    && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
 1763                {
 01764                    return GetUserRootFolder()
 01765                        .GetChildren(user, true)
 01766                        .OfType<CollectionFolder>()
 01767                        .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
 01768                        .Where(i => user.IsFolderGrouped(i.Id))
 01769                        .SelectMany(i => GetTopParentIdsForQuery(i, user));
 1770                }
 1771
 01772                return [];
 1773            }
 1774
 131775            if (item is CollectionFolder collectionFolder)
 1776            {
 131777                return collectionFolder.PhysicalFolderIds;
 1778            }
 1779
 01780            var topParent = item.GetTopParent();
 01781            if (topParent is not null)
 1782            {
 01783                return [topParent.Id];
 1784            }
 1785
 01786            return [];
 1787        }
 1788
 1789        /// <summary>
 1790        /// Gets the intros.
 1791        /// </summary>
 1792        /// <param name="item">The item.</param>
 1793        /// <param name="user">The user.</param>
 1794        /// <returns>IEnumerable{System.String}.</returns>
 1795        public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
 1796        {
 1797            if (IntroProviders.Length == 0)
 1798            {
 1799                return [];
 1800            }
 1801
 1802            var tasks = IntroProviders
 1803                .Select(i => GetIntros(i, item, user));
 1804
 1805            var items = await Task.WhenAll(tasks).ConfigureAwait(false);
 1806
 1807            return items
 1808                .SelectMany(i => i)
 1809                .Select(ResolveIntro)
 1810                .Where(i => i is not null)!; // null values got filtered out
 1811        }
 1812
 1813        /// <summary>
 1814        /// Gets the intros.
 1815        /// </summary>
 1816        /// <param name="provider">The provider.</param>
 1817        /// <param name="item">The item.</param>
 1818        /// <param name="user">The user.</param>
 1819        /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
 1820        private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
 1821        {
 1822            try
 1823            {
 1824                return await provider.GetIntros(item, user).ConfigureAwait(false);
 1825            }
 1826            catch (Exception ex)
 1827            {
 1828                _logger.LogError(ex, "Error getting intros");
 1829
 1830                return [];
 1831            }
 1832        }
 1833
 1834        /// <summary>
 1835        /// Resolves the intro.
 1836        /// </summary>
 1837        /// <param name="info">The info.</param>
 1838        /// <returns>Video.</returns>
 1839        private Video? ResolveIntro(IntroInfo info)
 1840        {
 01841            Video? video = null;
 1842
 01843            if (info.ItemId.HasValue)
 1844            {
 1845                // Get an existing item by Id
 01846                video = GetItemById(info.ItemId.Value) as Video;
 1847
 01848                if (video is null)
 1849                {
 01850                    _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
 1851                }
 1852            }
 01853            else if (!string.IsNullOrEmpty(info.Path))
 1854            {
 1855                try
 1856                {
 1857                    // Try to resolve the path into a video
 01858                    video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
 1859
 01860                    if (video is null)
 1861                    {
 01862                        _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
 1863                    }
 1864                    else
 1865                    {
 1866                        // Pull the saved db item that will include metadata
 01867                        var dbItem = GetItemById(video.Id) as Video;
 1868
 01869                        if (dbItem is not null)
 1870                        {
 01871                            video = dbItem;
 1872                        }
 1873                        else
 1874                        {
 01875                            return null;
 1876                        }
 1877                    }
 01878                }
 01879                catch (Exception ex)
 1880                {
 01881                    _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
 01882                }
 1883            }
 1884            else
 1885            {
 01886                _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
 1887            }
 1888
 01889            return video;
 01890        }
 1891
 1892        /// <inheritdoc />
 1893        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortO
 1894        {
 11895            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1896
 41897            foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
 1898            {
 11899                if (orderBy is RandomComparer)
 1900                {
 01901                    var randomItems = items.ToArray();
 01902                    Random.Shared.Shuffle(randomItems);
 01903                    items = randomItems;
 1904                    // Items are no longer ordered at this point, so set orderedItems back to null
 01905                    orderedItems = null;
 1906                }
 11907                else if (orderedItems is null)
 1908                {
 11909                    orderedItems = sortOrder == SortOrder.Descending
 11910                        ? items.OrderByDescending(i => i, orderBy)
 11911                        : items.OrderBy(i => i, orderBy);
 1912                }
 1913                else
 1914                {
 01915                    orderedItems = sortOrder == SortOrder.Descending
 01916                        ? orderedItems!.ThenByDescending(i => i, orderBy)
 01917                        : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
 1918                }
 1919            }
 1920
 11921            return orderedItems ?? items;
 1922        }
 1923
 1924        /// <inheritdoc />
 1925        public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, Sort
 1926        {
 01927            IOrderedEnumerable<BaseItem>? orderedItems = null;
 1928
 01929            foreach (var (name, sortOrder) in orderBy)
 1930            {
 01931                var comparer = GetComparer(name, user);
 01932                if (comparer is null)
 1933                {
 1934                    continue;
 1935                }
 1936
 01937                if (comparer is RandomComparer)
 1938                {
 01939                    var randomItems = items.ToArray();
 01940                    Random.Shared.Shuffle(randomItems);
 01941                    items = randomItems;
 1942                    // Items are no longer ordered at this point, so set orderedItems back to null
 01943                    orderedItems = null;
 1944                }
 01945                else if (orderedItems is null)
 1946                {
 01947                    orderedItems = sortOrder == SortOrder.Descending
 01948                        ? items.OrderByDescending(i => i, comparer)
 01949                        : items.OrderBy(i => i, comparer);
 1950                }
 1951                else
 1952                {
 01953                    orderedItems = sortOrder == SortOrder.Descending
 01954                        ? orderedItems!.ThenByDescending(i => i, comparer)
 01955                        : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
 1956                }
 1957            }
 1958
 01959            return orderedItems ?? items;
 1960        }
 1961
 1962        /// <summary>
 1963        /// Gets the comparer.
 1964        /// </summary>
 1965        /// <param name="name">The name.</param>
 1966        /// <param name="user">The user.</param>
 1967        /// <returns>IBaseItemComparer.</returns>
 1968        private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
 1969        {
 11970            var comparer = Comparers.FirstOrDefault(c => name == c.Type);
 1971
 1972            // If it requires a user, create a new one, and assign the user
 11973            if (comparer is IUserBaseItemComparer)
 1974            {
 01975                var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null fo
 1976
 01977                userComparer.User = user;
 01978                userComparer.UserManager = _userManager;
 01979                userComparer.UserDataManager = _userDataManager;
 1980
 01981                return userComparer;
 1982            }
 1983
 11984            return comparer;
 1985        }
 1986
 1987        /// <inheritdoc />
 1988        public void CreateItem(BaseItem item, BaseItem? parent)
 1989        {
 01990            CreateItems([item], parent, CancellationToken.None);
 01991        }
 1992
 1993        /// <inheritdoc />
 1994        public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
 1995        {
 21996            _itemRepository.SaveItems(items, cancellationToken);
 1997
 81998            foreach (var item in items)
 1999            {
 22000                RegisterItem(item);
 2001            }
 2002
 22003            if (parent is Folder folder)
 2004            {
 22005                folder.Children = null;
 22006                folder.UserData = null;
 2007            }
 2008
 22009            if (ItemAdded is not null)
 2010            {
 82011                foreach (var item in items)
 2012                {
 2013                    // With the live tv guide this just creates too much noise
 22014                    if (item.SourceType != SourceType.Library)
 2015                    {
 2016                        continue;
 2017                    }
 2018
 2019                    try
 2020                    {
 22021                        ItemAdded(
 22022                            this,
 22023                            new ItemChangeEventArgs
 22024                            {
 22025                                Item = item,
 22026                                Parent = parent ?? item.GetParent()
 22027                            });
 22028                    }
 02029                    catch (Exception ex)
 2030                    {
 02031                        _logger.LogError(ex, "Error in ItemAdded event handler");
 02032                    }
 2033                }
 2034            }
 22035        }
 2036
 2037        private bool ImageNeedsRefresh(ItemImageInfo image)
 2038        {
 02039            if (image.Path is not null && image.IsLocalFile)
 2040            {
 02041                if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
 2042                {
 02043                    return true;
 2044                }
 2045
 2046                try
 2047                {
 02048                    return image.DateModified.Subtract(_fileSystem.GetLastWriteTimeUtc(image.Path)).Duration().TotalSeco
 2049                }
 02050                catch (Exception ex)
 2051                {
 02052                    _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
 02053                    return false;
 2054                }
 2055            }
 2056
 02057            return image.Path is not null && !image.IsLocalFile;
 02058        }
 2059
 2060        /// <inheritdoc />
 2061        public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
 2062        {
 2063            ArgumentNullException.ThrowIfNull(item);
 2064
 2065            var outdated = forceUpdate
 2066                ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
 2067                : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
 2068            // Skip image processing if current or live tv source
 2069            if (outdated.Length == 0 || item.SourceType != SourceType.Library)
 2070            {
 2071                RegisterItem(item);
 2072                return;
 2073            }
 2074
 2075            foreach (var img in outdated)
 2076            {
 2077                var image = img;
 2078                if (!img.IsLocalFile)
 2079                {
 2080                    try
 2081                    {
 2082                        var index = item.GetImageIndex(img);
 2083                        image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
 2084                    }
 2085                    catch (ArgumentException)
 2086                    {
 2087                        _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
 2088                        continue;
 2089                    }
 2090                    catch (Exception ex) when (ex is InvalidOperationException or IOException)
 2091                    {
 2092                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
 2093                        continue;
 2094                    }
 2095                    catch (HttpRequestException ex)
 2096                    {
 2097                        _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", im
 2098                        continue;
 2099                    }
 2100                }
 2101
 2102                if (!File.Exists(image.Path))
 2103                {
 2104                    _logger.LogWarning("Image not found at {ImagePath}", image.Path);
 2105                    continue;
 2106                }
 2107
 2108                ImageDimensions size;
 2109                try
 2110                {
 2111                    size = _imageProcessor.GetImageDimensions(item, image);
 2112                    image.Width = size.Width;
 2113                    image.Height = size.Height;
 2114                }
 2115                catch (Exception ex)
 2116                {
 2117                    _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
 2118                    size = default;
 2119                    image.Width = 0;
 2120                    image.Height = 0;
 2121                }
 2122
 2123                try
 2124                {
 2125                    var blurhash = _imageProcessor.GetImageBlurHash(image.Path, size);
 2126                    image.BlurHash = blurhash;
 2127                }
 2128                catch (Exception ex)
 2129                {
 2130                    _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
 2131                    image.BlurHash = string.Empty;
 2132                }
 2133
 2134                try
 2135                {
 2136                    var modifiedDate = _fileSystem.GetLastWriteTimeUtc(image.Path);
 2137                    image.DateModified = modifiedDate;
 2138                }
 2139                catch (Exception ex)
 2140                {
 2141                    _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
 2142                }
 2143            }
 2144
 2145            item.ValidateImages();
 2146
 2147            await _itemRepository.SaveImagesAsync(item).ConfigureAwait(false);
 2148
 2149            RegisterItem(item);
 2150        }
 2151
 2152        /// <inheritdoc />
 2153        public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, 
 2154        {
 2155            foreach (var item in items)
 2156            {
 2157                item.DateLastSaved = DateTime.UtcNow;
 2158                await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
 2159
 2160                // Modify again, so saved value is after write time of externally saved metadata
 2161                item.DateLastSaved = DateTime.UtcNow;
 2162            }
 2163
 2164            _itemRepository.SaveItems(items, cancellationToken);
 2165
 2166            if (parent is Folder folder)
 2167            {
 2168                folder.Children = null;
 2169                folder.UserData = null;
 2170            }
 2171
 2172            if (ItemUpdated is not null)
 2173            {
 2174                foreach (var item in items)
 2175                {
 2176                    // With the live tv guide this just creates too much noise
 2177                    if (item.SourceType != SourceType.Library)
 2178                    {
 2179                        continue;
 2180                    }
 2181
 2182                    try
 2183                    {
 2184                        ItemUpdated(
 2185                            this,
 2186                            new ItemChangeEventArgs
 2187                            {
 2188                                Item = item,
 2189                                Parent = parent,
 2190                                UpdateReason = updateReason
 2191                            });
 2192                    }
 2193                    catch (Exception ex)
 2194                    {
 2195                        _logger.LogError(ex, "Error in ItemUpdated event handler");
 2196                    }
 2197                }
 2198            }
 2199        }
 2200
 2201        /// <inheritdoc />
 2202        public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance
 1072203            => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
 2204
 2205        /// <inheritdoc />
 2206        public async Task ReattachUserDataAsync(BaseItem item, CancellationToken cancellationToken)
 2207        {
 2208            await _itemRepository.ReattachUserDataAsync(item, cancellationToken).ConfigureAwait(false);
 2209        }
 2210
 2211        public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
 2212        {
 2213            if (item.IsFileProtocol)
 2214            {
 2215                await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
 2216            }
 2217
 2218            await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
 2219        }
 2220
 2221        /// <summary>
 2222        /// Reports the item removed.
 2223        /// </summary>
 2224        /// <param name="item">The item.</param>
 2225        /// <param name="parent">The parent item.</param>
 2226        public void ReportItemRemoved(BaseItem item, BaseItem parent)
 2227        {
 02228            if (ItemRemoved is not null)
 2229            {
 2230                try
 2231                {
 02232                    ItemRemoved(
 02233                        this,
 02234                        new ItemChangeEventArgs
 02235                        {
 02236                            Item = item,
 02237                            Parent = parent
 02238                        });
 02239                }
 02240                catch (Exception ex)
 2241                {
 02242                    _logger.LogError(ex, "Error in ItemRemoved event handler");
 02243                }
 2244            }
 02245        }
 2246
 2247        /// <summary>
 2248        /// Retrieves the item.
 2249        /// </summary>
 2250        /// <param name="id">The id.</param>
 2251        /// <returns>BaseItem.</returns>
 2252        public BaseItem RetrieveItem(Guid id)
 2253        {
 1032254            return _itemRepository.RetrieveItem(id);
 2255        }
 2256
 2257        public List<Folder> GetCollectionFolders(BaseItem item)
 2258        {
 7592259            return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
 2260        }
 2261
 2262        public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2263        {
 7972264            while (item is not null)
 2265            {
 7972266                var parent = item.GetParent();
 2267
 7972268                if (parent is AggregateFolder)
 2269                {
 2270                    break;
 2271                }
 2272
 7082273                if (parent is null)
 2274                {
 6702275                    var owner = item.GetOwner();
 2276
 6702277                    if (owner is null)
 2278                    {
 2279                        break;
 2280                    }
 2281
 02282                    item = owner;
 2283                }
 2284                else
 2285                {
 382286                    item = parent;
 2287                }
 2288            }
 2289
 7592290            if (item is null)
 2291            {
 02292                return new List<Folder>();
 2293            }
 2294
 7592295            return GetCollectionFoldersInternal(item, allUserRootChildren);
 2296        }
 2297
 2298        private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
 2299        {
 7592300            return allUserRootChildren
 7592301                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 7592302                .ToList();
 2303        }
 2304
 2305        public LibraryOptions GetLibraryOptions(BaseItem item)
 2306        {
 4782307            if (item is CollectionFolder collectionFolder)
 2308            {
 582309                return collectionFolder.GetLibraryOptions();
 2310            }
 2311
 2312            // List.Find is more performant than FirstOrDefault due to enumerator allocation
 4202313            return GetCollectionFolders(item)
 4202314                .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
 4202315                ? collectionFolder2.GetLibraryOptions()
 4202316                : new LibraryOptions();
 2317        }
 2318
 2319        public CollectionType? GetContentType(BaseItem item)
 2320        {
 522321            var configuredContentType = GetConfiguredContentType(item, false);
 522322            if (configuredContentType is not null)
 2323            {
 02324                return configuredContentType;
 2325            }
 2326
 522327            configuredContentType = GetConfiguredContentType(item, true);
 522328            if (configuredContentType is not null)
 2329            {
 02330                return configuredContentType;
 2331            }
 2332
 522333            return GetInheritedContentType(item);
 2334        }
 2335
 2336        public CollectionType? GetInheritedContentType(BaseItem item)
 2337        {
 522338            var type = GetTopFolderContentType(item);
 2339
 522340            if (type is not null)
 2341            {
 02342                return type;
 2343            }
 2344
 522345            return item.GetParents()
 522346                .Select(GetConfiguredContentType)
 522347                .LastOrDefault(i => i is not null);
 2348        }
 2349
 2350        public CollectionType? GetConfiguredContentType(BaseItem item)
 2351        {
 02352            return GetConfiguredContentType(item, false);
 2353        }
 2354
 2355        public CollectionType? GetConfiguredContentType(string path)
 2356        {
 02357            return GetContentTypeOverride(path, false);
 2358        }
 2359
 2360        public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
 2361        {
 1042362            if (item is ICollectionFolder collectionFolder)
 2363            {
 02364                return collectionFolder.CollectionType;
 2365            }
 2366
 1042367            return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
 2368        }
 2369
 2370        private CollectionType? GetContentTypeOverride(string path, bool inherit)
 2371        {
 1222372            var nameValuePair = _configurationManager.Configuration.ContentTypes
 1222373                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
 1222374                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
 1222375                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
 1222376            if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
 2377            {
 02378                return collectionType;
 2379            }
 2380
 1222381            return null;
 2382        }
 2383
 2384        private CollectionType? GetTopFolderContentType(BaseItem item)
 2385        {
 522386            if (item is null)
 2387            {
 02388                return null;
 2389            }
 2390
 522391            while (!item.ParentId.IsEmpty())
 2392            {
 02393                var parent = item.GetParent();
 02394                if (parent is null || parent is AggregateFolder)
 2395                {
 2396                    break;
 2397                }
 2398
 02399                item = parent;
 2400            }
 2401
 522402            return GetUserRootFolder().Children
 522403                .OfType<ICollectionFolder>()
 522404                .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.
 522405                .Select(i => i.CollectionType)
 522406                .FirstOrDefault(i => i is not null);
 2407        }
 2408
 2409        public UserView GetNamedView(
 2410            User user,
 2411            string name,
 2412            CollectionType? viewType,
 2413            string sortName)
 2414        {
 02415            return GetNamedView(user, name, Guid.Empty, viewType, sortName);
 2416        }
 2417
 2418        public UserView GetNamedView(
 2419            string name,
 2420            CollectionType viewType,
 2421            string sortName)
 2422        {
 02423            var path = Path.Combine(
 02424                _configurationManager.ApplicationPaths.InternalMetadataPath,
 02425                "views",
 02426                _fileSystem.GetValidFilename(viewType.ToString()));
 2427
 02428            var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 2429
 02430            var item = GetItemById(id) as UserView;
 2431
 02432            var refresh = false;
 2433
 02434            if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
 2435            {
 02436                var info = Directory.CreateDirectory(path);
 02437                item = new UserView
 02438                {
 02439                    Path = path,
 02440                    Id = id,
 02441                    DateCreated = info.CreationTimeUtc,
 02442                    DateModified = info.LastWriteTimeUtc,
 02443                    Name = name,
 02444                    ViewType = viewType,
 02445                    ForcedSortName = sortName
 02446                };
 2447
 02448                CreateItem(item, null);
 2449
 02450                refresh = true;
 2451            }
 2452
 02453            if (refresh)
 2454            {
 02455                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu
 02456                ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref
 2457            }
 2458
 02459            return item;
 2460        }
 2461
 2462        public UserView GetNamedView(
 2463            User user,
 2464            string name,
 2465            Guid parentId,
 2466            CollectionType? viewType,
 2467            string sortName)
 2468        {
 02469            var parentIdString = parentId.IsEmpty()
 02470                ? null
 02471                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02472            var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin
 2473
 02474            var id = GetNewItemId(idValues, typeof(UserView));
 2475
 02476            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2477
 02478            var item = GetItemById(id) as UserView;
 2479
 02480            var isNew = false;
 2481
 02482            if (item is null)
 2483            {
 02484                var info = Directory.CreateDirectory(path);
 02485                item = new UserView
 02486                {
 02487                    Path = path,
 02488                    Id = id,
 02489                    DateCreated = info.CreationTimeUtc,
 02490                    DateModified = info.LastWriteTimeUtc,
 02491                    Name = name,
 02492                    ViewType = viewType,
 02493                    ForcedSortName = sortName,
 02494                    UserId = user.Id,
 02495                    DisplayParentId = parentId
 02496                };
 2497
 02498                CreateItem(item, null);
 2499
 02500                isNew = true;
 2501            }
 2502
 02503            var lastRefreshedUtc = item.DateLastRefreshed;
 02504            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2505
 02506            if (!refresh && !item.DisplayParentId.IsEmpty())
 2507            {
 02508                var displayParent = GetItemById(item.DisplayParentId);
 02509                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2510            }
 2511
 02512            if (refresh)
 2513            {
 02514                ProviderManager.QueueRefresh(
 02515                    item.Id,
 02516                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02517                    {
 02518                        // Need to force save to increment DateLastSaved
 02519                        ForceSave = true
 02520                    },
 02521                    RefreshPriority.Normal);
 2522            }
 2523
 02524            return item;
 2525        }
 2526
 2527        public UserView GetShadowView(
 2528            BaseItem parent,
 2529            CollectionType? viewType,
 2530            string sortName)
 2531        {
 02532            ArgumentNullException.ThrowIfNull(parent);
 2533
 02534            var name = parent.Name;
 02535            var parentId = parent.Id;
 2536
 02537            var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
 2538
 02539            var id = GetNewItemId(idValues, typeof(UserView));
 2540
 02541            var path = parent.Path;
 2542
 02543            var item = GetItemById(id) as UserView;
 2544
 02545            var isNew = false;
 2546
 02547            if (item is null)
 2548            {
 02549                var info = Directory.CreateDirectory(path);
 02550                item = new UserView
 02551                {
 02552                    Path = path,
 02553                    Id = id,
 02554                    DateCreated = info.CreationTimeUtc,
 02555                    DateModified = info.LastWriteTimeUtc,
 02556                    Name = name,
 02557                    ViewType = viewType,
 02558                    ForcedSortName = sortName,
 02559                    DisplayParentId = parentId
 02560                };
 2561
 02562                CreateItem(item, null);
 2563
 02564                isNew = true;
 2565            }
 2566
 02567            var lastRefreshedUtc = item.DateLastRefreshed;
 02568            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2569
 02570            if (!refresh && !item.DisplayParentId.IsEmpty())
 2571            {
 02572                var displayParent = GetItemById(item.DisplayParentId);
 02573                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2574            }
 2575
 02576            if (refresh)
 2577            {
 02578                ProviderManager.QueueRefresh(
 02579                    item.Id,
 02580                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02581                    {
 02582                        // Need to force save to increment DateLastSaved
 02583                        ForceSave = true
 02584                    },
 02585                    RefreshPriority.Normal);
 2586            }
 2587
 02588            return item;
 2589        }
 2590
 2591        public UserView GetNamedView(
 2592            string name,
 2593            Guid parentId,
 2594            CollectionType? viewType,
 2595            string sortName,
 2596            string uniqueId)
 2597        {
 02598            ArgumentException.ThrowIfNullOrEmpty(name);
 2599
 02600            var parentIdString = parentId.IsEmpty()
 02601                ? null
 02602                : parentId.ToString("N", CultureInfo.InvariantCulture);
 02603            var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E
 02604            if (!string.IsNullOrEmpty(uniqueId))
 2605            {
 02606                idValues += uniqueId;
 2607            }
 2608
 02609            var id = GetNewItemId(idValues, typeof(UserView));
 2610
 02611            var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N
 2612
 02613            var item = GetItemById(id) as UserView;
 2614
 02615            var isNew = false;
 2616
 02617            if (item is null)
 2618            {
 02619                var info = Directory.CreateDirectory(path);
 02620                item = new UserView
 02621                {
 02622                    Path = path,
 02623                    Id = id,
 02624                    DateCreated = info.CreationTimeUtc,
 02625                    DateModified = info.LastWriteTimeUtc,
 02626                    Name = name,
 02627                    ViewType = viewType,
 02628                    ForcedSortName = sortName,
 02629                    DisplayParentId = parentId
 02630                };
 2631
 02632                CreateItem(item, null);
 2633
 02634                isNew = true;
 2635            }
 2636
 02637            if (viewType != item.ViewType)
 2638            {
 02639                item.ViewType = viewType;
 02640                item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult
 2641            }
 2642
 02643            var lastRefreshedUtc = item.DateLastRefreshed;
 02644            var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
 2645
 02646            if (!refresh && !item.DisplayParentId.IsEmpty())
 2647            {
 02648                var displayParent = GetItemById(item.DisplayParentId);
 02649                refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
 2650            }
 2651
 02652            if (refresh)
 2653            {
 02654                ProviderManager.QueueRefresh(
 02655                    item.Id,
 02656                    new MetadataRefreshOptions(new DirectoryService(_fileSystem))
 02657                    {
 02658                        // Need to force save to increment DateLastSaved
 02659                        ForceSave = true
 02660                    },
 02661                    RefreshPriority.Normal);
 2662            }
 2663
 02664            return item;
 2665        }
 2666
 2667        public BaseItem GetParentItem(Guid? parentId, Guid? userId)
 2668        {
 32669            if (parentId.HasValue)
 2670            {
 02671                return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}"
 2672            }
 2673
 32674            if (!userId.IsNullOrEmpty())
 2675            {
 32676                return GetUserRootFolder();
 2677            }
 2678
 02679            return RootFolder;
 2680        }
 2681
 2682        /// <inheritdoc />
 2683        public void QueueLibraryScan()
 2684        {
 02685            _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
 02686        }
 2687
 2688        /// <inheritdoc />
 2689        public int? GetSeasonNumberFromPath(string path, Guid? parentId)
 2690        {
 02691            var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
 02692            return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
 2693        }
 2694
 2695        /// <inheritdoc />
 2696        public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
 2697        {
 02698            var series = episode.Series;
 02699            bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis
 02700            if (!isAbsoluteNaming.Value)
 2701            {
 2702                // In other words, no filter applied
 02703                isAbsoluteNaming = null;
 2704            }
 2705
 02706            var resolver = new EpisodeResolver(_namingOptions);
 2707
 02708            var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
 2709
 02710            EpisodeInfo? episodeInfo = null;
 02711            if (episode.IsFileProtocol)
 2712            {
 02713                episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
 2714                // Resolve from parent folder if it's not the Season folder
 02715                var parent = episode.GetParent();
 02716                if (episodeInfo is null && parent.GetType() == typeof(Folder))
 2717                {
 02718                    episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
 02719                    if (episodeInfo is not null)
 2720                    {
 2721                        // add the container
 02722                        episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
 2723                    }
 2724                }
 2725            }
 2726
 02727            var changed = false;
 02728            if (episodeInfo is null)
 2729            {
 02730                return changed;
 2731            }
 2732
 02733            if (episodeInfo.IsByDate)
 2734            {
 02735                if (episode.IndexNumber.HasValue)
 2736                {
 02737                    episode.IndexNumber = null;
 02738                    changed = true;
 2739                }
 2740
 02741                if (episode.IndexNumberEnd.HasValue)
 2742                {
 02743                    episode.IndexNumberEnd = null;
 02744                    changed = true;
 2745                }
 2746
 02747                if (!episode.PremiereDate.HasValue)
 2748                {
 02749                    if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
 2750                    {
 02751                        episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo
 2752                    }
 2753
 02754                    if (episode.PremiereDate.HasValue)
 2755                    {
 02756                        changed = true;
 2757                    }
 2758                }
 2759
 02760                if (!episode.ProductionYear.HasValue)
 2761                {
 02762                    episode.ProductionYear = episodeInfo.Year;
 2763
 02764                    if (episode.ProductionYear.HasValue)
 2765                    {
 02766                        changed = true;
 2767                    }
 2768                }
 2769            }
 2770            else
 2771            {
 02772                if (!episode.IndexNumber.HasValue || forceRefresh)
 2773                {
 02774                    if (episode.IndexNumber != episodeInfo.EpisodeNumber)
 2775                    {
 02776                        changed = true;
 2777                    }
 2778
 02779                    episode.IndexNumber = episodeInfo.EpisodeNumber;
 2780                }
 2781
 02782                if (!episode.IndexNumberEnd.HasValue || forceRefresh)
 2783                {
 02784                    if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
 2785                    {
 02786                        changed = true;
 2787                    }
 2788
 02789                    episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
 2790                }
 2791
 02792                if (!episode.ParentIndexNumber.HasValue || forceRefresh)
 2793                {
 02794                    if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
 2795                    {
 02796                        changed = true;
 2797                    }
 2798
 02799                    episode.ParentIndexNumber = episodeInfo.SeasonNumber;
 2800                }
 2801            }
 2802
 02803            if (!episode.ParentIndexNumber.HasValue)
 2804            {
 02805                var season = episode.Season;
 2806
 02807                if (season is not null)
 2808                {
 02809                    episode.ParentIndexNumber = season.IndexNumber;
 2810                }
 2811
 02812                if (episode.ParentIndexNumber.HasValue)
 2813                {
 02814                    changed = true;
 2815                }
 2816            }
 2817
 02818            return changed;
 2819        }
 2820
 2821        public ItemLookupInfo ParseName(string name)
 2822        {
 02823            var namingOptions = _namingOptions;
 02824            var result = VideoResolver.CleanDateTime(name, namingOptions);
 2825
 02826            return new ItemLookupInfo
 02827            {
 02828                Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name
 02829                Year = result.Year
 02830            };
 2831        }
 2832
 2833        public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID
 2834        {
 2835            // Apply .ignore rules
 2836            var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
 2837            var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co
 2838            if (ownerVideoInfo is null)
 2839            {
 2840                yield break;
 2841            }
 2842
 2843            var count = filtered.Count;
 2844            for (var i = 0; i < count; i++)
 2845            {
 2846                var current = filtered[i];
 2847                if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
 2848                {
 2849                    var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
 2850                    var filesInSubFolderList = filesInSubFolder.ToList();
 2851
 2852                    bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
 2853
 2854                    foreach (var file in filesInSubFolderList)
 2855                    {
 2856                        if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
 2857                        {
 2858                            continue;
 2859                        }
 2860
 2861                        var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
 2862                        if (extra is not null)
 2863                        {
 2864                            yield return extra;
 2865                        }
 2866                    }
 2867                }
 2868                else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo
 2869                {
 2870                    var extra = GetExtra(current, extraType.Value, false);
 2871                    if (extra is not null)
 2872                    {
 2873                        yield return extra;
 2874                    }
 2875                }
 2876            }
 2877
 2878            BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
 2879            {
 2880                var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso
 2881                if (extra is not Video && extra is not Audio)
 2882                {
 2883                    return null;
 2884                }
 2885
 2886                // Try to retrieve it from the db. If we don't find it, use the resolved version
 2887                var itemById = GetItemById(extra.Id);
 2888                if (itemById is not null)
 2889                {
 2890                    extra = itemById;
 2891                }
 2892
 2893                // Only update extra type if it is more specific then the currently known extra type
 2894                if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
 2895                {
 2896                    extra.ExtraType = extraType;
 2897                }
 2898
 2899                extra.ParentId = Guid.Empty;
 2900                extra.OwnerId = owner.Id;
 2901                extra.IsInMixedFolder = isInMixedFolder;
 2902                return extra;
 2903            }
 2904        }
 2905
 2906        public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
 2907        {
 122908            foreach (var map in _configurationManager.Configuration.PathSubstitutions)
 2909            {
 02910                if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
 2911                {
 02912                    return newPath;
 2913                }
 2914            }
 2915
 62916            return path;
 2917        }
 2918
 2919        public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
 2920        {
 02921            return _peopleRepository.GetPeople(query);
 2922        }
 2923
 2924        public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
 2925        {
 62926            if (item.SupportsPeople)
 2927            {
 02928                var people = GetPeople(new InternalPeopleQuery
 02929                {
 02930                    ItemId = item.Id
 02931                });
 2932
 02933                if (people.Count > 0)
 2934                {
 02935                    return people;
 2936                }
 2937            }
 2938
 62939            return [];
 2940        }
 2941
 2942        public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
 2943        {
 02944            return _peopleRepository.GetPeopleNames(query)
 02945            .Select(i =>
 02946            {
 02947                try
 02948                {
 02949                    return GetPerson(i);
 02950                }
 02951                catch (Exception ex)
 02952                {
 02953                    _logger.LogError(ex, "Error getting person");
 02954                    return null;
 02955                }
 02956            })
 02957            .Where(i => i is not null)
 02958            .Where(i => query.User is null || i!.IsVisible(query.User))
 02959            .ToList()!; // null values are filtered out
 2960        }
 2961
 2962        public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
 2963        {
 02964            return _peopleRepository.GetPeopleNames(query);
 2965        }
 2966
 2967        public void UpdatePeople(BaseItem item, List<PersonInfo> people)
 2968        {
 02969            UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
 02970        }
 2971
 2972        /// <inheritdoc />
 2973        public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat
 2974        {
 2975            if (!item.SupportsPeople)
 2976            {
 2977                return;
 2978            }
 2979
 2980            if (people is not null)
 2981            {
 2982                people = people.Where(e => e is not null).ToArray();
 2983                _peopleRepository.UpdatePeople(item.Id, people);
 2984                await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
 2985            }
 2986        }
 2987
 2988        public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re
 2989        {
 2990            foreach (var url in image.Path.Split('|'))
 2991            {
 2992                try
 2993                {
 2994                    _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
 2995
 2996                    await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure
 2997
 2998                    await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai
 2999
 3000                    return item.GetImageInfo(image.Type, imageIndex);
 3001                }
 3002                catch (HttpRequestException ex)
 3003                {
 3004                    if (ex.StatusCode.HasValue
 3005                        && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb
 3006                    {
 3007                        _logger.LogDebug(ex, "Error downloading image {Url}", url);
 3008                        continue;
 3009                    }
 3010
 3011                    throw;
 3012                }
 3013            }
 3014
 3015            if (removeOnFailure)
 3016            {
 3017                // Remove this image to prevent it from retrying over and over
 3018                item.RemoveImage(image);
 3019                await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa
 3020            }
 3021
 3022            throw new InvalidOperationException("Unable to convert any images to local");
 3023        }
 3024
 3025        public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b
 3026        {
 3027            if (string.IsNullOrWhiteSpace(name))
 3028            {
 3029                throw new ArgumentNullException(nameof(name));
 3030            }
 3031
 3032            name = _fileSystem.GetValidFilename(name.Trim());
 3033
 3034            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3035
 3036            var existingNameCount = 1; // first numbered name will be 2
 3037            var virtualFolderPath = Path.Combine(rootFolderPath, name);
 3038            var originalName = name;
 3039            while (Directory.Exists(virtualFolderPath))
 3040            {
 3041                existingNameCount++;
 3042                name = originalName + existingNameCount;
 3043                virtualFolderPath = Path.Combine(rootFolderPath, name);
 3044            }
 3045
 3046            var mediaPathInfos = options.PathInfos;
 3047            if (mediaPathInfos is not null)
 3048            {
 3049                var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
 3050                if (invalidpath is not null)
 3051                {
 3052                    throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
 3053                }
 3054            }
 3055
 3056            LibraryMonitor.Stop();
 3057
 3058            try
 3059            {
 3060                Directory.CreateDirectory(virtualFolderPath);
 3061
 3062                if (collectionType is not null)
 3063                {
 3064                    var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect
 3065
 3066                    FileHelper.CreateEmpty(path);
 3067                }
 3068
 3069                CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
 3070
 3071                if (mediaPathInfos is not null)
 3072                {
 3073                    foreach (var path in mediaPathInfos)
 3074                    {
 3075                        AddMediaPathInternal(name, path, false);
 3076                    }
 3077                }
 3078            }
 3079            finally
 3080            {
 3081                await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
 3082
 3083                if (refreshLibrary)
 3084                {
 3085                    StartScanInBackground();
 3086                }
 3087                else
 3088                {
 3089                    // Need to add a delay here or directory watchers may still pick up the changes
 3090                    await Task.Delay(1000).ConfigureAwait(false);
 3091                    LibraryMonitor.Start();
 3092                }
 3093            }
 3094        }
 3095
 3096        private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
 3097        {
 3098            foreach (var person in people)
 3099            {
 3100                cancellationToken.ThrowIfCancellationRequested();
 3101
 3102                var itemUpdateType = ItemUpdateType.MetadataDownload;
 3103                var saveEntity = false;
 3104                var createEntity = false;
 3105                var personEntity = GetPerson(person.Name);
 3106
 3107                if (personEntity is null)
 3108                {
 3109                    try
 3110                    {
 3111                        var path = Person.GetPath(person.Name);
 3112                        var info = Directory.CreateDirectory(path);
 3113                        personEntity = new Person()
 3114                        {
 3115                            Name = person.Name,
 3116                            Id = GetItemByNameId<Person>(path),
 3117                            DateCreated = info.CreationTimeUtc,
 3118                            DateModified = info.LastWriteTimeUtc,
 3119                            Path = path
 3120                        };
 3121
 3122                        personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
 3123                        saveEntity = true;
 3124                        createEntity = true;
 3125                    }
 3126                    catch (Exception ex)
 3127                    {
 3128                        _logger.LogWarning(ex, "Failed to create person {Name}", person.Name);
 3129                        continue;
 3130                    }
 3131                }
 3132
 3133                foreach (var id in person.ProviderIds)
 3134                {
 3135                    if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)
 3136                    {
 3137                        personEntity.SetProviderId(id.Key, id.Value);
 3138                        saveEntity = true;
 3139                    }
 3140                }
 3141
 3142                if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
 3143                {
 3144                    personEntity.SetImage(
 3145                        new ItemImageInfo
 3146                        {
 3147                            Path = person.ImageUrl,
 3148                            Type = ImageType.Primary
 3149                        },
 3150                        0);
 3151
 3152                    saveEntity = true;
 3153                    itemUpdateType = ItemUpdateType.ImageUpdate;
 3154                }
 3155
 3156                if (saveEntity)
 3157                {
 3158                    if (createEntity)
 3159                    {
 3160                        CreateItems([personEntity], null, CancellationToken.None);
 3161                    }
 3162
 3163                    await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
 3164                    personEntity.DateLastSaved = DateTime.UtcNow;
 3165
 3166                    CreateItems([personEntity], null, CancellationToken.None);
 3167                }
 3168            }
 3169        }
 3170
 3171        private void StartScanInBackground()
 3172        {
 33173            Task.Run(() =>
 33174            {
 33175                // No need to start if scanning the library because it will handle it
 33176                ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
 33177            });
 33178        }
 3179
 3180        public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3181        {
 13182            AddMediaPathInternal(virtualFolderName, mediaPath, true);
 03183        }
 3184
 3185        private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
 3186        {
 13187            ArgumentNullException.ThrowIfNull(pathInfo);
 3188
 13189            var path = pathInfo.Path;
 3190
 13191            if (string.IsNullOrWhiteSpace(path))
 3192            {
 03193                throw new ArgumentException(nameof(path));
 3194            }
 3195
 13196            if (!Directory.Exists(path))
 3197            {
 13198                throw new FileNotFoundException("The path does not exist.");
 3199            }
 3200
 03201            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03202            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3203
 03204            CreateShortcut(virtualFolderPath, pathInfo);
 3205
 03206            if (saveLibraryOptions)
 3207            {
 03208                var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3209
 03210                libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
 3211
 03212                SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3213
 03214                CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 3215            }
 03216        }
 3217
 3218        public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
 3219        {
 03220            ArgumentNullException.ThrowIfNull(mediaPath);
 3221
 03222            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 03223            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3224
 03225            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3226
 03227            SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
 3228
 03229            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03230        }
 3231
 3232        private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
 3233        {
 03234            var topLibraryFolders = GetUserRootFolder().Children.ToList();
 03235            var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
 3236
 03237            if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
 3238            {
 03239                var list = options.PathInfos.ToList();
 3240
 03241                foreach (var location in info.Locations)
 3242                {
 03243                    if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
 3244                    {
 03245                        list.Add(new MediaPathInfo(location));
 3246                    }
 3247                }
 3248
 03249                options.PathInfos = list.ToArray();
 3250            }
 03251        }
 3252
 3253        public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
 3254        {
 3255            if (string.IsNullOrWhiteSpace(name))
 3256            {
 3257                throw new ArgumentNullException(nameof(name));
 3258            }
 3259
 3260            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3261
 3262            var path = Path.Combine(rootFolderPath, name);
 3263
 3264            if (!Directory.Exists(path))
 3265            {
 3266                throw new FileNotFoundException("The media folder does not exist");
 3267            }
 3268
 3269            LibraryMonitor.Stop();
 3270
 3271            try
 3272            {
 3273                Directory.Delete(path, true);
 3274            }
 3275            finally
 3276            {
 3277                CollectionFolder.OnCollectionFolderChange();
 3278
 3279                if (refreshLibrary)
 3280                {
 3281                    await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
 3282
 3283                    StartScanInBackground();
 3284                }
 3285                else
 3286                {
 3287                    // Need to add a delay here or directory watchers may still pick up the changes
 3288                    await Task.Delay(1000).ConfigureAwait(false);
 3289                    LibraryMonitor.Start();
 3290                }
 3291            }
 3292        }
 3293
 3294        private void RemoveContentTypeOverrides(string path)
 3295        {
 03296            if (string.IsNullOrWhiteSpace(path))
 3297            {
 03298                throw new ArgumentNullException(nameof(path));
 3299            }
 3300
 03301            List<NameValuePair>? removeList = null;
 3302
 03303            foreach (var contentType in _configurationManager.Configuration.ContentTypes)
 3304            {
 03305                if (string.IsNullOrWhiteSpace(contentType.Name)
 03306                    || _fileSystem.AreEqual(path, contentType.Name)
 03307                    || _fileSystem.ContainsSubPath(path, contentType.Name))
 3308                {
 03309                    (removeList ??= new()).Add(contentType);
 3310                }
 3311            }
 3312
 03313            if (removeList is not null)
 3314            {
 03315                _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
 03316                    .Except(removeList)
 03317                    .ToArray();
 3318
 03319                _configurationManager.SaveConfiguration();
 3320            }
 03321        }
 3322
 3323        public void RemoveMediaPath(string virtualFolderName, string mediaPath)
 3324        {
 13325            ArgumentException.ThrowIfNullOrEmpty(mediaPath);
 3326
 13327            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 13328            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
 3329
 13330            if (!Directory.Exists(virtualFolderPath))
 3331            {
 13332                throw new FileNotFoundException(
 13333                    string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder
 3334            }
 3335
 03336            var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
 03337                .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa
 03338                .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String
 3339
 03340            if (!string.IsNullOrEmpty(shortcut))
 3341            {
 03342                _fileSystem.DeleteFile(shortcut);
 3343            }
 3344
 03345            var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
 3346
 03347            libraryOptions.PathInfos = libraryOptions
 03348                .PathInfos
 03349                .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
 03350                .ToArray();
 3351
 03352            CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
 03353        }
 3354
 3355        private static bool ItemIsVisible(BaseItem? item, User? user)
 3356        {
 213357            if (item is null)
 3358            {
 213359                return false;
 3360            }
 3361
 03362            if (user is null)
 3363            {
 03364                return true;
 3365            }
 3366
 03367            return item is UserRootFolder || item.IsVisibleStandalone(user);
 3368        }
 3369
 3370        public void CreateShortcut(string virtualFolderPath, MediaPathInfo pathInfo)
 3371        {
 03372            var path = pathInfo.Path;
 03373            var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
 3374
 03375            var shortcutFilename = Path.GetFileNameWithoutExtension(path);
 3376
 03377            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3378
 03379            while (File.Exists(lnk))
 3380            {
 03381                shortcutFilename += "1";
 03382                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
 3383            }
 3384
 03385            _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
 03386            RemoveContentTypeOverrides(path);
 03387        }
 3388    }
 3389}

Methods/Properties

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