| | 1 | | #pragma warning disable CS1591 |
| | 2 | | #pragma warning disable CA5394 |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Generic; |
| | 6 | | using System.Globalization; |
| | 7 | | using System.IO; |
| | 8 | | using System.Linq; |
| | 9 | | using System.Net; |
| | 10 | | using System.Net.Http; |
| | 11 | | using System.Threading; |
| | 12 | | using System.Threading.Tasks; |
| | 13 | | using BitFaster.Caching.Lru; |
| | 14 | | using Emby.Naming.Common; |
| | 15 | | using Emby.Naming.TV; |
| | 16 | | using Emby.Server.Implementations.Library.Resolvers; |
| | 17 | | using Emby.Server.Implementations.Library.Validators; |
| | 18 | | using Emby.Server.Implementations.Playlists; |
| | 19 | | using Emby.Server.Implementations.ScheduledTasks.Tasks; |
| | 20 | | using Emby.Server.Implementations.Sorting; |
| | 21 | | using Jellyfin.Data; |
| | 22 | | using Jellyfin.Data.Enums; |
| | 23 | | using Jellyfin.Database.Implementations.Entities; |
| | 24 | | using Jellyfin.Database.Implementations.Enums; |
| | 25 | | using Jellyfin.Extensions; |
| | 26 | | using MediaBrowser.Common.Extensions; |
| | 27 | | using MediaBrowser.Controller; |
| | 28 | | using MediaBrowser.Controller.Configuration; |
| | 29 | | using MediaBrowser.Controller.Drawing; |
| | 30 | | using MediaBrowser.Controller.Dto; |
| | 31 | | using MediaBrowser.Controller.Entities; |
| | 32 | | using MediaBrowser.Controller.Entities.Audio; |
| | 33 | | using MediaBrowser.Controller.IO; |
| | 34 | | using MediaBrowser.Controller.Library; |
| | 35 | | using MediaBrowser.Controller.LiveTv; |
| | 36 | | using MediaBrowser.Controller.MediaEncoding; |
| | 37 | | using MediaBrowser.Controller.MediaSegments; |
| | 38 | | using MediaBrowser.Controller.Persistence; |
| | 39 | | using MediaBrowser.Controller.Providers; |
| | 40 | | using MediaBrowser.Controller.Resolvers; |
| | 41 | | using MediaBrowser.Controller.Sorting; |
| | 42 | | using MediaBrowser.Controller.Trickplay; |
| | 43 | | using MediaBrowser.Model.Configuration; |
| | 44 | | using MediaBrowser.Model.Dlna; |
| | 45 | | using MediaBrowser.Model.Drawing; |
| | 46 | | using MediaBrowser.Model.Dto; |
| | 47 | | using MediaBrowser.Model.Entities; |
| | 48 | | using MediaBrowser.Model.IO; |
| | 49 | | using MediaBrowser.Model.Library; |
| | 50 | | using MediaBrowser.Model.Querying; |
| | 51 | | using MediaBrowser.Model.Tasks; |
| | 52 | | using Microsoft.Extensions.Logging; |
| | 53 | | using Episode = MediaBrowser.Controller.Entities.TV.Episode; |
| | 54 | | using EpisodeInfo = Emby.Naming.TV.EpisodeInfo; |
| | 55 | | using Genre = MediaBrowser.Controller.Entities.Genre; |
| | 56 | | using Person = MediaBrowser.Controller.Entities.Person; |
| | 57 | | using VideoResolver = Emby.Naming.Video.VideoResolver; |
| | 58 | |
|
| | 59 | | namespace 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> |
| 28 | 90 | | private readonly Lock _rootFolderSyncLock = new(); |
| 28 | 91 | | private readonly Lock _userRootFolderSyncLock = new(); |
| | 92 | |
|
| 28 | 93 | | 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 | | { |
| 28 | 142 | | _appHost = appHost; |
| 28 | 143 | | _logger = loggerFactory.CreateLogger<LibraryManager>(); |
| 28 | 144 | | _taskManager = taskManager; |
| 28 | 145 | | _userManager = userManager; |
| 28 | 146 | | _configurationManager = configurationManager; |
| 28 | 147 | | _userDataManager = userDataManager; |
| 28 | 148 | | _libraryMonitorFactory = libraryMonitorFactory; |
| 28 | 149 | | _fileSystem = fileSystem; |
| 28 | 150 | | _providerManagerFactory = providerManagerFactory; |
| 28 | 151 | | _userViewManagerFactory = userViewManagerFactory; |
| 28 | 152 | | _mediaEncoder = mediaEncoder; |
| 28 | 153 | | _itemRepository = itemRepository; |
| 28 | 154 | | _imageProcessor = imageProcessor; |
| | 155 | |
|
| 28 | 156 | | _cache = new FastConcurrentLru<Guid, BaseItem>(_configurationManager.Configuration.CacheSize); |
| | 157 | |
|
| 28 | 158 | | _namingOptions = namingOptions; |
| 28 | 159 | | _peopleRepository = peopleRepository; |
| 28 | 160 | | _pathManager = pathManager; |
| 28 | 161 | | _extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryServ |
| | 162 | |
|
| 28 | 163 | | _configurationManager.ConfigurationUpdated += ConfigurationUpdated; |
| | 164 | |
|
| 28 | 165 | | RecordConfigurationValues(_configurationManager.Configuration); |
| 28 | 166 | | } |
| | 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 | | { |
| 182 | 191 | | if (_rootFolder is null) |
| 21 | 192 | | { |
| | 193 | | lock (_rootFolderSyncLock) |
| | 194 | | { |
| 21 | 195 | | _rootFolder ??= CreateRootFolder(); |
| 21 | 196 | | } |
| | 197 | | } |
| | 198 | |
|
| 182 | 199 | | return _rootFolder; |
| | 200 | | } |
| | 201 | | } |
| | 202 | |
|
| 41 | 203 | | private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value; |
| | 204 | |
|
| 113 | 205 | | private IProviderManager ProviderManager => _providerManagerFactory.Value; |
| | 206 | |
|
| 1 | 207 | | 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 | | { |
| 28 | 258 | | EntityResolutionIgnoreRules = rules.ToArray(); |
| 28 | 259 | | EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray(); |
| 28 | 260 | | MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray(); |
| 28 | 261 | | IntroProviders = introProviders.ToArray(); |
| 28 | 262 | | Comparers = itemComparers.ToArray(); |
| 28 | 263 | | PostScanTasks = postScanTasks.ToArray(); |
| 28 | 264 | | } |
| | 265 | |
|
| | 266 | | /// <summary> |
| | 267 | | /// Records the configuration values. |
| | 268 | | /// </summary> |
| | 269 | | /// <param name="configuration">The configuration.</param> |
| | 270 | | private void RecordConfigurationValues(ServerConfiguration configuration) |
| | 271 | | { |
| 129 | 272 | | _wizardCompleted = configuration.IsStartupWizardCompleted; |
| 129 | 273 | | } |
| | 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 | | { |
| 101 | 282 | | var config = _configurationManager.Configuration; |
| | 283 | |
|
| 101 | 284 | | var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted; |
| | 285 | |
|
| 101 | 286 | | RecordConfigurationValues(config); |
| | 287 | |
|
| 101 | 288 | | if (wizardChanged) |
| | 289 | | { |
| 16 | 290 | | _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>(); |
| | 291 | | } |
| 101 | 292 | | } |
| | 293 | |
|
| | 294 | | public void RegisterItem(BaseItem item) |
| | 295 | | { |
| 182 | 296 | | ArgumentNullException.ThrowIfNull(item); |
| | 297 | |
|
| 182 | 298 | | if (item is IItemByName) |
| | 299 | | { |
| 0 | 300 | | if (item is not MusicArtist) |
| | 301 | | { |
| 0 | 302 | | return; |
| | 303 | | } |
| | 304 | | } |
| 182 | 305 | | else if (!item.IsFolder) |
| | 306 | | { |
| 0 | 307 | | if (item is not Video && item is not LiveTvChannel) |
| | 308 | | { |
| 0 | 309 | | return; |
| | 310 | | } |
| | 311 | | } |
| | 312 | |
|
| 182 | 313 | | _cache.AddOrUpdate(item.Id, item); |
| 182 | 314 | | } |
| | 315 | |
|
| | 316 | | public void DeleteItem(BaseItem item, DeleteOptions options) |
| | 317 | | { |
| 0 | 318 | | DeleteItem(item, options, false); |
| 0 | 319 | | } |
| | 320 | |
|
| | 321 | | public void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem) |
| | 322 | | { |
| 0 | 323 | | ArgumentNullException.ThrowIfNull(item); |
| | 324 | |
|
| 0 | 325 | | var parent = item.GetOwner() ?? item.GetParent(); |
| | 326 | |
|
| 0 | 327 | | DeleteItem(item, options, parent, notifyParentItem); |
| 0 | 328 | | } |
| | 329 | |
|
| | 330 | | public void DeleteItemsUnsafeFast(IEnumerable<BaseItem> items) |
| | 331 | | { |
| 0 | 332 | | var pathMaps = items.Select(e => (Item: e, InternalPath: GetInternalMetadataPaths(e), DeletePaths: e.GetDele |
| | 333 | |
|
| 0 | 334 | | foreach (var (item, internalPaths, pathsToDelete) in pathMaps) |
| | 335 | | { |
| 0 | 336 | | foreach (var metadataPath in internalPaths) |
| | 337 | | { |
| 0 | 338 | | if (!Directory.Exists(metadataPath)) |
| | 339 | | { |
| | 340 | | continue; |
| | 341 | | } |
| | 342 | |
|
| 0 | 343 | | _logger.LogDebug( |
| 0 | 344 | | "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}", |
| 0 | 345 | | item.GetType().Name, |
| 0 | 346 | | item.Name ?? "Unknown name", |
| 0 | 347 | | metadataPath, |
| 0 | 348 | | item.Id); |
| | 349 | |
|
| | 350 | | try |
| | 351 | | { |
| 0 | 352 | | Directory.Delete(metadataPath, true); |
| 0 | 353 | | } |
| 0 | 354 | | catch (Exception ex) |
| | 355 | | { |
| 0 | 356 | | _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath); |
| 0 | 357 | | } |
| | 358 | | } |
| | 359 | |
|
| 0 | 360 | | foreach (var fileSystemInfo in pathsToDelete) |
| | 361 | | { |
| 0 | 362 | | DeleteItemPath(item, false, fileSystemInfo); |
| | 363 | | } |
| | 364 | | } |
| | 365 | |
|
| 0 | 366 | | _itemRepository.DeleteItem([.. pathMaps.Select(f => f.Item.Id)]); |
| 0 | 367 | | } |
| | 368 | |
|
| | 369 | | public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem) |
| | 370 | | { |
| 0 | 371 | | ArgumentNullException.ThrowIfNull(item); |
| | 372 | |
|
| 0 | 373 | | if (item.SourceType == SourceType.Channel) |
| | 374 | | { |
| 0 | 375 | | if (options.DeleteFromExternalProvider) |
| | 376 | | { |
| | 377 | | try |
| | 378 | | { |
| 0 | 379 | | BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult(); |
| 0 | 380 | | } |
| 0 | 381 | | catch (ArgumentException) |
| | 382 | | { |
| | 383 | | // channel no longer installed |
| 0 | 384 | | } |
| | 385 | | } |
| | 386 | |
|
| 0 | 387 | | options.DeleteFileLocation = false; |
| | 388 | | } |
| | 389 | |
|
| 0 | 390 | | if (item is LiveTvProgram) |
| | 391 | | { |
| 0 | 392 | | _logger.LogDebug( |
| 0 | 393 | | "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}", |
| 0 | 394 | | item.GetType().Name, |
| 0 | 395 | | item.Name ?? "Unknown name", |
| 0 | 396 | | item.Path ?? string.Empty, |
| 0 | 397 | | item.Id); |
| | 398 | | } |
| | 399 | | else |
| | 400 | | { |
| 0 | 401 | | _logger.LogInformation( |
| 0 | 402 | | "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}", |
| 0 | 403 | | item.GetType().Name, |
| 0 | 404 | | item.Name ?? "Unknown name", |
| 0 | 405 | | item.Path ?? string.Empty, |
| 0 | 406 | | item.Id); |
| | 407 | | } |
| | 408 | |
|
| 0 | 409 | | var children = item.IsFolder |
| 0 | 410 | | ? ((Folder)item).GetRecursiveChildren(false) |
| 0 | 411 | | : []; |
| | 412 | |
|
| 0 | 413 | | foreach (var metadataPath in GetMetadataPaths(item, children)) |
| | 414 | | { |
| 0 | 415 | | if (!Directory.Exists(metadataPath)) |
| | 416 | | { |
| | 417 | | continue; |
| | 418 | | } |
| | 419 | |
|
| 0 | 420 | | _logger.LogDebug( |
| 0 | 421 | | "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}", |
| 0 | 422 | | item.GetType().Name, |
| 0 | 423 | | item.Name ?? "Unknown name", |
| 0 | 424 | | metadataPath, |
| 0 | 425 | | item.Id); |
| | 426 | |
|
| | 427 | | try |
| | 428 | | { |
| 0 | 429 | | Directory.Delete(metadataPath, true); |
| 0 | 430 | | } |
| 0 | 431 | | catch (Exception ex) |
| | 432 | | { |
| 0 | 433 | | _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath); |
| 0 | 434 | | } |
| | 435 | | } |
| | 436 | |
|
| 0 | 437 | | 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 |
| 0 | 441 | | var isRequiredForDelete = true; |
| | 442 | |
|
| 0 | 443 | | foreach (var fileSystemInfo in item.GetDeletePaths()) |
| | 444 | | { |
| 0 | 445 | | DeleteItemPath(item, isRequiredForDelete, fileSystemInfo); |
| | 446 | |
|
| 0 | 447 | | isRequiredForDelete = false; |
| | 448 | | } |
| | 449 | | } |
| | 450 | |
|
| 0 | 451 | | item.SetParent(null); |
| | 452 | |
|
| 0 | 453 | | _itemRepository.DeleteItem([item.Id, .. children.Select(f => f.Id)]); |
| 0 | 454 | | _cache.TryRemove(item.Id, out _); |
| 0 | 455 | | foreach (var child in children) |
| | 456 | | { |
| 0 | 457 | | _cache.TryRemove(child.Id, out _); |
| | 458 | | } |
| | 459 | |
|
| 0 | 460 | | ReportItemRemoved(item, parent); |
| 0 | 461 | | } |
| | 462 | |
|
| | 463 | | private void DeleteItemPath(BaseItem item, bool isRequiredForDelete, FileSystemMetadata fileSystemInfo) |
| | 464 | | { |
| 0 | 465 | | if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName)) |
| | 466 | | { |
| | 467 | | try |
| | 468 | | { |
| 0 | 469 | | _logger.LogInformation( |
| 0 | 470 | | "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}", |
| 0 | 471 | | item.GetType().Name, |
| 0 | 472 | | item.Name ?? "Unknown name", |
| 0 | 473 | | fileSystemInfo.FullName, |
| 0 | 474 | | item.Id); |
| | 475 | |
|
| 0 | 476 | | if (fileSystemInfo.IsDirectory) |
| | 477 | | { |
| 0 | 478 | | Directory.Delete(fileSystemInfo.FullName, true); |
| | 479 | | } |
| | 480 | | else |
| | 481 | | { |
| 0 | 482 | | File.Delete(fileSystemInfo.FullName); |
| | 483 | | } |
| 0 | 484 | | } |
| 0 | 485 | | catch (DirectoryNotFoundException) |
| | 486 | | { |
| 0 | 487 | | _logger.LogInformation( |
| 0 | 488 | | "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: |
| 0 | 489 | | item.GetType().Name, |
| 0 | 490 | | item.Name ?? "Unknown name", |
| 0 | 491 | | fileSystemInfo.FullName, |
| 0 | 492 | | item.Id); |
| 0 | 493 | | } |
| 0 | 494 | | catch (FileNotFoundException) |
| | 495 | | { |
| 0 | 496 | | _logger.LogInformation( |
| 0 | 497 | | "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id} |
| 0 | 498 | | item.GetType().Name, |
| 0 | 499 | | item.Name ?? "Unknown name", |
| 0 | 500 | | fileSystemInfo.FullName, |
| 0 | 501 | | item.Id); |
| 0 | 502 | | } |
| 0 | 503 | | catch (IOException) |
| | 504 | | { |
| 0 | 505 | | if (isRequiredForDelete) |
| | 506 | | { |
| 0 | 507 | | throw; |
| | 508 | | } |
| 0 | 509 | | } |
| 0 | 510 | | catch (UnauthorizedAccessException) |
| | 511 | | { |
| 0 | 512 | | if (isRequiredForDelete) |
| | 513 | | { |
| 0 | 514 | | throw; |
| | 515 | | } |
| 0 | 516 | | } |
| | 517 | | } |
| 0 | 518 | | } |
| | 519 | |
|
| | 520 | | private bool IsInternalItem(BaseItem item) |
| | 521 | | { |
| 0 | 522 | | if (!item.IsFileProtocol) |
| | 523 | | { |
| 0 | 524 | | return false; |
| | 525 | | } |
| | 526 | |
|
| 0 | 527 | | var pathToCheck = item switch |
| 0 | 528 | | { |
| 0 | 529 | | Genre => _configurationManager.ApplicationPaths.GenrePath, |
| 0 | 530 | | MusicArtist => _configurationManager.ApplicationPaths.ArtistsPath, |
| 0 | 531 | | MusicGenre => _configurationManager.ApplicationPaths.MusicGenrePath, |
| 0 | 532 | | Person => _configurationManager.ApplicationPaths.PeoplePath, |
| 0 | 533 | | Studio => _configurationManager.ApplicationPaths.StudioPath, |
| 0 | 534 | | Year => _configurationManager.ApplicationPaths.YearPath, |
| 0 | 535 | | _ => null |
| 0 | 536 | | }; |
| | 537 | |
|
| 0 | 538 | | var itemPath = item.Path; |
| 0 | 539 | | if (!string.IsNullOrEmpty(pathToCheck) && !string.IsNullOrEmpty(itemPath)) |
| | 540 | | { |
| 0 | 541 | | var cleanPath = _fileSystem.GetValidFilename(itemPath); |
| 0 | 542 | | var cleanCheckPath = _fileSystem.GetValidFilename(pathToCheck); |
| | 543 | |
|
| 0 | 544 | | return cleanPath.StartsWith(cleanCheckPath, StringComparison.Ordinal); |
| | 545 | | } |
| | 546 | |
|
| 0 | 547 | | return false; |
| | 548 | | } |
| | 549 | |
|
| | 550 | | private List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children) |
| | 551 | | { |
| 0 | 552 | | var list = GetInternalMetadataPaths(item); |
| 0 | 553 | | foreach (var child in children) |
| | 554 | | { |
| 0 | 555 | | list.AddRange(GetInternalMetadataPaths(child)); |
| | 556 | | } |
| | 557 | |
|
| 0 | 558 | | return list; |
| | 559 | | } |
| | 560 | |
|
| | 561 | | private List<string> GetInternalMetadataPaths(BaseItem item) |
| | 562 | | { |
| 0 | 563 | | var list = new List<string> |
| 0 | 564 | | { |
| 0 | 565 | | item.GetInternalMetadataPath() |
| 0 | 566 | | }; |
| | 567 | |
|
| 0 | 568 | | if (item is Video video) |
| | 569 | | { |
| | 570 | | // Trickplay |
| 0 | 571 | | list.Add(_pathManager.GetTrickplayDirectory(video)); |
| | 572 | |
|
| | 573 | | // Subtitles and attachments |
| 0 | 574 | | foreach (var mediaSource in item.GetMediaSources(false)) |
| | 575 | | { |
| 0 | 576 | | var subtitleFolder = _pathManager.GetSubtitleFolderPath(mediaSource.Id); |
| 0 | 577 | | if (subtitleFolder is not null) |
| | 578 | | { |
| 0 | 579 | | list.Add(subtitleFolder); |
| | 580 | | } |
| | 581 | |
|
| 0 | 582 | | var attachmentFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id); |
| 0 | 583 | | if (attachmentFolder is not null) |
| | 584 | | { |
| 0 | 585 | | list.Add(attachmentFolder); |
| | 586 | | } |
| | 587 | | } |
| | 588 | | } |
| | 589 | |
|
| 0 | 590 | | return list; |
| | 591 | | } |
| | 592 | |
|
| | 593 | | /// <summary> |
| | 594 | | /// Resolves the item. |
| | 595 | | /// </summary> |
| | 596 | | /// <param name="args">The args.</param> |
| | 597 | | /// <param name="resolvers">The resolvers.</param> |
| | 598 | | /// <returns>BaseItem.</returns> |
| | 599 | | private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers) |
| | 600 | | { |
| 77 | 601 | | var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r)) |
| 77 | 602 | | .FirstOrDefault(i => i is not null); |
| | 603 | |
|
| 77 | 604 | | if (item is not null) |
| | 605 | | { |
| 67 | 606 | | ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this); |
| | 607 | | } |
| | 608 | |
|
| 77 | 609 | | return item; |
| | 610 | | } |
| | 611 | |
|
| | 612 | | private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver) |
| | 613 | | { |
| | 614 | | try |
| | 615 | | { |
| 307 | 616 | | return resolver.ResolvePath(args); |
| | 617 | | } |
| 0 | 618 | | catch (Exception ex) |
| | 619 | | { |
| 0 | 620 | | _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path); |
| 0 | 621 | | return null; |
| | 622 | | } |
| 307 | 623 | | } |
| | 624 | |
|
| | 625 | | public Guid GetNewItemId(string key, Type type) |
| | 626 | | { |
| 130 | 627 | | return GetNewItemIdInternal(key, type, false); |
| | 628 | | } |
| | 629 | |
|
| | 630 | | private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive) |
| | 631 | | { |
| 131 | 632 | | ArgumentException.ThrowIfNullOrEmpty(key); |
| 131 | 633 | | ArgumentNullException.ThrowIfNull(type); |
| | 634 | |
|
| 131 | 635 | | string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath; |
| 131 | 636 | | if (key.StartsWith(programDataPath, StringComparison.Ordinal)) |
| | 637 | | { |
| | 638 | | // Try to normalize paths located underneath program-data in an attempt to make them more portable |
| 114 | 639 | | key = key.Substring(programDataPath.Length) |
| 114 | 640 | | .TrimStart('/', '\\') |
| 114 | 641 | | .Replace('/', '\\'); |
| | 642 | | } |
| | 643 | |
|
| 131 | 644 | | if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds) |
| | 645 | | { |
| 1 | 646 | | key = key.ToLowerInvariant(); |
| | 647 | | } |
| | 648 | |
|
| 131 | 649 | | key = type.FullName + key; |
| | 650 | |
|
| 131 | 651 | | return key.GetMD5(); |
| | 652 | | } |
| | 653 | |
|
| | 654 | | public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directorySer |
| 42 | 655 | | => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent); |
| | 656 | |
|
| | 657 | | private BaseItem? ResolvePath( |
| | 658 | | FileSystemMetadata fileInfo, |
| | 659 | | IDirectoryService directoryService, |
| | 660 | | IItemResolver[]? resolvers, |
| | 661 | | Folder? parent = null, |
| | 662 | | CollectionType? collectionType = null, |
| | 663 | | LibraryOptions? libraryOptions = null) |
| | 664 | | { |
| 77 | 665 | | ArgumentNullException.ThrowIfNull(fileInfo); |
| | 666 | |
|
| 77 | 667 | | var fullPath = fileInfo.FullName; |
| | 668 | |
|
| 77 | 669 | | if (collectionType is null && parent is not null) |
| | 670 | | { |
| 18 | 671 | | collectionType = GetContentTypeOverride(fullPath, true); |
| | 672 | | } |
| | 673 | |
|
| 77 | 674 | | var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this) |
| 77 | 675 | | { |
| 77 | 676 | | Parent = parent, |
| 77 | 677 | | FileInfo = fileInfo, |
| 77 | 678 | | CollectionType = collectionType, |
| 77 | 679 | | LibraryOptions = libraryOptions |
| 77 | 680 | | }; |
| | 681 | |
|
| | 682 | | // Return null if ignore rules deem that we should do so |
| 77 | 683 | | if (IgnoreFile(args.FileInfo, args.Parent)) |
| | 684 | | { |
| 0 | 685 | | return null; |
| | 686 | | } |
| | 687 | |
|
| | 688 | | // Gather child folder and files |
| 77 | 689 | | if (args.IsDirectory) |
| | 690 | | { |
| 50 | 691 | | var isPhysicalRoot = args.IsPhysicalRoot; |
| | 692 | |
|
| | 693 | | // When resolving the root, we need it's grandchildren (children of user views) |
| 50 | 694 | | var flattenFolderDepth = isPhysicalRoot ? 2 : 0; |
| | 695 | |
|
| | 696 | | FileSystemMetadata[] files; |
| 50 | 697 | | var isVf = args.IsVf; |
| | 698 | |
|
| | 699 | | try |
| | 700 | | { |
| 50 | 701 | | files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _l |
| 50 | 702 | | } |
| 0 | 703 | | catch (Exception ex) |
| | 704 | | { |
| 0 | 705 | | if (parent is not null && parent.IsPhysicalRoot) |
| | 706 | | { |
| 0 | 707 | | _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPh |
| | 708 | |
|
| 0 | 709 | | files = []; |
| | 710 | | } |
| | 711 | | else |
| | 712 | | { |
| 0 | 713 | | throw; |
| | 714 | | } |
| 0 | 715 | | } |
| | 716 | |
|
| | 717 | | // Need to remove sub-paths that may have been resolved from shortcuts |
| | 718 | | // Example: if \\server\movies exists, then strip out \\server\movies\action |
| 50 | 719 | | if (isPhysicalRoot) |
| | 720 | | { |
| 21 | 721 | | files = NormalizeRootPathList(files).ToArray(); |
| | 722 | | } |
| | 723 | |
|
| 50 | 724 | | args.FileSystemChildren = files; |
| | 725 | | } |
| | 726 | |
|
| | 727 | | // Filter content based on ignore rules |
| 77 | 728 | | if (args.IsDirectory) |
| | 729 | | { |
| 50 | 730 | | var filtered = args.GetActualFileSystemChildren().ToArray(); |
| 50 | 731 | | args.FileSystemChildren = filtered ?? []; |
| | 732 | | } |
| | 733 | |
|
| 77 | 734 | | return ResolveItem(args, resolvers); |
| | 735 | | } |
| | 736 | |
|
| | 737 | | public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent) |
| 103 | 738 | | => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)); |
| | 739 | |
|
| | 740 | | public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths) |
| | 741 | | { |
| 80 | 742 | | var originalList = paths.ToList(); |
| | 743 | |
|
| 80 | 744 | | var list = originalList.Where(i => i.IsDirectory) |
| 80 | 745 | | .Select(i => Path.TrimEndingDirectorySeparator(i.FullName)) |
| 80 | 746 | | .Distinct() |
| 80 | 747 | | .ToList(); |
| | 748 | |
|
| 80 | 749 | | var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.Ordinal) && list.Any(i => _fileS |
| 80 | 750 | | .ToList(); |
| | 751 | |
|
| 160 | 752 | | foreach (var dupe in dupes) |
| | 753 | | { |
| 0 | 754 | | _logger.LogInformation("Found duplicate path: {0}", dupe); |
| | 755 | | } |
| | 756 | |
|
| 80 | 757 | | var newList = list.Except(dupes, StringComparer.Ordinal).Select(_fileSystem.GetDirectoryInfo).ToList(); |
| 80 | 758 | | newList.AddRange(originalList.Where(i => !i.IsDirectory)); |
| 80 | 759 | | return newList; |
| | 760 | | } |
| | 761 | |
|
| | 762 | | public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryServ |
| | 763 | | { |
| 59 | 764 | | return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers); |
| | 765 | | } |
| | 766 | |
|
| | 767 | | public IEnumerable<BaseItem> ResolvePaths( |
| | 768 | | IEnumerable<FileSystemMetadata> files, |
| | 769 | | IDirectoryService directoryService, |
| | 770 | | Folder parent, |
| | 771 | | LibraryOptions libraryOptions, |
| | 772 | | CollectionType? collectionType, |
| | 773 | | IItemResolver[] resolvers) |
| | 774 | | { |
| 59 | 775 | | var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList(); |
| | 776 | |
|
| 59 | 777 | | if (parent is not null) |
| | 778 | | { |
| 59 | 779 | | var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>() |
| | 780 | |
|
| 354 | 781 | | foreach (var resolver in multiItemResolvers) |
| | 782 | | { |
| 118 | 783 | | var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService); |
| | 784 | |
|
| 118 | 785 | | if (result?.Items.Count > 0) |
| | 786 | | { |
| 0 | 787 | | var items = result.Items; |
| 0 | 788 | | items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryServic |
| 0 | 789 | | items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, reso |
| 0 | 790 | | return items; |
| | 791 | | } |
| | 792 | | } |
| | 793 | | } |
| | 794 | |
|
| 59 | 795 | | return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions); |
| 0 | 796 | | } |
| | 797 | |
|
| | 798 | | private IEnumerable<BaseItem> ResolveFileList( |
| | 799 | | IReadOnlyList<FileSystemMetadata> fileList, |
| | 800 | | IDirectoryService directoryService, |
| | 801 | | Folder? parent, |
| | 802 | | CollectionType? collectionType, |
| | 803 | | IItemResolver[]? resolvers, |
| | 804 | | LibraryOptions libraryOptions) |
| | 805 | | { |
| | 806 | | // Given that fileList is a list we can save enumerator allocations by indexing |
| | 807 | | for (var i = 0; i < fileList.Count; i++) |
| | 808 | | { |
| | 809 | | var file = fileList[i]; |
| | 810 | | BaseItem? result = null; |
| | 811 | | try |
| | 812 | | { |
| | 813 | | result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions); |
| | 814 | | } |
| | 815 | | catch (Exception ex) |
| | 816 | | { |
| | 817 | | _logger.LogError(ex, "Error resolving path {Path}", file.FullName); |
| | 818 | | } |
| | 819 | |
|
| | 820 | | if (result is not null) |
| | 821 | | { |
| | 822 | | yield return result; |
| | 823 | | } |
| | 824 | | } |
| | 825 | | } |
| | 826 | |
|
| | 827 | | /// <summary> |
| | 828 | | /// Creates the root media folder. |
| | 829 | | /// </summary> |
| | 830 | | /// <returns>AggregateFolder.</returns> |
| | 831 | | /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</except |
| | 832 | | public AggregateFolder CreateRootFolder() |
| | 833 | | { |
| 21 | 834 | | var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath; |
| | 835 | |
|
| 21 | 836 | | var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? |
| 21 | 837 | | (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOp |
| 21 | 838 | | .DeepCopy<Folder, AggregateFolder>(); |
| | 839 | |
|
| | 840 | | // In case program data folder was moved |
| 21 | 841 | | if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal)) |
| | 842 | | { |
| 0 | 843 | | _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath); |
| 0 | 844 | | rootFolder.Path = rootFolderPath; |
| | 845 | | } |
| | 846 | |
|
| | 847 | | // Add in the plug-in folders |
| 21 | 848 | | var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists"); |
| | 849 | |
|
| 21 | 850 | | var info = Directory.CreateDirectory(path); |
| 21 | 851 | | Folder folder = new PlaylistsFolder |
| 21 | 852 | | { |
| 21 | 853 | | Path = path, |
| 21 | 854 | | DateCreated = info.CreationTimeUtc, |
| 21 | 855 | | DateModified = info.LastWriteTimeUtc, |
| 21 | 856 | | }; |
| | 857 | |
|
| 21 | 858 | | if (folder.Id.IsEmpty()) |
| | 859 | | { |
| 21 | 860 | | folder.Id = GetNewItemId(folder.Path, folder.GetType()); |
| | 861 | | } |
| | 862 | |
|
| 21 | 863 | | var dbItem = GetItemById(folder.Id) as BasePluginFolder; |
| | 864 | |
|
| 21 | 865 | | if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase)) |
| | 866 | | { |
| 0 | 867 | | folder = dbItem; |
| | 868 | | } |
| | 869 | |
|
| 21 | 870 | | if (!folder.ParentId.Equals(rootFolder.Id)) |
| | 871 | | { |
| 21 | 872 | | rootFolder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().G |
| 21 | 873 | | folder.ParentId = rootFolder.Id; |
| 21 | 874 | | folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetRe |
| | 875 | | } |
| | 876 | |
|
| 21 | 877 | | rootFolder.AddVirtualChild(folder); |
| | 878 | |
|
| 21 | 879 | | RegisterItem(folder); |
| | 880 | |
|
| 21 | 881 | | return rootFolder; |
| | 882 | | } |
| | 883 | |
|
| | 884 | | public Folder GetUserRootFolder() |
| | 885 | | { |
| 914 | 886 | | if (_userRootFolder is null) |
| 21 | 887 | | { |
| | 888 | | lock (_userRootFolderSyncLock) |
| | 889 | | { |
| 21 | 890 | | if (_userRootFolder is null) |
| | 891 | | { |
| 21 | 892 | | var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| | 893 | |
|
| 21 | 894 | | _logger.LogDebug("Creating userRootPath at {Path}", userRootPath); |
| 21 | 895 | | Directory.CreateDirectory(userRootPath); |
| | 896 | |
|
| 21 | 897 | | var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder)); |
| 21 | 898 | | UserRootFolder? tmpItem = null; |
| | 899 | | try |
| | 900 | | { |
| 21 | 901 | | tmpItem = GetItemById(newItemId) as UserRootFolder; |
| 21 | 902 | | } |
| 0 | 903 | | catch (Exception ex) |
| | 904 | | { |
| 0 | 905 | | _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId); |
| 0 | 906 | | } |
| | 907 | |
|
| 21 | 908 | | if (tmpItem is null) |
| | 909 | | { |
| 21 | 910 | | _logger.LogDebug("Creating new userRootFolder with DeepCopy"); |
| 21 | 911 | | tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new In |
| 21 | 912 | | .DeepCopy<Folder, UserRootFolder>(); |
| | 913 | | } |
| | 914 | |
|
| | 915 | | // In case program data folder was moved |
| 21 | 916 | | if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal)) |
| | 917 | | { |
| 0 | 918 | | _logger.LogInformation("Resetting user root folder path to {0}", userRootPath); |
| 0 | 919 | | tmpItem.Path = userRootPath; |
| | 920 | | } |
| | 921 | |
|
| 21 | 922 | | _userRootFolder = tmpItem; |
| 21 | 923 | | _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder); |
| | 924 | | } |
| 21 | 925 | | } |
| | 926 | | } |
| | 927 | |
|
| 914 | 928 | | return _userRootFolder; |
| | 929 | | } |
| | 930 | |
|
| | 931 | | /// <inheritdoc /> |
| | 932 | | public BaseItem? FindByPath(string path, bool? isFolder) |
| | 933 | | { |
| | 934 | | // If this returns multiple items it could be tricky figuring out which one is correct. |
| | 935 | | // In most cases, the newest one will be and the others obsolete but not yet cleaned up |
| 0 | 936 | | ArgumentException.ThrowIfNullOrEmpty(path); |
| | 937 | |
|
| 0 | 938 | | var query = new InternalItemsQuery |
| 0 | 939 | | { |
| 0 | 940 | | Path = path, |
| 0 | 941 | | IsFolder = isFolder, |
| 0 | 942 | | OrderBy = [(ItemSortBy.DateCreated, SortOrder.Descending)], |
| 0 | 943 | | Limit = 1, |
| 0 | 944 | | DtoOptions = new DtoOptions(true) |
| 0 | 945 | | }; |
| | 946 | |
|
| 0 | 947 | | return GetItemList(query) |
| 0 | 948 | | .FirstOrDefault(); |
| | 949 | | } |
| | 950 | |
|
| | 951 | | /// <inheritdoc /> |
| | 952 | | public Person? GetPerson(string name) |
| | 953 | | { |
| 1 | 954 | | var path = Person.GetPath(name); |
| 1 | 955 | | var id = GetItemByNameId<Person>(path); |
| 1 | 956 | | if (GetItemById(id) is Person item) |
| | 957 | | { |
| 0 | 958 | | return item; |
| | 959 | | } |
| | 960 | |
|
| 1 | 961 | | return null; |
| | 962 | | } |
| | 963 | |
|
| | 964 | | /// <summary> |
| | 965 | | /// Gets the studio. |
| | 966 | | /// </summary> |
| | 967 | | /// <param name="name">The name.</param> |
| | 968 | | /// <returns>Task{Studio}.</returns> |
| | 969 | | public Studio GetStudio(string name) |
| | 970 | | { |
| 0 | 971 | | return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true)); |
| | 972 | | } |
| | 973 | |
|
| | 974 | | public Guid GetStudioId(string name) |
| | 975 | | { |
| 0 | 976 | | return GetItemByNameId<Studio>(Studio.GetPath(name)); |
| | 977 | | } |
| | 978 | |
|
| | 979 | | public Guid GetGenreId(string name) |
| | 980 | | { |
| 0 | 981 | | return GetItemByNameId<Genre>(Genre.GetPath(name)); |
| | 982 | | } |
| | 983 | |
|
| | 984 | | public Guid GetMusicGenreId(string name) |
| | 985 | | { |
| 0 | 986 | | return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name)); |
| | 987 | | } |
| | 988 | |
|
| | 989 | | /// <summary> |
| | 990 | | /// Gets the genre. |
| | 991 | | /// </summary> |
| | 992 | | /// <param name="name">The name.</param> |
| | 993 | | /// <returns>Task{Genre}.</returns> |
| | 994 | | public Genre GetGenre(string name) |
| | 995 | | { |
| 0 | 996 | | return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true)); |
| | 997 | | } |
| | 998 | |
|
| | 999 | | /// <summary> |
| | 1000 | | /// Gets the music genre. |
| | 1001 | | /// </summary> |
| | 1002 | | /// <param name="name">The name.</param> |
| | 1003 | | /// <returns>Task{MusicGenre}.</returns> |
| | 1004 | | public MusicGenre GetMusicGenre(string name) |
| | 1005 | | { |
| 0 | 1006 | | return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true)); |
| | 1007 | | } |
| | 1008 | |
|
| | 1009 | | /// <summary> |
| | 1010 | | /// Gets the year. |
| | 1011 | | /// </summary> |
| | 1012 | | /// <param name="value">The value.</param> |
| | 1013 | | /// <returns>Task{Year}.</returns> |
| | 1014 | | public Year GetYear(int value) |
| | 1015 | | { |
| 0 | 1016 | | if (value <= 0) |
| | 1017 | | { |
| 0 | 1018 | | throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid."); |
| | 1019 | | } |
| | 1020 | |
|
| 0 | 1021 | | var name = value.ToString(CultureInfo.InvariantCulture); |
| | 1022 | |
|
| 0 | 1023 | | return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true)); |
| | 1024 | | } |
| | 1025 | |
|
| | 1026 | | /// <summary> |
| | 1027 | | /// Gets a Genre. |
| | 1028 | | /// </summary> |
| | 1029 | | /// <param name="name">The name.</param> |
| | 1030 | | /// <returns>Task{Genre}.</returns> |
| | 1031 | | public MusicArtist GetArtist(string name) |
| | 1032 | | { |
| 0 | 1033 | | return GetArtist(name, new DtoOptions(true)); |
| | 1034 | | } |
| | 1035 | |
|
| | 1036 | | public IReadOnlyDictionary<string, MusicArtist[]> GetArtists(IReadOnlyList<string> names) |
| | 1037 | | { |
| 0 | 1038 | | return _itemRepository.FindArtists(names); |
| | 1039 | | } |
| | 1040 | |
|
| | 1041 | | public MusicArtist GetArtist(string name, DtoOptions options) |
| | 1042 | | { |
| 0 | 1043 | | return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options); |
| | 1044 | | } |
| | 1045 | |
|
| | 1046 | | private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options) |
| | 1047 | | where T : BaseItem, new() |
| | 1048 | | { |
| 0 | 1049 | | if (typeof(T) == typeof(MusicArtist)) |
| | 1050 | | { |
| 0 | 1051 | | var existing = GetItemList(new InternalItemsQuery |
| 0 | 1052 | | { |
| 0 | 1053 | | IncludeItemTypes = [BaseItemKind.MusicArtist], |
| 0 | 1054 | | Name = name, |
| 0 | 1055 | | DtoOptions = options |
| 0 | 1056 | | }).Cast<MusicArtist>() |
| 0 | 1057 | | .OrderBy(i => i.IsAccessedByName ? 1 : 0) |
| 0 | 1058 | | .Cast<T>() |
| 0 | 1059 | | .FirstOrDefault(); |
| | 1060 | |
|
| 0 | 1061 | | if (existing is not null) |
| | 1062 | | { |
| 0 | 1063 | | return existing; |
| | 1064 | | } |
| | 1065 | | } |
| | 1066 | |
|
| 0 | 1067 | | var path = getPathFn(name); |
| 0 | 1068 | | var id = GetItemByNameId<T>(path); |
| 0 | 1069 | | var item = GetItemById(id) as T; |
| 0 | 1070 | | if (item is null) |
| | 1071 | | { |
| 0 | 1072 | | var info = Directory.CreateDirectory(path); |
| 0 | 1073 | | item = new T |
| 0 | 1074 | | { |
| 0 | 1075 | | Name = name, |
| 0 | 1076 | | Id = id, |
| 0 | 1077 | | DateCreated = info.CreationTimeUtc, |
| 0 | 1078 | | DateModified = info.LastWriteTimeUtc, |
| 0 | 1079 | | Path = path |
| 0 | 1080 | | }; |
| | 1081 | |
|
| 0 | 1082 | | CreateItem(item, null); |
| | 1083 | | } |
| | 1084 | |
|
| 0 | 1085 | | return item; |
| | 1086 | | } |
| | 1087 | |
|
| | 1088 | | private Guid GetItemByNameId<T>(string path) |
| | 1089 | | where T : BaseItem, new() |
| | 1090 | | { |
| 1 | 1091 | | var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds; |
| 1 | 1092 | | return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId); |
| | 1093 | | } |
| | 1094 | |
|
| | 1095 | | /// <inheritdoc /> |
| | 1096 | | public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken) |
| | 1097 | | { |
| | 1098 | | // Ensure the location is available. |
| 0 | 1099 | | Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath); |
| | 1100 | |
|
| 0 | 1101 | | return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress); |
| | 1102 | | } |
| | 1103 | |
|
| | 1104 | | /// <summary> |
| | 1105 | | /// Reloads the root media folder. |
| | 1106 | | /// </summary> |
| | 1107 | | /// <param name="progress">The progress.</param> |
| | 1108 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | 1109 | | /// <returns>Task.</returns> |
| | 1110 | | public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken) |
| | 1111 | | { |
| | 1112 | | // Just run the scheduled task so that the user can see it |
| 3 | 1113 | | _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>(); |
| | 1114 | |
|
| 3 | 1115 | | return Task.CompletedTask; |
| | 1116 | | } |
| | 1117 | |
|
| | 1118 | | /// <summary> |
| | 1119 | | /// Validates the media library internal. |
| | 1120 | | /// </summary> |
| | 1121 | | /// <param name="progress">The progress.</param> |
| | 1122 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | 1123 | | /// <returns>Task.</returns> |
| | 1124 | | public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken) |
| | 1125 | | { |
| | 1126 | | IsScanRunning = true; |
| | 1127 | | LibraryMonitor.Stop(); |
| | 1128 | |
|
| | 1129 | | try |
| | 1130 | | { |
| | 1131 | | await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false); |
| | 1132 | | } |
| | 1133 | | finally |
| | 1134 | | { |
| | 1135 | | LibraryMonitor.Start(); |
| | 1136 | | IsScanRunning = false; |
| | 1137 | | } |
| | 1138 | | } |
| | 1139 | |
|
| | 1140 | | public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false) |
| | 1141 | | { |
| | 1142 | | RootFolder.Children = null; |
| | 1143 | | await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); |
| | 1144 | |
|
| | 1145 | | // Start by just validating the children of the root, but go no further |
| | 1146 | | await RootFolder.ValidateChildren( |
| | 1147 | | new Progress<double>(), |
| | 1148 | | new MetadataRefreshOptions(new DirectoryService(_fileSystem)), |
| | 1149 | | recursive: false, |
| | 1150 | | allowRemoveRoot: removeRoot, |
| | 1151 | | cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 1152 | |
|
| | 1153 | | var rootFolder = GetUserRootFolder(); |
| | 1154 | | rootFolder.Children = null; |
| | 1155 | |
|
| | 1156 | | await rootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); |
| | 1157 | |
|
| | 1158 | | await rootFolder.ValidateChildren( |
| | 1159 | | new Progress<double>(), |
| | 1160 | | new MetadataRefreshOptions(new DirectoryService(_fileSystem)), |
| | 1161 | | recursive: false, |
| | 1162 | | allowRemoveRoot: removeRoot, |
| | 1163 | | cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 1164 | |
|
| | 1165 | | // Quickly scan CollectionFolders for changes |
| | 1166 | | var toDelete = new List<Guid>(); |
| | 1167 | | foreach (var child in rootFolder.Children!.OfType<Folder>()) |
| | 1168 | | { |
| | 1169 | | // If the user has somehow deleted the collection directory, remove the metadata from the database. |
| | 1170 | | if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path)) |
| | 1171 | | { |
| | 1172 | | toDelete.Add(collectionFolder.Id); |
| | 1173 | | } |
| | 1174 | | else |
| | 1175 | | { |
| | 1176 | | await child.RefreshMetadata(cancellationToken).ConfigureAwait(false); |
| | 1177 | | } |
| | 1178 | | } |
| | 1179 | |
|
| | 1180 | | if (toDelete.Count > 0) |
| | 1181 | | { |
| | 1182 | | _itemRepository.DeleteItem(toDelete.ToArray()); |
| | 1183 | | } |
| | 1184 | | } |
| | 1185 | |
|
| | 1186 | | private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken) |
| | 1187 | | { |
| | 1188 | | _logger.LogInformation("Validating media library"); |
| | 1189 | |
|
| | 1190 | | await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false); |
| | 1191 | |
|
| | 1192 | | var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96)); |
| | 1193 | |
|
| | 1194 | | // Validate the entire media library |
| | 1195 | | await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem |
| | 1196 | |
|
| | 1197 | | progress.Report(96); |
| | 1198 | |
|
| | 1199 | | innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04))); |
| | 1200 | |
|
| | 1201 | | await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false); |
| | 1202 | |
|
| | 1203 | | progress.Report(100); |
| | 1204 | | } |
| | 1205 | |
|
| | 1206 | | /// <summary> |
| | 1207 | | /// Runs the post scan tasks. |
| | 1208 | | /// </summary> |
| | 1209 | | /// <param name="progress">The progress.</param> |
| | 1210 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | 1211 | | /// <returns>Task.</returns> |
| | 1212 | | private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken) |
| | 1213 | | { |
| | 1214 | | var tasks = PostScanTasks.ToList(); |
| | 1215 | |
|
| | 1216 | | var numComplete = 0; |
| | 1217 | | var numTasks = tasks.Count; |
| | 1218 | |
|
| | 1219 | | foreach (var task in tasks) |
| | 1220 | | { |
| | 1221 | | // Prevent access to modified closure |
| | 1222 | | var currentNumComplete = numComplete; |
| | 1223 | |
|
| | 1224 | | var innerProgress = new Progress<double>(pct => |
| | 1225 | | { |
| | 1226 | | double innerPercent = pct; |
| | 1227 | | innerPercent /= 100; |
| | 1228 | | innerPercent += currentNumComplete; |
| | 1229 | |
|
| | 1230 | | innerPercent /= numTasks; |
| | 1231 | | innerPercent *= 100; |
| | 1232 | |
|
| | 1233 | | progress.Report(innerPercent); |
| | 1234 | | }); |
| | 1235 | |
|
| | 1236 | | _logger.LogDebug("Running post-scan task {0}", task.GetType().Name); |
| | 1237 | |
|
| | 1238 | | try |
| | 1239 | | { |
| | 1240 | | await task.Run(innerProgress, cancellationToken).ConfigureAwait(false); |
| | 1241 | | } |
| | 1242 | | catch (OperationCanceledException) |
| | 1243 | | { |
| | 1244 | | _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name); |
| | 1245 | | throw; |
| | 1246 | | } |
| | 1247 | | catch (Exception ex) |
| | 1248 | | { |
| | 1249 | | _logger.LogError(ex, "Error running post-scan task"); |
| | 1250 | | } |
| | 1251 | |
|
| | 1252 | | numComplete++; |
| | 1253 | | double percent = numComplete; |
| | 1254 | | percent /= numTasks; |
| | 1255 | | progress.Report(percent * 100); |
| | 1256 | | } |
| | 1257 | |
|
| | 1258 | | _itemRepository.UpdateInheritedValues(); |
| | 1259 | |
|
| | 1260 | | progress.Report(100); |
| | 1261 | | } |
| | 1262 | |
|
| | 1263 | | /// <summary> |
| | 1264 | | /// Gets the default view. |
| | 1265 | | /// </summary> |
| | 1266 | | /// <returns>IEnumerable{VirtualFolderInfo}.</returns> |
| | 1267 | | public List<VirtualFolderInfo> GetVirtualFolders() |
| | 1268 | | { |
| 23 | 1269 | | return GetVirtualFolders(false); |
| | 1270 | | } |
| | 1271 | |
|
| | 1272 | | public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState) |
| | 1273 | | { |
| 24 | 1274 | | _logger.LogDebug("Getting topLibraryFolders"); |
| 24 | 1275 | | var topLibraryFolders = GetUserRootFolder().Children.ToList(); |
| | 1276 | |
|
| 24 | 1277 | | _logger.LogDebug("Getting refreshQueue"); |
| 24 | 1278 | | var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null; |
| | 1279 | |
|
| 24 | 1280 | | return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath) |
| 24 | 1281 | | .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue)) |
| 24 | 1282 | | .ToList(); |
| | 1283 | | } |
| | 1284 | |
|
| | 1285 | | private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? r |
| | 1286 | | { |
| 1 | 1287 | | var info = new VirtualFolderInfo |
| 1 | 1288 | | { |
| 1 | 1289 | | Name = Path.GetFileName(dir), |
| 1 | 1290 | |
|
| 1 | 1291 | | Locations = _fileSystem.GetFilePaths(dir, false) |
| 1 | 1292 | | .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa |
| 1 | 1293 | | .Select(i => |
| 1 | 1294 | | { |
| 1 | 1295 | | try |
| 1 | 1296 | | { |
| 1 | 1297 | | return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i)); |
| 1 | 1298 | | } |
| 1 | 1299 | | catch (Exception ex) |
| 1 | 1300 | | { |
| 1 | 1301 | | _logger.LogError(ex, "Error resolving shortcut file {File}", i); |
| 1 | 1302 | | return null; |
| 1 | 1303 | | } |
| 1 | 1304 | | }) |
| 1 | 1305 | | .Where(i => i is not null) |
| 1 | 1306 | | .Order() |
| 1 | 1307 | | .ToArray(), |
| 1 | 1308 | |
|
| 1 | 1309 | | CollectionType = GetCollectionType(dir) |
| 1 | 1310 | | }; |
| | 1311 | |
|
| 1 | 1312 | | var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.Ord |
| 1 | 1313 | | if (libraryFolder is not null) |
| | 1314 | | { |
| 1 | 1315 | | var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture); |
| 1 | 1316 | | info.ItemId = libraryFolderId; |
| 1 | 1317 | | if (libraryFolder.HasImage(ImageType.Primary)) |
| | 1318 | | { |
| 0 | 1319 | | info.PrimaryImageItemId = libraryFolderId; |
| | 1320 | | } |
| | 1321 | |
|
| 1 | 1322 | | info.LibraryOptions = GetLibraryOptions(libraryFolder); |
| | 1323 | |
|
| 1 | 1324 | | if (refreshQueue is not null) |
| | 1325 | | { |
| 1 | 1326 | | info.RefreshProgress = libraryFolder.GetRefreshProgress(); |
| | 1327 | |
|
| 1 | 1328 | | info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder. |
| | 1329 | | } |
| | 1330 | | } |
| | 1331 | |
|
| 1 | 1332 | | return info; |
| | 1333 | | } |
| | 1334 | |
|
| | 1335 | | private CollectionTypeOptions? GetCollectionType(string path) |
| | 1336 | | { |
| 1 | 1337 | | var files = _fileSystem.GetFilePaths(path, [".collection"], true, false); |
| 2 | 1338 | | foreach (ReadOnlySpan<char> file in files) |
| | 1339 | | { |
| 0 | 1340 | | if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res)) |
| | 1341 | | { |
| 0 | 1342 | | return res; |
| | 1343 | | } |
| | 1344 | | } |
| | 1345 | |
|
| 1 | 1346 | | return null; |
| 0 | 1347 | | } |
| | 1348 | |
|
| | 1349 | | /// <inheritdoc /> |
| | 1350 | | public BaseItem? GetItemById(Guid id) |
| | 1351 | | { |
| 555 | 1352 | | if (id.IsEmpty()) |
| | 1353 | | { |
| 0 | 1354 | | throw new ArgumentException("Guid can't be empty", nameof(id)); |
| | 1355 | | } |
| | 1356 | |
|
| 555 | 1357 | | if (_cache.TryGet(id, out var item)) |
| | 1358 | | { |
| 452 | 1359 | | return item; |
| | 1360 | | } |
| | 1361 | |
|
| 103 | 1362 | | item = RetrieveItem(id); |
| | 1363 | |
|
| 103 | 1364 | | if (item is not null) |
| | 1365 | | { |
| 0 | 1366 | | RegisterItem(item); |
| | 1367 | | } |
| | 1368 | |
|
| 103 | 1369 | | return item; |
| | 1370 | | } |
| | 1371 | |
|
| | 1372 | | /// <inheritdoc /> |
| | 1373 | | public T? GetItemById<T>(Guid id) |
| | 1374 | | where T : BaseItem |
| | 1375 | | { |
| 23 | 1376 | | var item = GetItemById(id); |
| 23 | 1377 | | if (item is T typedItem) |
| | 1378 | | { |
| 1 | 1379 | | return typedItem; |
| | 1380 | | } |
| | 1381 | |
|
| 22 | 1382 | | return null; |
| | 1383 | | } |
| | 1384 | |
|
| | 1385 | | /// <inheritdoc /> |
| | 1386 | | public T? GetItemById<T>(Guid id, Guid userId) |
| | 1387 | | where T : BaseItem |
| | 1388 | | { |
| 1 | 1389 | | var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId); |
| 1 | 1390 | | return GetItemById<T>(id, user); |
| | 1391 | | } |
| | 1392 | |
|
| | 1393 | | /// <inheritdoc /> |
| | 1394 | | public T? GetItemById<T>(Guid id, User? user) |
| | 1395 | | where T : BaseItem |
| | 1396 | | { |
| 21 | 1397 | | var item = GetItemById<T>(id); |
| 21 | 1398 | | return ItemIsVisible(item, user) ? item : null; |
| | 1399 | | } |
| | 1400 | |
|
| | 1401 | | public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent) |
| | 1402 | | { |
| 119 | 1403 | | if (query.Recursive && !query.ParentId.IsEmpty()) |
| | 1404 | | { |
| 44 | 1405 | | var parent = GetItemById(query.ParentId); |
| 44 | 1406 | | if (parent is not null) |
| | 1407 | | { |
| 44 | 1408 | | SetTopParentIdsOrAncestors(query, [parent]); |
| | 1409 | | } |
| | 1410 | | } |
| | 1411 | |
|
| 119 | 1412 | | if (query.User is not null) |
| | 1413 | | { |
| 1 | 1414 | | AddUserToQuery(query, query.User, allowExternalContent); |
| | 1415 | | } |
| | 1416 | |
|
| 119 | 1417 | | var itemList = _itemRepository.GetItemList(query); |
| 119 | 1418 | | var user = query.User; |
| 119 | 1419 | | if (user is not null) |
| | 1420 | | { |
| 1 | 1421 | | return itemList.Where(i => i.IsVisible(user)).ToList(); |
| | 1422 | | } |
| | 1423 | |
|
| 118 | 1424 | | return itemList; |
| | 1425 | | } |
| | 1426 | |
|
| | 1427 | | public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query) |
| | 1428 | | { |
| 119 | 1429 | | return GetItemList(query, true); |
| | 1430 | | } |
| | 1431 | |
|
| | 1432 | | public int GetCount(InternalItemsQuery query) |
| | 1433 | | { |
| 0 | 1434 | | if (query.Recursive && !query.ParentId.IsEmpty()) |
| | 1435 | | { |
| 0 | 1436 | | var parent = GetItemById(query.ParentId); |
| 0 | 1437 | | if (parent is not null) |
| | 1438 | | { |
| 0 | 1439 | | SetTopParentIdsOrAncestors(query, [parent]); |
| | 1440 | | } |
| | 1441 | | } |
| | 1442 | |
|
| 0 | 1443 | | if (query.User is not null) |
| | 1444 | | { |
| 0 | 1445 | | AddUserToQuery(query, query.User); |
| | 1446 | | } |
| | 1447 | |
|
| 0 | 1448 | | return _itemRepository.GetCount(query); |
| | 1449 | | } |
| | 1450 | |
|
| | 1451 | | public ItemCounts GetItemCounts(InternalItemsQuery query) |
| | 1452 | | { |
| 0 | 1453 | | if (query.Recursive && !query.ParentId.IsEmpty()) |
| | 1454 | | { |
| 0 | 1455 | | var parent = GetItemById(query.ParentId); |
| 0 | 1456 | | if (parent is not null) |
| | 1457 | | { |
| 0 | 1458 | | SetTopParentIdsOrAncestors(query, [parent]); |
| | 1459 | | } |
| | 1460 | | } |
| | 1461 | |
|
| 0 | 1462 | | if (query.User is not null) |
| | 1463 | | { |
| 0 | 1464 | | AddUserToQuery(query, query.User); |
| | 1465 | | } |
| | 1466 | |
|
| 0 | 1467 | | return _itemRepository.GetItemCounts(query); |
| | 1468 | | } |
| | 1469 | |
|
| | 1470 | | public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents) |
| | 1471 | | { |
| 0 | 1472 | | SetTopParentIdsOrAncestors(query, parents); |
| | 1473 | |
|
| 0 | 1474 | | if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0) |
| | 1475 | | { |
| 0 | 1476 | | if (query.User is not null) |
| | 1477 | | { |
| 0 | 1478 | | AddUserToQuery(query, query.User); |
| | 1479 | | } |
| | 1480 | | } |
| | 1481 | |
|
| 0 | 1482 | | return _itemRepository.GetItemList(query); |
| | 1483 | | } |
| | 1484 | |
|
| | 1485 | | public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, Coll |
| | 1486 | | { |
| 0 | 1487 | | SetTopParentIdsOrAncestors(query, parents); |
| | 1488 | |
|
| 0 | 1489 | | if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0) |
| | 1490 | | { |
| 0 | 1491 | | if (query.User is not null) |
| | 1492 | | { |
| 0 | 1493 | | AddUserToQuery(query, query.User); |
| | 1494 | | } |
| | 1495 | | } |
| | 1496 | |
|
| 0 | 1497 | | return _itemRepository.GetLatestItemList(query, collectionType); |
| | 1498 | | } |
| | 1499 | |
|
| | 1500 | | public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents |
| | 1501 | | { |
| 0 | 1502 | | SetTopParentIdsOrAncestors(query, parents); |
| | 1503 | |
|
| 0 | 1504 | | if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0) |
| | 1505 | | { |
| 0 | 1506 | | if (query.User is not null) |
| | 1507 | | { |
| 0 | 1508 | | AddUserToQuery(query, query.User); |
| | 1509 | | } |
| | 1510 | | } |
| | 1511 | |
|
| 0 | 1512 | | return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff); |
| | 1513 | | } |
| | 1514 | |
|
| | 1515 | | public QueryResult<BaseItem> QueryItems(InternalItemsQuery query) |
| | 1516 | | { |
| 0 | 1517 | | if (query.User is not null) |
| | 1518 | | { |
| 0 | 1519 | | AddUserToQuery(query, query.User); |
| | 1520 | | } |
| | 1521 | |
|
| 0 | 1522 | | if (query.EnableTotalRecordCount) |
| | 1523 | | { |
| 0 | 1524 | | return _itemRepository.GetItems(query); |
| | 1525 | | } |
| | 1526 | |
|
| 0 | 1527 | | return new QueryResult<BaseItem>( |
| 0 | 1528 | | query.StartIndex, |
| 0 | 1529 | | null, |
| 0 | 1530 | | _itemRepository.GetItemList(query)); |
| | 1531 | | } |
| | 1532 | |
|
| | 1533 | | public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query) |
| | 1534 | | { |
| 17 | 1535 | | if (query.User is not null) |
| | 1536 | | { |
| 0 | 1537 | | AddUserToQuery(query, query.User); |
| | 1538 | | } |
| | 1539 | |
|
| 17 | 1540 | | return _itemRepository.GetItemIdsList(query); |
| | 1541 | | } |
| | 1542 | |
|
| | 1543 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query) |
| | 1544 | | { |
| 0 | 1545 | | if (query.User is not null) |
| | 1546 | | { |
| 0 | 1547 | | AddUserToQuery(query, query.User); |
| | 1548 | | } |
| | 1549 | |
|
| 0 | 1550 | | SetTopParentOrAncestorIds(query); |
| 0 | 1551 | | return _itemRepository.GetStudios(query); |
| | 1552 | | } |
| | 1553 | |
|
| | 1554 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query) |
| | 1555 | | { |
| 0 | 1556 | | if (query.User is not null) |
| | 1557 | | { |
| 0 | 1558 | | AddUserToQuery(query, query.User); |
| | 1559 | | } |
| | 1560 | |
|
| 0 | 1561 | | SetTopParentOrAncestorIds(query); |
| 0 | 1562 | | return _itemRepository.GetGenres(query); |
| | 1563 | | } |
| | 1564 | |
|
| | 1565 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query) |
| | 1566 | | { |
| 0 | 1567 | | if (query.User is not null) |
| | 1568 | | { |
| 0 | 1569 | | AddUserToQuery(query, query.User); |
| | 1570 | | } |
| | 1571 | |
|
| 0 | 1572 | | SetTopParentOrAncestorIds(query); |
| 0 | 1573 | | return _itemRepository.GetMusicGenres(query); |
| | 1574 | | } |
| | 1575 | |
|
| | 1576 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query) |
| | 1577 | | { |
| 0 | 1578 | | if (query.User is not null) |
| | 1579 | | { |
| 0 | 1580 | | AddUserToQuery(query, query.User); |
| | 1581 | | } |
| | 1582 | |
|
| 0 | 1583 | | SetTopParentOrAncestorIds(query); |
| 0 | 1584 | | return _itemRepository.GetAllArtists(query); |
| | 1585 | | } |
| | 1586 | |
|
| | 1587 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query) |
| | 1588 | | { |
| 0 | 1589 | | if (query.User is not null) |
| | 1590 | | { |
| 0 | 1591 | | AddUserToQuery(query, query.User); |
| | 1592 | | } |
| | 1593 | |
|
| 0 | 1594 | | SetTopParentOrAncestorIds(query); |
| 0 | 1595 | | return _itemRepository.GetArtists(query); |
| | 1596 | | } |
| | 1597 | |
|
| | 1598 | | private void SetTopParentOrAncestorIds(InternalItemsQuery query) |
| | 1599 | | { |
| 0 | 1600 | | var ancestorIds = query.AncestorIds; |
| 0 | 1601 | | int len = ancestorIds.Length; |
| 0 | 1602 | | if (len == 0) |
| | 1603 | | { |
| 0 | 1604 | | return; |
| | 1605 | | } |
| | 1606 | |
|
| 0 | 1607 | | var parents = new BaseItem[len]; |
| 0 | 1608 | | for (int i = 0; i < len; i++) |
| | 1609 | | { |
| 0 | 1610 | | parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id: |
| 0 | 1611 | | if (parents[i] is not (ICollectionFolder or UserView)) |
| | 1612 | | { |
| 0 | 1613 | | return; |
| | 1614 | | } |
| | 1615 | | } |
| | 1616 | |
|
| | 1617 | | // Optimize by querying against top level views |
| 0 | 1618 | | query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray(); |
| 0 | 1619 | | query.AncestorIds = []; |
| | 1620 | |
|
| | 1621 | | // Prevent searching in all libraries due to empty filter |
| 0 | 1622 | | if (query.TopParentIds.Length == 0) |
| | 1623 | | { |
| 0 | 1624 | | query.TopParentIds = [Guid.NewGuid()]; |
| | 1625 | | } |
| 0 | 1626 | | } |
| | 1627 | |
|
| | 1628 | | public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query) |
| | 1629 | | { |
| 0 | 1630 | | if (query.User is not null) |
| | 1631 | | { |
| 0 | 1632 | | AddUserToQuery(query, query.User); |
| | 1633 | | } |
| | 1634 | |
|
| 0 | 1635 | | SetTopParentOrAncestorIds(query); |
| 0 | 1636 | | return _itemRepository.GetAlbumArtists(query); |
| | 1637 | | } |
| | 1638 | |
|
| | 1639 | | public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query) |
| | 1640 | | { |
| 13 | 1641 | | if (query.Recursive && !query.ParentId.IsEmpty()) |
| | 1642 | | { |
| 12 | 1643 | | var parent = GetItemById(query.ParentId); |
| 12 | 1644 | | if (parent is not null) |
| | 1645 | | { |
| 12 | 1646 | | SetTopParentIdsOrAncestors(query, [parent]); |
| | 1647 | | } |
| | 1648 | | } |
| | 1649 | |
|
| 13 | 1650 | | if (query.User is not null) |
| | 1651 | | { |
| 1 | 1652 | | AddUserToQuery(query, query.User); |
| | 1653 | | } |
| | 1654 | |
|
| 13 | 1655 | | if (query.EnableTotalRecordCount) |
| | 1656 | | { |
| 1 | 1657 | | return _itemRepository.GetItems(query); |
| | 1658 | | } |
| | 1659 | |
|
| 12 | 1660 | | return new QueryResult<BaseItem>( |
| 12 | 1661 | | query.StartIndex, |
| 12 | 1662 | | null, |
| 12 | 1663 | | _itemRepository.GetItemList(query)); |
| | 1664 | | } |
| | 1665 | |
|
| | 1666 | | private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents) |
| | 1667 | | { |
| 56 | 1668 | | if (parents.All(i => i is ICollectionFolder || i is UserView)) |
| | 1669 | | { |
| | 1670 | | // Optimize by querying against top level views |
| 12 | 1671 | | query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray(); |
| | 1672 | |
|
| | 1673 | | // Prevent searching in all libraries due to empty filter |
| 12 | 1674 | | if (query.TopParentIds.Length == 0) |
| | 1675 | | { |
| 12 | 1676 | | query.TopParentIds = [Guid.NewGuid()]; |
| | 1677 | | } |
| | 1678 | | } |
| | 1679 | | else |
| | 1680 | | { |
| | 1681 | | // We need to be able to query from any arbitrary ancestor up the tree |
| 44 | 1682 | | query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray(); |
| | 1683 | |
|
| | 1684 | | // Prevent searching in all libraries due to empty filter |
| 44 | 1685 | | if (query.AncestorIds.Length == 0) |
| | 1686 | | { |
| 0 | 1687 | | query.AncestorIds = [Guid.NewGuid()]; |
| | 1688 | | } |
| | 1689 | | } |
| | 1690 | |
|
| 56 | 1691 | | query.Parent = null; |
| 56 | 1692 | | } |
| | 1693 | |
|
| | 1694 | | private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true) |
| | 1695 | | { |
| 2 | 1696 | | if (query.AncestorIds.Length == 0 && |
| 2 | 1697 | | query.ParentId.IsEmpty() && |
| 2 | 1698 | | query.ChannelIds.Count == 0 && |
| 2 | 1699 | | query.TopParentIds.Length == 0 && |
| 2 | 1700 | | string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) && |
| 2 | 1701 | | string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) && |
| 2 | 1702 | | query.ItemIds.Length == 0) |
| | 1703 | | { |
| 1 | 1704 | | var userViews = UserViewManager.GetUserViews(new UserViewQuery |
| 1 | 1705 | | { |
| 1 | 1706 | | User = user, |
| 1 | 1707 | | IncludeHidden = true, |
| 1 | 1708 | | IncludeExternalContent = allowExternalContent |
| 1 | 1709 | | }); |
| | 1710 | |
|
| 1 | 1711 | | query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray(); |
| | 1712 | |
|
| | 1713 | | // Prevent searching in all libraries due to empty filter |
| 1 | 1714 | | if (query.TopParentIds.Length == 0) |
| | 1715 | | { |
| 1 | 1716 | | query.TopParentIds = [Guid.NewGuid()]; |
| | 1717 | | } |
| | 1718 | | } |
| 2 | 1719 | | } |
| | 1720 | |
|
| | 1721 | | private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user) |
| | 1722 | | { |
| 12 | 1723 | | if (item is UserView view) |
| | 1724 | | { |
| 0 | 1725 | | if (view.ViewType == CollectionType.livetv) |
| | 1726 | | { |
| 0 | 1727 | | return [view.Id]; |
| | 1728 | | } |
| | 1729 | |
|
| | 1730 | | // Translate view into folders |
| 0 | 1731 | | if (!view.DisplayParentId.IsEmpty()) |
| | 1732 | | { |
| 0 | 1733 | | var displayParent = GetItemById(view.DisplayParentId); |
| 0 | 1734 | | if (displayParent is not null) |
| | 1735 | | { |
| 0 | 1736 | | return GetTopParentIdsForQuery(displayParent, user); |
| | 1737 | | } |
| | 1738 | |
|
| 0 | 1739 | | return []; |
| | 1740 | | } |
| | 1741 | |
|
| 0 | 1742 | | if (!view.ParentId.IsEmpty()) |
| | 1743 | | { |
| 0 | 1744 | | var displayParent = GetItemById(view.ParentId); |
| 0 | 1745 | | if (displayParent is not null) |
| | 1746 | | { |
| 0 | 1747 | | return GetTopParentIdsForQuery(displayParent, user); |
| | 1748 | | } |
| | 1749 | |
|
| 0 | 1750 | | return []; |
| | 1751 | | } |
| | 1752 | |
|
| | 1753 | | // Handle grouping |
| 0 | 1754 | | if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.V |
| 0 | 1755 | | && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0) |
| | 1756 | | { |
| 0 | 1757 | | return GetUserRootFolder() |
| 0 | 1758 | | .GetChildren(user, true) |
| 0 | 1759 | | .OfType<CollectionFolder>() |
| 0 | 1760 | | .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType) |
| 0 | 1761 | | .Where(i => user.IsFolderGrouped(i.Id)) |
| 0 | 1762 | | .SelectMany(i => GetTopParentIdsForQuery(i, user)); |
| | 1763 | | } |
| | 1764 | |
|
| 0 | 1765 | | return []; |
| | 1766 | | } |
| | 1767 | |
|
| 12 | 1768 | | if (item is CollectionFolder collectionFolder) |
| | 1769 | | { |
| 12 | 1770 | | return collectionFolder.PhysicalFolderIds; |
| | 1771 | | } |
| | 1772 | |
|
| 0 | 1773 | | var topParent = item.GetTopParent(); |
| 0 | 1774 | | if (topParent is not null) |
| | 1775 | | { |
| 0 | 1776 | | return [topParent.Id]; |
| | 1777 | | } |
| | 1778 | |
|
| 0 | 1779 | | return []; |
| | 1780 | | } |
| | 1781 | |
|
| | 1782 | | /// <summary> |
| | 1783 | | /// Gets the intros. |
| | 1784 | | /// </summary> |
| | 1785 | | /// <param name="item">The item.</param> |
| | 1786 | | /// <param name="user">The user.</param> |
| | 1787 | | /// <returns>IEnumerable{System.String}.</returns> |
| | 1788 | | public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user) |
| | 1789 | | { |
| | 1790 | | if (IntroProviders.Length == 0) |
| | 1791 | | { |
| | 1792 | | return []; |
| | 1793 | | } |
| | 1794 | |
|
| | 1795 | | var tasks = IntroProviders |
| | 1796 | | .Select(i => GetIntros(i, item, user)); |
| | 1797 | |
|
| | 1798 | | var items = await Task.WhenAll(tasks).ConfigureAwait(false); |
| | 1799 | |
|
| | 1800 | | return items |
| | 1801 | | .SelectMany(i => i) |
| | 1802 | | .Select(ResolveIntro) |
| | 1803 | | .Where(i => i is not null)!; // null values got filtered out |
| | 1804 | | } |
| | 1805 | |
|
| | 1806 | | /// <summary> |
| | 1807 | | /// Gets the intros. |
| | 1808 | | /// </summary> |
| | 1809 | | /// <param name="provider">The provider.</param> |
| | 1810 | | /// <param name="item">The item.</param> |
| | 1811 | | /// <param name="user">The user.</param> |
| | 1812 | | /// <returns>Task<IEnumerable<IntroInfo>>.</returns> |
| | 1813 | | private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user) |
| | 1814 | | { |
| | 1815 | | try |
| | 1816 | | { |
| | 1817 | | return await provider.GetIntros(item, user).ConfigureAwait(false); |
| | 1818 | | } |
| | 1819 | | catch (Exception ex) |
| | 1820 | | { |
| | 1821 | | _logger.LogError(ex, "Error getting intros"); |
| | 1822 | |
|
| | 1823 | | return []; |
| | 1824 | | } |
| | 1825 | | } |
| | 1826 | |
|
| | 1827 | | /// <summary> |
| | 1828 | | /// Resolves the intro. |
| | 1829 | | /// </summary> |
| | 1830 | | /// <param name="info">The info.</param> |
| | 1831 | | /// <returns>Video.</returns> |
| | 1832 | | private Video? ResolveIntro(IntroInfo info) |
| | 1833 | | { |
| 0 | 1834 | | Video? video = null; |
| | 1835 | |
|
| 0 | 1836 | | if (info.ItemId.HasValue) |
| | 1837 | | { |
| | 1838 | | // Get an existing item by Id |
| 0 | 1839 | | video = GetItemById(info.ItemId.Value) as Video; |
| | 1840 | |
|
| 0 | 1841 | | if (video is null) |
| | 1842 | | { |
| 0 | 1843 | | _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value); |
| | 1844 | | } |
| | 1845 | | } |
| 0 | 1846 | | else if (!string.IsNullOrEmpty(info.Path)) |
| | 1847 | | { |
| | 1848 | | try |
| | 1849 | | { |
| | 1850 | | // Try to resolve the path into a video |
| 0 | 1851 | | video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video; |
| | 1852 | |
|
| 0 | 1853 | | if (video is null) |
| | 1854 | | { |
| 0 | 1855 | | _logger.LogError("Intro resolver returned null for {Path}.", info.Path); |
| | 1856 | | } |
| | 1857 | | else |
| | 1858 | | { |
| | 1859 | | // Pull the saved db item that will include metadata |
| 0 | 1860 | | var dbItem = GetItemById(video.Id) as Video; |
| | 1861 | |
|
| 0 | 1862 | | if (dbItem is not null) |
| | 1863 | | { |
| 0 | 1864 | | video = dbItem; |
| | 1865 | | } |
| | 1866 | | else |
| | 1867 | | { |
| 0 | 1868 | | return null; |
| | 1869 | | } |
| | 1870 | | } |
| 0 | 1871 | | } |
| 0 | 1872 | | catch (Exception ex) |
| | 1873 | | { |
| 0 | 1874 | | _logger.LogError(ex, "Error resolving path {Path}.", info.Path); |
| 0 | 1875 | | } |
| | 1876 | | } |
| | 1877 | | else |
| | 1878 | | { |
| 0 | 1879 | | _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId."); |
| | 1880 | | } |
| | 1881 | |
|
| 0 | 1882 | | return video; |
| 0 | 1883 | | } |
| | 1884 | |
|
| | 1885 | | /// <inheritdoc /> |
| | 1886 | | public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortO |
| | 1887 | | { |
| 1 | 1888 | | IOrderedEnumerable<BaseItem>? orderedItems = null; |
| | 1889 | |
|
| 4 | 1890 | | foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null)) |
| | 1891 | | { |
| 1 | 1892 | | if (orderBy is RandomComparer) |
| | 1893 | | { |
| 0 | 1894 | | var randomItems = items.ToArray(); |
| 0 | 1895 | | Random.Shared.Shuffle(randomItems); |
| 0 | 1896 | | items = randomItems; |
| | 1897 | | // Items are no longer ordered at this point, so set orderedItems back to null |
| 0 | 1898 | | orderedItems = null; |
| | 1899 | | } |
| 1 | 1900 | | else if (orderedItems is null) |
| | 1901 | | { |
| 1 | 1902 | | orderedItems = sortOrder == SortOrder.Descending |
| 1 | 1903 | | ? items.OrderByDescending(i => i, orderBy) |
| 1 | 1904 | | : items.OrderBy(i => i, orderBy); |
| | 1905 | | } |
| | 1906 | | else |
| | 1907 | | { |
| 0 | 1908 | | orderedItems = sortOrder == SortOrder.Descending |
| 0 | 1909 | | ? orderedItems!.ThenByDescending(i => i, orderBy) |
| 0 | 1910 | | : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration |
| | 1911 | | } |
| | 1912 | | } |
| | 1913 | |
|
| 1 | 1914 | | return orderedItems ?? items; |
| | 1915 | | } |
| | 1916 | |
|
| | 1917 | | /// <inheritdoc /> |
| | 1918 | | public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, Sort |
| | 1919 | | { |
| 0 | 1920 | | IOrderedEnumerable<BaseItem>? orderedItems = null; |
| | 1921 | |
|
| 0 | 1922 | | foreach (var (name, sortOrder) in orderBy) |
| | 1923 | | { |
| 0 | 1924 | | var comparer = GetComparer(name, user); |
| 0 | 1925 | | if (comparer is null) |
| | 1926 | | { |
| | 1927 | | continue; |
| | 1928 | | } |
| | 1929 | |
|
| 0 | 1930 | | if (comparer is RandomComparer) |
| | 1931 | | { |
| 0 | 1932 | | var randomItems = items.ToArray(); |
| 0 | 1933 | | Random.Shared.Shuffle(randomItems); |
| 0 | 1934 | | items = randomItems; |
| | 1935 | | // Items are no longer ordered at this point, so set orderedItems back to null |
| 0 | 1936 | | orderedItems = null; |
| | 1937 | | } |
| 0 | 1938 | | else if (orderedItems is null) |
| | 1939 | | { |
| 0 | 1940 | | orderedItems = sortOrder == SortOrder.Descending |
| 0 | 1941 | | ? items.OrderByDescending(i => i, comparer) |
| 0 | 1942 | | : items.OrderBy(i => i, comparer); |
| | 1943 | | } |
| | 1944 | | else |
| | 1945 | | { |
| 0 | 1946 | | orderedItems = sortOrder == SortOrder.Descending |
| 0 | 1947 | | ? orderedItems!.ThenByDescending(i => i, comparer) |
| 0 | 1948 | | : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration |
| | 1949 | | } |
| | 1950 | | } |
| | 1951 | |
|
| 0 | 1952 | | return orderedItems ?? items; |
| | 1953 | | } |
| | 1954 | |
|
| | 1955 | | /// <summary> |
| | 1956 | | /// Gets the comparer. |
| | 1957 | | /// </summary> |
| | 1958 | | /// <param name="name">The name.</param> |
| | 1959 | | /// <param name="user">The user.</param> |
| | 1960 | | /// <returns>IBaseItemComparer.</returns> |
| | 1961 | | private IBaseItemComparer? GetComparer(ItemSortBy name, User? user) |
| | 1962 | | { |
| 1 | 1963 | | var comparer = Comparers.FirstOrDefault(c => name == c.Type); |
| | 1964 | |
|
| | 1965 | | // If it requires a user, create a new one, and assign the user |
| 1 | 1966 | | if (comparer is IUserBaseItemComparer) |
| | 1967 | | { |
| 0 | 1968 | | var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null fo |
| | 1969 | |
|
| 0 | 1970 | | userComparer.User = user; |
| 0 | 1971 | | userComparer.UserManager = _userManager; |
| 0 | 1972 | | userComparer.UserDataManager = _userDataManager; |
| | 1973 | |
|
| 0 | 1974 | | return userComparer; |
| | 1975 | | } |
| | 1976 | |
|
| 1 | 1977 | | return comparer; |
| | 1978 | | } |
| | 1979 | |
|
| | 1980 | | /// <inheritdoc /> |
| | 1981 | | public void CreateItem(BaseItem item, BaseItem? parent) |
| | 1982 | | { |
| 0 | 1983 | | CreateItems([item], parent, CancellationToken.None); |
| 0 | 1984 | | } |
| | 1985 | |
|
| | 1986 | | /// <inheritdoc /> |
| | 1987 | | public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken) |
| | 1988 | | { |
| 2 | 1989 | | _itemRepository.SaveItems(items, cancellationToken); |
| | 1990 | |
|
| 8 | 1991 | | foreach (var item in items) |
| | 1992 | | { |
| 2 | 1993 | | RegisterItem(item); |
| | 1994 | | } |
| | 1995 | |
|
| 2 | 1996 | | if (ItemAdded is not null) |
| | 1997 | | { |
| 8 | 1998 | | foreach (var item in items) |
| | 1999 | | { |
| | 2000 | | // With the live tv guide this just creates too much noise |
| 2 | 2001 | | if (item.SourceType != SourceType.Library) |
| | 2002 | | { |
| | 2003 | | continue; |
| | 2004 | | } |
| | 2005 | |
|
| | 2006 | | try |
| | 2007 | | { |
| 2 | 2008 | | ItemAdded( |
| 2 | 2009 | | this, |
| 2 | 2010 | | new ItemChangeEventArgs |
| 2 | 2011 | | { |
| 2 | 2012 | | Item = item, |
| 2 | 2013 | | Parent = parent ?? item.GetParent() |
| 2 | 2014 | | }); |
| 2 | 2015 | | } |
| 0 | 2016 | | catch (Exception ex) |
| | 2017 | | { |
| 0 | 2018 | | _logger.LogError(ex, "Error in ItemAdded event handler"); |
| 0 | 2019 | | } |
| | 2020 | | } |
| | 2021 | | } |
| 2 | 2022 | | } |
| | 2023 | |
|
| | 2024 | | private bool ImageNeedsRefresh(ItemImageInfo image) |
| | 2025 | | { |
| 0 | 2026 | | if (image.Path is not null && image.IsLocalFile) |
| | 2027 | | { |
| 0 | 2028 | | if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash)) |
| | 2029 | | { |
| 0 | 2030 | | return true; |
| | 2031 | | } |
| | 2032 | |
|
| | 2033 | | try |
| | 2034 | | { |
| 0 | 2035 | | return image.DateModified.Subtract(_fileSystem.GetLastWriteTimeUtc(image.Path)).Duration().TotalSeco |
| | 2036 | | } |
| 0 | 2037 | | catch (Exception ex) |
| | 2038 | | { |
| 0 | 2039 | | _logger.LogError(ex, "Cannot get file info for {0}", image.Path); |
| 0 | 2040 | | return false; |
| | 2041 | | } |
| | 2042 | | } |
| | 2043 | |
|
| 0 | 2044 | | return image.Path is not null && !image.IsLocalFile; |
| 0 | 2045 | | } |
| | 2046 | |
|
| | 2047 | | /// <inheritdoc /> |
| | 2048 | | public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false) |
| | 2049 | | { |
| | 2050 | | ArgumentNullException.ThrowIfNull(item); |
| | 2051 | |
|
| | 2052 | | var outdated = forceUpdate |
| | 2053 | | ? item.ImageInfos.Where(i => i.Path is not null).ToArray() |
| | 2054 | | : item.ImageInfos.Where(ImageNeedsRefresh).ToArray(); |
| | 2055 | | // Skip image processing if current or live tv source |
| | 2056 | | if (outdated.Length == 0 || item.SourceType != SourceType.Library) |
| | 2057 | | { |
| | 2058 | | RegisterItem(item); |
| | 2059 | | return; |
| | 2060 | | } |
| | 2061 | |
|
| | 2062 | | foreach (var img in outdated) |
| | 2063 | | { |
| | 2064 | | var image = img; |
| | 2065 | | if (!img.IsLocalFile) |
| | 2066 | | { |
| | 2067 | | try |
| | 2068 | | { |
| | 2069 | | var index = item.GetImageIndex(img); |
| | 2070 | | image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false); |
| | 2071 | | } |
| | 2072 | | catch (ArgumentException) |
| | 2073 | | { |
| | 2074 | | _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path); |
| | 2075 | | continue; |
| | 2076 | | } |
| | 2077 | | catch (Exception ex) when (ex is InvalidOperationException or IOException) |
| | 2078 | | { |
| | 2079 | | _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path); |
| | 2080 | | continue; |
| | 2081 | | } |
| | 2082 | | catch (HttpRequestException ex) |
| | 2083 | | { |
| | 2084 | | _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", im |
| | 2085 | | continue; |
| | 2086 | | } |
| | 2087 | | } |
| | 2088 | |
|
| | 2089 | | if (!File.Exists(image.Path)) |
| | 2090 | | { |
| | 2091 | | _logger.LogWarning("Image not found at {ImagePath}", image.Path); |
| | 2092 | | continue; |
| | 2093 | | } |
| | 2094 | |
|
| | 2095 | | ImageDimensions size; |
| | 2096 | | try |
| | 2097 | | { |
| | 2098 | | size = _imageProcessor.GetImageDimensions(item, image); |
| | 2099 | | image.Width = size.Width; |
| | 2100 | | image.Height = size.Height; |
| | 2101 | | } |
| | 2102 | | catch (Exception ex) |
| | 2103 | | { |
| | 2104 | | _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path); |
| | 2105 | | size = default; |
| | 2106 | | image.Width = 0; |
| | 2107 | | image.Height = 0; |
| | 2108 | | } |
| | 2109 | |
|
| | 2110 | | try |
| | 2111 | | { |
| | 2112 | | var blurhash = _imageProcessor.GetImageBlurHash(image.Path, size); |
| | 2113 | | image.BlurHash = blurhash; |
| | 2114 | | } |
| | 2115 | | catch (Exception ex) |
| | 2116 | | { |
| | 2117 | | _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path); |
| | 2118 | | image.BlurHash = string.Empty; |
| | 2119 | | } |
| | 2120 | |
|
| | 2121 | | try |
| | 2122 | | { |
| | 2123 | | var modifiedDate = _fileSystem.GetLastWriteTimeUtc(image.Path); |
| | 2124 | | image.DateModified = modifiedDate; |
| | 2125 | | } |
| | 2126 | | catch (Exception ex) |
| | 2127 | | { |
| | 2128 | | _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path); |
| | 2129 | | } |
| | 2130 | | } |
| | 2131 | |
|
| | 2132 | | item.ValidateImages(); |
| | 2133 | |
|
| | 2134 | | _itemRepository.SaveImages(item); |
| | 2135 | |
|
| | 2136 | | RegisterItem(item); |
| | 2137 | | } |
| | 2138 | |
|
| | 2139 | | /// <inheritdoc /> |
| | 2140 | | public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, |
| | 2141 | | { |
| | 2142 | | foreach (var item in items) |
| | 2143 | | { |
| | 2144 | | item.DateLastSaved = DateTime.UtcNow; |
| | 2145 | | await RunMetadataSavers(item, updateReason).ConfigureAwait(false); |
| | 2146 | |
|
| | 2147 | | // Modify again, so saved value is after write time of externally saved metadata |
| | 2148 | | item.DateLastSaved = DateTime.UtcNow; |
| | 2149 | | } |
| | 2150 | |
|
| | 2151 | | _itemRepository.SaveItems(items, cancellationToken); |
| | 2152 | |
|
| | 2153 | | if (ItemUpdated is not null) |
| | 2154 | | { |
| | 2155 | | foreach (var item in items) |
| | 2156 | | { |
| | 2157 | | // With the live tv guide this just creates too much noise |
| | 2158 | | if (item.SourceType != SourceType.Library) |
| | 2159 | | { |
| | 2160 | | continue; |
| | 2161 | | } |
| | 2162 | |
|
| | 2163 | | try |
| | 2164 | | { |
| | 2165 | | ItemUpdated( |
| | 2166 | | this, |
| | 2167 | | new ItemChangeEventArgs |
| | 2168 | | { |
| | 2169 | | Item = item, |
| | 2170 | | Parent = parent, |
| | 2171 | | UpdateReason = updateReason |
| | 2172 | | }); |
| | 2173 | | } |
| | 2174 | | catch (Exception ex) |
| | 2175 | | { |
| | 2176 | | _logger.LogError(ex, "Error in ItemUpdated event handler"); |
| | 2177 | | } |
| | 2178 | | } |
| | 2179 | | } |
| | 2180 | | } |
| | 2181 | |
|
| | 2182 | | /// <inheritdoc /> |
| | 2183 | | public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cance |
| 112 | 2184 | | => UpdateItemsAsync([item], parent, updateReason, cancellationToken); |
| | 2185 | |
|
| | 2186 | | public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason) |
| | 2187 | | { |
| | 2188 | | if (item.IsFileProtocol) |
| | 2189 | | { |
| | 2190 | | await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false); |
| | 2191 | | } |
| | 2192 | |
|
| | 2193 | | await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); |
| | 2194 | | } |
| | 2195 | |
|
| | 2196 | | /// <summary> |
| | 2197 | | /// Reports the item removed. |
| | 2198 | | /// </summary> |
| | 2199 | | /// <param name="item">The item.</param> |
| | 2200 | | /// <param name="parent">The parent item.</param> |
| | 2201 | | public void ReportItemRemoved(BaseItem item, BaseItem parent) |
| | 2202 | | { |
| 0 | 2203 | | if (ItemRemoved is not null) |
| | 2204 | | { |
| | 2205 | | try |
| | 2206 | | { |
| 0 | 2207 | | ItemRemoved( |
| 0 | 2208 | | this, |
| 0 | 2209 | | new ItemChangeEventArgs |
| 0 | 2210 | | { |
| 0 | 2211 | | Item = item, |
| 0 | 2212 | | Parent = parent |
| 0 | 2213 | | }); |
| 0 | 2214 | | } |
| 0 | 2215 | | catch (Exception ex) |
| | 2216 | | { |
| 0 | 2217 | | _logger.LogError(ex, "Error in ItemRemoved event handler"); |
| 0 | 2218 | | } |
| | 2219 | | } |
| 0 | 2220 | | } |
| | 2221 | |
|
| | 2222 | | /// <summary> |
| | 2223 | | /// Retrieves the item. |
| | 2224 | | /// </summary> |
| | 2225 | | /// <param name="id">The id.</param> |
| | 2226 | | /// <returns>BaseItem.</returns> |
| | 2227 | | public BaseItem RetrieveItem(Guid id) |
| | 2228 | | { |
| 103 | 2229 | | return _itemRepository.RetrieveItem(id); |
| | 2230 | | } |
| | 2231 | |
|
| | 2232 | | public List<Folder> GetCollectionFolders(BaseItem item) |
| | 2233 | | { |
| 793 | 2234 | | return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>()); |
| | 2235 | | } |
| | 2236 | |
|
| | 2237 | | public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren) |
| | 2238 | | { |
| 829 | 2239 | | while (item is not null) |
| | 2240 | | { |
| 829 | 2241 | | var parent = item.GetParent(); |
| | 2242 | |
|
| 829 | 2243 | | if (parent is AggregateFolder) |
| | 2244 | | { |
| | 2245 | | break; |
| | 2246 | | } |
| | 2247 | |
|
| 736 | 2248 | | if (parent is null) |
| | 2249 | | { |
| 700 | 2250 | | var owner = item.GetOwner(); |
| | 2251 | |
|
| 700 | 2252 | | if (owner is null) |
| | 2253 | | { |
| | 2254 | | break; |
| | 2255 | | } |
| | 2256 | |
|
| 0 | 2257 | | item = owner; |
| | 2258 | | } |
| | 2259 | | else |
| | 2260 | | { |
| 36 | 2261 | | item = parent; |
| | 2262 | | } |
| | 2263 | | } |
| | 2264 | |
|
| 793 | 2265 | | if (item is null) |
| | 2266 | | { |
| 0 | 2267 | | return new List<Folder>(); |
| | 2268 | | } |
| | 2269 | |
|
| 793 | 2270 | | return GetCollectionFoldersInternal(item, allUserRootChildren); |
| | 2271 | | } |
| | 2272 | |
|
| | 2273 | | private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren) |
| | 2274 | | { |
| 793 | 2275 | | return allUserRootChildren |
| 793 | 2276 | | .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations. |
| 793 | 2277 | | .ToList(); |
| | 2278 | | } |
| | 2279 | |
|
| | 2280 | | public LibraryOptions GetLibraryOptions(BaseItem item) |
| | 2281 | | { |
| 496 | 2282 | | if (item is CollectionFolder collectionFolder) |
| | 2283 | | { |
| 54 | 2284 | | return collectionFolder.GetLibraryOptions(); |
| | 2285 | | } |
| | 2286 | |
|
| | 2287 | | // List.Find is more performant than FirstOrDefault due to enumerator allocation |
| 442 | 2288 | | return GetCollectionFolders(item) |
| 442 | 2289 | | .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2 |
| 442 | 2290 | | ? collectionFolder2.GetLibraryOptions() |
| 442 | 2291 | | : new LibraryOptions(); |
| | 2292 | | } |
| | 2293 | |
|
| | 2294 | | public CollectionType? GetContentType(BaseItem item) |
| | 2295 | | { |
| 59 | 2296 | | var configuredContentType = GetConfiguredContentType(item, false); |
| 59 | 2297 | | if (configuredContentType is not null) |
| | 2298 | | { |
| 0 | 2299 | | return configuredContentType; |
| | 2300 | | } |
| | 2301 | |
|
| 59 | 2302 | | configuredContentType = GetConfiguredContentType(item, true); |
| 59 | 2303 | | if (configuredContentType is not null) |
| | 2304 | | { |
| 0 | 2305 | | return configuredContentType; |
| | 2306 | | } |
| | 2307 | |
|
| 59 | 2308 | | return GetInheritedContentType(item); |
| | 2309 | | } |
| | 2310 | |
|
| | 2311 | | public CollectionType? GetInheritedContentType(BaseItem item) |
| | 2312 | | { |
| 59 | 2313 | | var type = GetTopFolderContentType(item); |
| | 2314 | |
|
| 59 | 2315 | | if (type is not null) |
| | 2316 | | { |
| 0 | 2317 | | return type; |
| | 2318 | | } |
| | 2319 | |
|
| 59 | 2320 | | return item.GetParents() |
| 59 | 2321 | | .Select(GetConfiguredContentType) |
| 59 | 2322 | | .LastOrDefault(i => i is not null); |
| | 2323 | | } |
| | 2324 | |
|
| | 2325 | | public CollectionType? GetConfiguredContentType(BaseItem item) |
| | 2326 | | { |
| 0 | 2327 | | return GetConfiguredContentType(item, false); |
| | 2328 | | } |
| | 2329 | |
|
| | 2330 | | public CollectionType? GetConfiguredContentType(string path) |
| | 2331 | | { |
| 0 | 2332 | | return GetContentTypeOverride(path, false); |
| | 2333 | | } |
| | 2334 | |
|
| | 2335 | | public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath) |
| | 2336 | | { |
| 118 | 2337 | | if (item is ICollectionFolder collectionFolder) |
| | 2338 | | { |
| 0 | 2339 | | return collectionFolder.CollectionType; |
| | 2340 | | } |
| | 2341 | |
|
| 118 | 2342 | | return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath); |
| | 2343 | | } |
| | 2344 | |
|
| | 2345 | | private CollectionType? GetContentTypeOverride(string path, bool inherit) |
| | 2346 | | { |
| 136 | 2347 | | var nameValuePair = _configurationManager.Configuration.ContentTypes |
| 136 | 2348 | | .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path) |
| 136 | 2349 | | || (inherit && !string.IsNullOrEmpty(i.Name) |
| 136 | 2350 | | && _fileSystem.ContainsSubPath(i.Name, path))); |
| 136 | 2351 | | if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType)) |
| | 2352 | | { |
| 0 | 2353 | | return collectionType; |
| | 2354 | | } |
| | 2355 | |
|
| 136 | 2356 | | return null; |
| | 2357 | | } |
| | 2358 | |
|
| | 2359 | | private CollectionType? GetTopFolderContentType(BaseItem item) |
| | 2360 | | { |
| 59 | 2361 | | if (item is null) |
| | 2362 | | { |
| 0 | 2363 | | return null; |
| | 2364 | | } |
| | 2365 | |
|
| 59 | 2366 | | while (!item.ParentId.IsEmpty()) |
| | 2367 | | { |
| 0 | 2368 | | var parent = item.GetParent(); |
| 0 | 2369 | | if (parent is null || parent is AggregateFolder) |
| | 2370 | | { |
| | 2371 | | break; |
| | 2372 | | } |
| | 2373 | |
|
| 0 | 2374 | | item = parent; |
| | 2375 | | } |
| | 2376 | |
|
| 59 | 2377 | | return GetUserRootFolder().Children |
| 59 | 2378 | | .OfType<ICollectionFolder>() |
| 59 | 2379 | | .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations. |
| 59 | 2380 | | .Select(i => i.CollectionType) |
| 59 | 2381 | | .FirstOrDefault(i => i is not null); |
| | 2382 | | } |
| | 2383 | |
|
| | 2384 | | public UserView GetNamedView( |
| | 2385 | | User user, |
| | 2386 | | string name, |
| | 2387 | | CollectionType? viewType, |
| | 2388 | | string sortName) |
| | 2389 | | { |
| 0 | 2390 | | return GetNamedView(user, name, Guid.Empty, viewType, sortName); |
| | 2391 | | } |
| | 2392 | |
|
| | 2393 | | public UserView GetNamedView( |
| | 2394 | | string name, |
| | 2395 | | CollectionType viewType, |
| | 2396 | | string sortName) |
| | 2397 | | { |
| 0 | 2398 | | var path = Path.Combine( |
| 0 | 2399 | | _configurationManager.ApplicationPaths.InternalMetadataPath, |
| 0 | 2400 | | "views", |
| 0 | 2401 | | _fileSystem.GetValidFilename(viewType.ToString())); |
| | 2402 | |
|
| 0 | 2403 | | var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView)); |
| | 2404 | |
|
| 0 | 2405 | | var item = GetItemById(id) as UserView; |
| | 2406 | |
|
| 0 | 2407 | | var refresh = false; |
| | 2408 | |
|
| 0 | 2409 | | if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) |
| | 2410 | | { |
| 0 | 2411 | | var info = Directory.CreateDirectory(path); |
| 0 | 2412 | | item = new UserView |
| 0 | 2413 | | { |
| 0 | 2414 | | Path = path, |
| 0 | 2415 | | Id = id, |
| 0 | 2416 | | DateCreated = info.CreationTimeUtc, |
| 0 | 2417 | | DateModified = info.LastWriteTimeUtc, |
| 0 | 2418 | | Name = name, |
| 0 | 2419 | | ViewType = viewType, |
| 0 | 2420 | | ForcedSortName = sortName |
| 0 | 2421 | | }; |
| | 2422 | |
|
| 0 | 2423 | | CreateItem(item, null); |
| | 2424 | |
|
| 0 | 2425 | | refresh = true; |
| | 2426 | | } |
| | 2427 | |
|
| 0 | 2428 | | if (refresh) |
| | 2429 | | { |
| 0 | 2430 | | item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResu |
| 0 | 2431 | | ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), Ref |
| | 2432 | | } |
| | 2433 | |
|
| 0 | 2434 | | return item; |
| | 2435 | | } |
| | 2436 | |
|
| | 2437 | | public UserView GetNamedView( |
| | 2438 | | User user, |
| | 2439 | | string name, |
| | 2440 | | Guid parentId, |
| | 2441 | | CollectionType? viewType, |
| | 2442 | | string sortName) |
| | 2443 | | { |
| 0 | 2444 | | var parentIdString = parentId.IsEmpty() |
| 0 | 2445 | | ? null |
| 0 | 2446 | | : parentId.ToString("N", CultureInfo.InvariantCulture); |
| 0 | 2447 | | var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdStrin |
| | 2448 | |
|
| 0 | 2449 | | var id = GetNewItemId(idValues, typeof(UserView)); |
| | 2450 | |
|
| 0 | 2451 | | var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N |
| | 2452 | |
|
| 0 | 2453 | | var item = GetItemById(id) as UserView; |
| | 2454 | |
|
| 0 | 2455 | | var isNew = false; |
| | 2456 | |
|
| 0 | 2457 | | if (item is null) |
| | 2458 | | { |
| 0 | 2459 | | var info = Directory.CreateDirectory(path); |
| 0 | 2460 | | item = new UserView |
| 0 | 2461 | | { |
| 0 | 2462 | | Path = path, |
| 0 | 2463 | | Id = id, |
| 0 | 2464 | | DateCreated = info.CreationTimeUtc, |
| 0 | 2465 | | DateModified = info.LastWriteTimeUtc, |
| 0 | 2466 | | Name = name, |
| 0 | 2467 | | ViewType = viewType, |
| 0 | 2468 | | ForcedSortName = sortName, |
| 0 | 2469 | | UserId = user.Id, |
| 0 | 2470 | | DisplayParentId = parentId |
| 0 | 2471 | | }; |
| | 2472 | |
|
| 0 | 2473 | | CreateItem(item, null); |
| | 2474 | |
|
| 0 | 2475 | | isNew = true; |
| | 2476 | | } |
| | 2477 | |
|
| 0 | 2478 | | var lastRefreshedUtc = item.DateLastRefreshed; |
| 0 | 2479 | | var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval; |
| | 2480 | |
|
| 0 | 2481 | | if (!refresh && !item.DisplayParentId.IsEmpty()) |
| | 2482 | | { |
| 0 | 2483 | | var displayParent = GetItemById(item.DisplayParentId); |
| 0 | 2484 | | refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc; |
| | 2485 | | } |
| | 2486 | |
|
| 0 | 2487 | | if (refresh) |
| | 2488 | | { |
| 0 | 2489 | | ProviderManager.QueueRefresh( |
| 0 | 2490 | | item.Id, |
| 0 | 2491 | | new MetadataRefreshOptions(new DirectoryService(_fileSystem)) |
| 0 | 2492 | | { |
| 0 | 2493 | | // Need to force save to increment DateLastSaved |
| 0 | 2494 | | ForceSave = true |
| 0 | 2495 | | }, |
| 0 | 2496 | | RefreshPriority.Normal); |
| | 2497 | | } |
| | 2498 | |
|
| 0 | 2499 | | return item; |
| | 2500 | | } |
| | 2501 | |
|
| | 2502 | | public UserView GetShadowView( |
| | 2503 | | BaseItem parent, |
| | 2504 | | CollectionType? viewType, |
| | 2505 | | string sortName) |
| | 2506 | | { |
| 0 | 2507 | | ArgumentNullException.ThrowIfNull(parent); |
| | 2508 | |
|
| 0 | 2509 | | var name = parent.Name; |
| 0 | 2510 | | var parentId = parent.Id; |
| | 2511 | |
|
| 0 | 2512 | | var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty); |
| | 2513 | |
|
| 0 | 2514 | | var id = GetNewItemId(idValues, typeof(UserView)); |
| | 2515 | |
|
| 0 | 2516 | | var path = parent.Path; |
| | 2517 | |
|
| 0 | 2518 | | var item = GetItemById(id) as UserView; |
| | 2519 | |
|
| 0 | 2520 | | var isNew = false; |
| | 2521 | |
|
| 0 | 2522 | | if (item is null) |
| | 2523 | | { |
| 0 | 2524 | | var info = Directory.CreateDirectory(path); |
| 0 | 2525 | | item = new UserView |
| 0 | 2526 | | { |
| 0 | 2527 | | Path = path, |
| 0 | 2528 | | Id = id, |
| 0 | 2529 | | DateCreated = info.CreationTimeUtc, |
| 0 | 2530 | | DateModified = info.LastWriteTimeUtc, |
| 0 | 2531 | | Name = name, |
| 0 | 2532 | | ViewType = viewType, |
| 0 | 2533 | | ForcedSortName = sortName, |
| 0 | 2534 | | DisplayParentId = parentId |
| 0 | 2535 | | }; |
| | 2536 | |
|
| 0 | 2537 | | CreateItem(item, null); |
| | 2538 | |
|
| 0 | 2539 | | isNew = true; |
| | 2540 | | } |
| | 2541 | |
|
| 0 | 2542 | | var lastRefreshedUtc = item.DateLastRefreshed; |
| 0 | 2543 | | var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval; |
| | 2544 | |
|
| 0 | 2545 | | if (!refresh && !item.DisplayParentId.IsEmpty()) |
| | 2546 | | { |
| 0 | 2547 | | var displayParent = GetItemById(item.DisplayParentId); |
| 0 | 2548 | | refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc; |
| | 2549 | | } |
| | 2550 | |
|
| 0 | 2551 | | if (refresh) |
| | 2552 | | { |
| 0 | 2553 | | ProviderManager.QueueRefresh( |
| 0 | 2554 | | item.Id, |
| 0 | 2555 | | new MetadataRefreshOptions(new DirectoryService(_fileSystem)) |
| 0 | 2556 | | { |
| 0 | 2557 | | // Need to force save to increment DateLastSaved |
| 0 | 2558 | | ForceSave = true |
| 0 | 2559 | | }, |
| 0 | 2560 | | RefreshPriority.Normal); |
| | 2561 | | } |
| | 2562 | |
|
| 0 | 2563 | | return item; |
| | 2564 | | } |
| | 2565 | |
|
| | 2566 | | public UserView GetNamedView( |
| | 2567 | | string name, |
| | 2568 | | Guid parentId, |
| | 2569 | | CollectionType? viewType, |
| | 2570 | | string sortName, |
| | 2571 | | string uniqueId) |
| | 2572 | | { |
| 0 | 2573 | | ArgumentException.ThrowIfNullOrEmpty(name); |
| | 2574 | |
|
| 0 | 2575 | | var parentIdString = parentId.IsEmpty() |
| 0 | 2576 | | ? null |
| 0 | 2577 | | : parentId.ToString("N", CultureInfo.InvariantCulture); |
| 0 | 2578 | | var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.E |
| 0 | 2579 | | if (!string.IsNullOrEmpty(uniqueId)) |
| | 2580 | | { |
| 0 | 2581 | | idValues += uniqueId; |
| | 2582 | | } |
| | 2583 | |
|
| 0 | 2584 | | var id = GetNewItemId(idValues, typeof(UserView)); |
| | 2585 | |
|
| 0 | 2586 | | var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N |
| | 2587 | |
|
| 0 | 2588 | | var item = GetItemById(id) as UserView; |
| | 2589 | |
|
| 0 | 2590 | | var isNew = false; |
| | 2591 | |
|
| 0 | 2592 | | if (item is null) |
| | 2593 | | { |
| 0 | 2594 | | var info = Directory.CreateDirectory(path); |
| 0 | 2595 | | item = new UserView |
| 0 | 2596 | | { |
| 0 | 2597 | | Path = path, |
| 0 | 2598 | | Id = id, |
| 0 | 2599 | | DateCreated = info.CreationTimeUtc, |
| 0 | 2600 | | DateModified = info.LastWriteTimeUtc, |
| 0 | 2601 | | Name = name, |
| 0 | 2602 | | ViewType = viewType, |
| 0 | 2603 | | ForcedSortName = sortName, |
| 0 | 2604 | | DisplayParentId = parentId |
| 0 | 2605 | | }; |
| | 2606 | |
|
| 0 | 2607 | | CreateItem(item, null); |
| | 2608 | |
|
| 0 | 2609 | | isNew = true; |
| | 2610 | | } |
| | 2611 | |
|
| 0 | 2612 | | if (viewType != item.ViewType) |
| | 2613 | | { |
| 0 | 2614 | | item.ViewType = viewType; |
| 0 | 2615 | | item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult |
| | 2616 | | } |
| | 2617 | |
|
| 0 | 2618 | | var lastRefreshedUtc = item.DateLastRefreshed; |
| 0 | 2619 | | var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval; |
| | 2620 | |
|
| 0 | 2621 | | if (!refresh && !item.DisplayParentId.IsEmpty()) |
| | 2622 | | { |
| 0 | 2623 | | var displayParent = GetItemById(item.DisplayParentId); |
| 0 | 2624 | | refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc; |
| | 2625 | | } |
| | 2626 | |
|
| 0 | 2627 | | if (refresh) |
| | 2628 | | { |
| 0 | 2629 | | ProviderManager.QueueRefresh( |
| 0 | 2630 | | item.Id, |
| 0 | 2631 | | new MetadataRefreshOptions(new DirectoryService(_fileSystem)) |
| 0 | 2632 | | { |
| 0 | 2633 | | // Need to force save to increment DateLastSaved |
| 0 | 2634 | | ForceSave = true |
| 0 | 2635 | | }, |
| 0 | 2636 | | RefreshPriority.Normal); |
| | 2637 | | } |
| | 2638 | |
|
| 0 | 2639 | | return item; |
| | 2640 | | } |
| | 2641 | |
|
| | 2642 | | public BaseItem GetParentItem(Guid? parentId, Guid? userId) |
| | 2643 | | { |
| 3 | 2644 | | if (parentId.HasValue) |
| | 2645 | | { |
| 0 | 2646 | | return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}" |
| | 2647 | | } |
| | 2648 | |
|
| 3 | 2649 | | if (!userId.IsNullOrEmpty()) |
| | 2650 | | { |
| 3 | 2651 | | return GetUserRootFolder(); |
| | 2652 | | } |
| | 2653 | |
|
| 0 | 2654 | | return RootFolder; |
| | 2655 | | } |
| | 2656 | |
|
| | 2657 | | /// <inheritdoc /> |
| | 2658 | | public void QueueLibraryScan() |
| | 2659 | | { |
| 0 | 2660 | | _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>(); |
| 0 | 2661 | | } |
| | 2662 | |
|
| | 2663 | | /// <inheritdoc /> |
| | 2664 | | public int? GetSeasonNumberFromPath(string path, Guid? parentId) |
| | 2665 | | { |
| 0 | 2666 | | var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null; |
| 0 | 2667 | | return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber; |
| | 2668 | | } |
| | 2669 | |
|
| | 2670 | | /// <inheritdoc /> |
| | 2671 | | public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh) |
| | 2672 | | { |
| 0 | 2673 | | var series = episode.Series; |
| 0 | 2674 | | bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparis |
| 0 | 2675 | | if (!isAbsoluteNaming.Value) |
| | 2676 | | { |
| | 2677 | | // In other words, no filter applied |
| 0 | 2678 | | isAbsoluteNaming = null; |
| | 2679 | | } |
| | 2680 | |
|
| 0 | 2681 | | var resolver = new EpisodeResolver(_namingOptions); |
| | 2682 | |
|
| 0 | 2683 | | var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd; |
| | 2684 | |
|
| 0 | 2685 | | EpisodeInfo? episodeInfo = null; |
| 0 | 2686 | | if (episode.IsFileProtocol) |
| | 2687 | | { |
| 0 | 2688 | | episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming); |
| | 2689 | | // Resolve from parent folder if it's not the Season folder |
| 0 | 2690 | | var parent = episode.GetParent(); |
| 0 | 2691 | | if (episodeInfo is null && parent.GetType() == typeof(Folder)) |
| | 2692 | | { |
| 0 | 2693 | | episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming); |
| 0 | 2694 | | if (episodeInfo is not null) |
| | 2695 | | { |
| | 2696 | | // add the container |
| 0 | 2697 | | episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.'); |
| | 2698 | | } |
| | 2699 | | } |
| | 2700 | | } |
| | 2701 | |
|
| 0 | 2702 | | var changed = false; |
| 0 | 2703 | | if (episodeInfo is null) |
| | 2704 | | { |
| 0 | 2705 | | return changed; |
| | 2706 | | } |
| | 2707 | |
|
| 0 | 2708 | | if (episodeInfo.IsByDate) |
| | 2709 | | { |
| 0 | 2710 | | if (episode.IndexNumber.HasValue) |
| | 2711 | | { |
| 0 | 2712 | | episode.IndexNumber = null; |
| 0 | 2713 | | changed = true; |
| | 2714 | | } |
| | 2715 | |
|
| 0 | 2716 | | if (episode.IndexNumberEnd.HasValue) |
| | 2717 | | { |
| 0 | 2718 | | episode.IndexNumberEnd = null; |
| 0 | 2719 | | changed = true; |
| | 2720 | | } |
| | 2721 | |
|
| 0 | 2722 | | if (!episode.PremiereDate.HasValue) |
| | 2723 | | { |
| 0 | 2724 | | if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue) |
| | 2725 | | { |
| 0 | 2726 | | episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo |
| | 2727 | | } |
| | 2728 | |
|
| 0 | 2729 | | if (episode.PremiereDate.HasValue) |
| | 2730 | | { |
| 0 | 2731 | | changed = true; |
| | 2732 | | } |
| | 2733 | | } |
| | 2734 | |
|
| 0 | 2735 | | if (!episode.ProductionYear.HasValue) |
| | 2736 | | { |
| 0 | 2737 | | episode.ProductionYear = episodeInfo.Year; |
| | 2738 | |
|
| 0 | 2739 | | if (episode.ProductionYear.HasValue) |
| | 2740 | | { |
| 0 | 2741 | | changed = true; |
| | 2742 | | } |
| | 2743 | | } |
| | 2744 | | } |
| | 2745 | | else |
| | 2746 | | { |
| 0 | 2747 | | if (!episode.IndexNumber.HasValue || forceRefresh) |
| | 2748 | | { |
| 0 | 2749 | | if (episode.IndexNumber != episodeInfo.EpisodeNumber) |
| | 2750 | | { |
| 0 | 2751 | | changed = true; |
| | 2752 | | } |
| | 2753 | |
|
| 0 | 2754 | | episode.IndexNumber = episodeInfo.EpisodeNumber; |
| | 2755 | | } |
| | 2756 | |
|
| 0 | 2757 | | if (!episode.IndexNumberEnd.HasValue || forceRefresh) |
| | 2758 | | { |
| 0 | 2759 | | if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber) |
| | 2760 | | { |
| 0 | 2761 | | changed = true; |
| | 2762 | | } |
| | 2763 | |
|
| 0 | 2764 | | episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber; |
| | 2765 | | } |
| | 2766 | |
|
| 0 | 2767 | | if (!episode.ParentIndexNumber.HasValue || forceRefresh) |
| | 2768 | | { |
| 0 | 2769 | | if (episode.ParentIndexNumber != episodeInfo.SeasonNumber) |
| | 2770 | | { |
| 0 | 2771 | | changed = true; |
| | 2772 | | } |
| | 2773 | |
|
| 0 | 2774 | | episode.ParentIndexNumber = episodeInfo.SeasonNumber; |
| | 2775 | | } |
| | 2776 | | } |
| | 2777 | |
|
| 0 | 2778 | | if (!episode.ParentIndexNumber.HasValue) |
| | 2779 | | { |
| 0 | 2780 | | var season = episode.Season; |
| | 2781 | |
|
| 0 | 2782 | | if (season is not null) |
| | 2783 | | { |
| 0 | 2784 | | episode.ParentIndexNumber = season.IndexNumber; |
| | 2785 | | } |
| | 2786 | |
|
| 0 | 2787 | | if (episode.ParentIndexNumber.HasValue) |
| | 2788 | | { |
| 0 | 2789 | | changed = true; |
| | 2790 | | } |
| | 2791 | | } |
| | 2792 | |
|
| 0 | 2793 | | return changed; |
| | 2794 | | } |
| | 2795 | |
|
| | 2796 | | public ItemLookupInfo ParseName(string name) |
| | 2797 | | { |
| 0 | 2798 | | var namingOptions = _namingOptions; |
| 0 | 2799 | | var result = VideoResolver.CleanDateTime(name, namingOptions); |
| | 2800 | |
|
| 0 | 2801 | | return new ItemLookupInfo |
| 0 | 2802 | | { |
| 0 | 2803 | | Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name |
| 0 | 2804 | | Year = result.Year |
| 0 | 2805 | | }; |
| | 2806 | | } |
| | 2807 | |
|
| | 2808 | | public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, ID |
| | 2809 | | { |
| | 2810 | | // Apply .ignore rules |
| | 2811 | | var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList(); |
| | 2812 | | var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.Co |
| | 2813 | | if (ownerVideoInfo is null) |
| | 2814 | | { |
| | 2815 | | yield break; |
| | 2816 | | } |
| | 2817 | |
|
| | 2818 | | var count = filtered.Count; |
| | 2819 | | for (var i = 0; i < count; i++) |
| | 2820 | | { |
| | 2821 | | var current = filtered[i]; |
| | 2822 | | if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name)) |
| | 2823 | | { |
| | 2824 | | var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false); |
| | 2825 | | var filesInSubFolderList = filesInSubFolder.ToList(); |
| | 2826 | |
|
| | 2827 | | bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1; |
| | 2828 | |
|
| | 2829 | | foreach (var file in filesInSubFolderList) |
| | 2830 | | { |
| | 2831 | | if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType)) |
| | 2832 | | { |
| | 2833 | | continue; |
| | 2834 | | } |
| | 2835 | |
|
| | 2836 | | var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder); |
| | 2837 | | if (extra is not null) |
| | 2838 | | { |
| | 2839 | | yield return extra; |
| | 2840 | | } |
| | 2841 | | } |
| | 2842 | | } |
| | 2843 | | else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo |
| | 2844 | | { |
| | 2845 | | var extra = GetExtra(current, extraType.Value, false); |
| | 2846 | | if (extra is not null) |
| | 2847 | | { |
| | 2848 | | yield return extra; |
| | 2849 | | } |
| | 2850 | | } |
| | 2851 | | } |
| | 2852 | |
|
| | 2853 | | BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder) |
| | 2854 | | { |
| | 2855 | | var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetReso |
| | 2856 | | if (extra is not Video && extra is not Audio) |
| | 2857 | | { |
| | 2858 | | return null; |
| | 2859 | | } |
| | 2860 | |
|
| | 2861 | | // Try to retrieve it from the db. If we don't find it, use the resolved version |
| | 2862 | | var itemById = GetItemById(extra.Id); |
| | 2863 | | if (itemById is not null) |
| | 2864 | | { |
| | 2865 | | extra = itemById; |
| | 2866 | | } |
| | 2867 | |
|
| | 2868 | | // Only update extra type if it is more specific then the currently known extra type |
| | 2869 | | if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown) |
| | 2870 | | { |
| | 2871 | | extra.ExtraType = extraType; |
| | 2872 | | } |
| | 2873 | |
|
| | 2874 | | extra.ParentId = Guid.Empty; |
| | 2875 | | extra.OwnerId = owner.Id; |
| | 2876 | | extra.IsInMixedFolder = isInMixedFolder; |
| | 2877 | | return extra; |
| | 2878 | | } |
| | 2879 | | } |
| | 2880 | |
|
| | 2881 | | public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem) |
| | 2882 | | { |
| 12 | 2883 | | foreach (var map in _configurationManager.Configuration.PathSubstitutions) |
| | 2884 | | { |
| 0 | 2885 | | if (path.TryReplaceSubPath(map.From, map.To, out var newPath)) |
| | 2886 | | { |
| 0 | 2887 | | return newPath; |
| | 2888 | | } |
| | 2889 | | } |
| | 2890 | |
|
| 6 | 2891 | | return path; |
| | 2892 | | } |
| | 2893 | |
|
| | 2894 | | public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query) |
| | 2895 | | { |
| 0 | 2896 | | return _peopleRepository.GetPeople(query); |
| | 2897 | | } |
| | 2898 | |
|
| | 2899 | | public IReadOnlyList<PersonInfo> GetPeople(BaseItem item) |
| | 2900 | | { |
| 6 | 2901 | | if (item.SupportsPeople) |
| | 2902 | | { |
| 0 | 2903 | | var people = GetPeople(new InternalPeopleQuery |
| 0 | 2904 | | { |
| 0 | 2905 | | ItemId = item.Id |
| 0 | 2906 | | }); |
| | 2907 | |
|
| 0 | 2908 | | if (people.Count > 0) |
| | 2909 | | { |
| 0 | 2910 | | return people; |
| | 2911 | | } |
| | 2912 | | } |
| | 2913 | |
|
| 6 | 2914 | | return []; |
| | 2915 | | } |
| | 2916 | |
|
| | 2917 | | public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query) |
| | 2918 | | { |
| 0 | 2919 | | return _peopleRepository.GetPeopleNames(query) |
| 0 | 2920 | | .Select(i => |
| 0 | 2921 | | { |
| 0 | 2922 | | try |
| 0 | 2923 | | { |
| 0 | 2924 | | return GetPerson(i); |
| 0 | 2925 | | } |
| 0 | 2926 | | catch (Exception ex) |
| 0 | 2927 | | { |
| 0 | 2928 | | _logger.LogError(ex, "Error getting person"); |
| 0 | 2929 | | return null; |
| 0 | 2930 | | } |
| 0 | 2931 | | }) |
| 0 | 2932 | | .Where(i => i is not null) |
| 0 | 2933 | | .Where(i => query.User is null || i!.IsVisible(query.User)) |
| 0 | 2934 | | .ToList()!; // null values are filtered out |
| | 2935 | | } |
| | 2936 | |
|
| | 2937 | | public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query) |
| | 2938 | | { |
| 0 | 2939 | | return _peopleRepository.GetPeopleNames(query); |
| | 2940 | | } |
| | 2941 | |
|
| | 2942 | | public void UpdatePeople(BaseItem item, List<PersonInfo> people) |
| | 2943 | | { |
| 0 | 2944 | | UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult(); |
| 0 | 2945 | | } |
| | 2946 | |
|
| | 2947 | | /// <inheritdoc /> |
| | 2948 | | public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellat |
| | 2949 | | { |
| | 2950 | | if (!item.SupportsPeople) |
| | 2951 | | { |
| | 2952 | | return; |
| | 2953 | | } |
| | 2954 | |
|
| | 2955 | | if (people is not null) |
| | 2956 | | { |
| | 2957 | | people = people.Where(e => e is not null).ToArray(); |
| | 2958 | | _peopleRepository.UpdatePeople(item.Id, people); |
| | 2959 | | await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false); |
| | 2960 | | } |
| | 2961 | | } |
| | 2962 | |
|
| | 2963 | | public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool re |
| | 2964 | | { |
| | 2965 | | foreach (var url in image.Path.Split('|')) |
| | 2966 | | { |
| | 2967 | | try |
| | 2968 | | { |
| | 2969 | | _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url); |
| | 2970 | |
|
| | 2971 | | await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).Configure |
| | 2972 | |
|
| | 2973 | | await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwai |
| | 2974 | |
|
| | 2975 | | return item.GetImageInfo(image.Type, imageIndex); |
| | 2976 | | } |
| | 2977 | | catch (HttpRequestException ex) |
| | 2978 | | { |
| | 2979 | | if (ex.StatusCode.HasValue |
| | 2980 | | && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forb |
| | 2981 | | { |
| | 2982 | | _logger.LogDebug(ex, "Error downloading image {Url}", url); |
| | 2983 | | continue; |
| | 2984 | | } |
| | 2985 | |
|
| | 2986 | | throw; |
| | 2987 | | } |
| | 2988 | | } |
| | 2989 | |
|
| | 2990 | | if (removeOnFailure) |
| | 2991 | | { |
| | 2992 | | // Remove this image to prevent it from retrying over and over |
| | 2993 | | item.RemoveImage(image); |
| | 2994 | | await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(fa |
| | 2995 | | } |
| | 2996 | |
|
| | 2997 | | throw new InvalidOperationException("Unable to convert any images to local"); |
| | 2998 | | } |
| | 2999 | |
|
| | 3000 | | public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, b |
| | 3001 | | { |
| | 3002 | | if (string.IsNullOrWhiteSpace(name)) |
| | 3003 | | { |
| | 3004 | | throw new ArgumentNullException(nameof(name)); |
| | 3005 | | } |
| | 3006 | |
|
| | 3007 | | name = _fileSystem.GetValidFilename(name.Trim()); |
| | 3008 | |
|
| | 3009 | | var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| | 3010 | |
|
| | 3011 | | var existingNameCount = 1; // first numbered name will be 2 |
| | 3012 | | var virtualFolderPath = Path.Combine(rootFolderPath, name); |
| | 3013 | | var originalName = name; |
| | 3014 | | while (Directory.Exists(virtualFolderPath)) |
| | 3015 | | { |
| | 3016 | | existingNameCount++; |
| | 3017 | | name = originalName + existingNameCount; |
| | 3018 | | virtualFolderPath = Path.Combine(rootFolderPath, name); |
| | 3019 | | } |
| | 3020 | |
|
| | 3021 | | var mediaPathInfos = options.PathInfos; |
| | 3022 | | if (mediaPathInfos is not null) |
| | 3023 | | { |
| | 3024 | | var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path)); |
| | 3025 | | if (invalidpath is not null) |
| | 3026 | | { |
| | 3027 | | throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + "."); |
| | 3028 | | } |
| | 3029 | | } |
| | 3030 | |
|
| | 3031 | | LibraryMonitor.Stop(); |
| | 3032 | |
|
| | 3033 | | try |
| | 3034 | | { |
| | 3035 | | Directory.CreateDirectory(virtualFolderPath); |
| | 3036 | |
|
| | 3037 | | if (collectionType is not null) |
| | 3038 | | { |
| | 3039 | | var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collect |
| | 3040 | |
|
| | 3041 | | FileHelper.CreateEmpty(path); |
| | 3042 | | } |
| | 3043 | |
|
| | 3044 | | CollectionFolder.SaveLibraryOptions(virtualFolderPath, options); |
| | 3045 | |
|
| | 3046 | | if (mediaPathInfos is not null) |
| | 3047 | | { |
| | 3048 | | foreach (var path in mediaPathInfos) |
| | 3049 | | { |
| | 3050 | | AddMediaPathInternal(name, path, false); |
| | 3051 | | } |
| | 3052 | | } |
| | 3053 | | } |
| | 3054 | | finally |
| | 3055 | | { |
| | 3056 | | await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false); |
| | 3057 | |
|
| | 3058 | | if (refreshLibrary) |
| | 3059 | | { |
| | 3060 | | StartScanInBackground(); |
| | 3061 | | } |
| | 3062 | | else |
| | 3063 | | { |
| | 3064 | | // Need to add a delay here or directory watchers may still pick up the changes |
| | 3065 | | await Task.Delay(1000).ConfigureAwait(false); |
| | 3066 | | LibraryMonitor.Start(); |
| | 3067 | | } |
| | 3068 | | } |
| | 3069 | | } |
| | 3070 | |
|
| | 3071 | | private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken) |
| | 3072 | | { |
| | 3073 | | foreach (var person in people) |
| | 3074 | | { |
| | 3075 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 3076 | |
|
| | 3077 | | var itemUpdateType = ItemUpdateType.MetadataDownload; |
| | 3078 | | var saveEntity = false; |
| | 3079 | | var createEntity = false; |
| | 3080 | | var personEntity = GetPerson(person.Name); |
| | 3081 | |
|
| | 3082 | | if (personEntity is null) |
| | 3083 | | { |
| | 3084 | | try |
| | 3085 | | { |
| | 3086 | | var path = Person.GetPath(person.Name); |
| | 3087 | | var info = Directory.CreateDirectory(path); |
| | 3088 | | personEntity = new Person() |
| | 3089 | | { |
| | 3090 | | Name = person.Name, |
| | 3091 | | Id = GetItemByNameId<Person>(path), |
| | 3092 | | DateCreated = info.CreationTimeUtc, |
| | 3093 | | DateModified = info.LastWriteTimeUtc, |
| | 3094 | | Path = path |
| | 3095 | | }; |
| | 3096 | |
|
| | 3097 | | personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey(); |
| | 3098 | | saveEntity = true; |
| | 3099 | | createEntity = true; |
| | 3100 | | } |
| | 3101 | | catch (Exception ex) |
| | 3102 | | { |
| | 3103 | | _logger.LogWarning(ex, "Failed to create person {Name}", person.Name); |
| | 3104 | | continue; |
| | 3105 | | } |
| | 3106 | | } |
| | 3107 | |
|
| | 3108 | | foreach (var id in person.ProviderIds) |
| | 3109 | | { |
| | 3110 | | if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase) |
| | 3111 | | { |
| | 3112 | | personEntity.SetProviderId(id.Key, id.Value); |
| | 3113 | | saveEntity = true; |
| | 3114 | | } |
| | 3115 | | } |
| | 3116 | |
|
| | 3117 | | if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) |
| | 3118 | | { |
| | 3119 | | personEntity.SetImage( |
| | 3120 | | new ItemImageInfo |
| | 3121 | | { |
| | 3122 | | Path = person.ImageUrl, |
| | 3123 | | Type = ImageType.Primary |
| | 3124 | | }, |
| | 3125 | | 0); |
| | 3126 | |
|
| | 3127 | | saveEntity = true; |
| | 3128 | | itemUpdateType = ItemUpdateType.ImageUpdate; |
| | 3129 | | } |
| | 3130 | |
|
| | 3131 | | if (saveEntity) |
| | 3132 | | { |
| | 3133 | | if (createEntity) |
| | 3134 | | { |
| | 3135 | | CreateItems([personEntity], null, CancellationToken.None); |
| | 3136 | | } |
| | 3137 | |
|
| | 3138 | | await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); |
| | 3139 | | personEntity.DateLastSaved = DateTime.UtcNow; |
| | 3140 | |
|
| | 3141 | | CreateItems([personEntity], null, CancellationToken.None); |
| | 3142 | | } |
| | 3143 | | } |
| | 3144 | | } |
| | 3145 | |
|
| | 3146 | | private void StartScanInBackground() |
| | 3147 | | { |
| 3 | 3148 | | Task.Run(() => |
| 3 | 3149 | | { |
| 3 | 3150 | | // No need to start if scanning the library because it will handle it |
| 3 | 3151 | | ValidateMediaLibrary(new Progress<double>(), CancellationToken.None); |
| 3 | 3152 | | }); |
| 3 | 3153 | | } |
| | 3154 | |
|
| | 3155 | | public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath) |
| | 3156 | | { |
| 1 | 3157 | | AddMediaPathInternal(virtualFolderName, mediaPath, true); |
| 0 | 3158 | | } |
| | 3159 | |
|
| | 3160 | | private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions) |
| | 3161 | | { |
| 1 | 3162 | | ArgumentNullException.ThrowIfNull(pathInfo); |
| | 3163 | |
|
| 1 | 3164 | | var path = pathInfo.Path; |
| | 3165 | |
|
| 1 | 3166 | | if (string.IsNullOrWhiteSpace(path)) |
| | 3167 | | { |
| 0 | 3168 | | throw new ArgumentException(nameof(path)); |
| | 3169 | | } |
| | 3170 | |
|
| 1 | 3171 | | if (!Directory.Exists(path)) |
| | 3172 | | { |
| 1 | 3173 | | throw new FileNotFoundException("The path does not exist."); |
| | 3174 | | } |
| | 3175 | |
|
| 0 | 3176 | | var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| 0 | 3177 | | var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); |
| | 3178 | |
|
| 0 | 3179 | | var shortcutFilename = Path.GetFileNameWithoutExtension(path); |
| | 3180 | |
|
| 0 | 3181 | | var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); |
| | 3182 | |
|
| 0 | 3183 | | while (File.Exists(lnk)) |
| | 3184 | | { |
| 0 | 3185 | | shortcutFilename += "1"; |
| 0 | 3186 | | lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); |
| | 3187 | | } |
| | 3188 | |
|
| 0 | 3189 | | _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path)); |
| | 3190 | |
|
| 0 | 3191 | | RemoveContentTypeOverrides(path); |
| | 3192 | |
|
| 0 | 3193 | | if (saveLibraryOptions) |
| | 3194 | | { |
| 0 | 3195 | | var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath); |
| | 3196 | |
|
| 0 | 3197 | | libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo]; |
| | 3198 | |
|
| 0 | 3199 | | SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions); |
| | 3200 | |
|
| 0 | 3201 | | CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions); |
| | 3202 | | } |
| 0 | 3203 | | } |
| | 3204 | |
|
| | 3205 | | public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath) |
| | 3206 | | { |
| 0 | 3207 | | ArgumentNullException.ThrowIfNull(mediaPath); |
| | 3208 | |
|
| 0 | 3209 | | var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| 0 | 3210 | | var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); |
| | 3211 | |
|
| 0 | 3212 | | var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath); |
| | 3213 | |
|
| 0 | 3214 | | SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions); |
| | 3215 | |
|
| 0 | 3216 | | CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions); |
| 0 | 3217 | | } |
| | 3218 | |
|
| | 3219 | | private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options) |
| | 3220 | | { |
| 0 | 3221 | | var topLibraryFolders = GetUserRootFolder().Children.ToList(); |
| 0 | 3222 | | var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null); |
| | 3223 | |
|
| 0 | 3224 | | if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length) |
| | 3225 | | { |
| 0 | 3226 | | var list = options.PathInfos.ToList(); |
| | 3227 | |
|
| 0 | 3228 | | foreach (var location in info.Locations) |
| | 3229 | | { |
| 0 | 3230 | | if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal))) |
| | 3231 | | { |
| 0 | 3232 | | list.Add(new MediaPathInfo(location)); |
| | 3233 | | } |
| | 3234 | | } |
| | 3235 | |
|
| 0 | 3236 | | options.PathInfos = list.ToArray(); |
| | 3237 | | } |
| 0 | 3238 | | } |
| | 3239 | |
|
| | 3240 | | public async Task RemoveVirtualFolder(string name, bool refreshLibrary) |
| | 3241 | | { |
| | 3242 | | if (string.IsNullOrWhiteSpace(name)) |
| | 3243 | | { |
| | 3244 | | throw new ArgumentNullException(nameof(name)); |
| | 3245 | | } |
| | 3246 | |
|
| | 3247 | | var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| | 3248 | |
|
| | 3249 | | var path = Path.Combine(rootFolderPath, name); |
| | 3250 | |
|
| | 3251 | | if (!Directory.Exists(path)) |
| | 3252 | | { |
| | 3253 | | throw new FileNotFoundException("The media folder does not exist"); |
| | 3254 | | } |
| | 3255 | |
|
| | 3256 | | LibraryMonitor.Stop(); |
| | 3257 | |
|
| | 3258 | | try |
| | 3259 | | { |
| | 3260 | | Directory.Delete(path, true); |
| | 3261 | | } |
| | 3262 | | finally |
| | 3263 | | { |
| | 3264 | | CollectionFolder.OnCollectionFolderChange(); |
| | 3265 | |
|
| | 3266 | | if (refreshLibrary) |
| | 3267 | | { |
| | 3268 | | await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false); |
| | 3269 | |
|
| | 3270 | | StartScanInBackground(); |
| | 3271 | | } |
| | 3272 | | else |
| | 3273 | | { |
| | 3274 | | // Need to add a delay here or directory watchers may still pick up the changes |
| | 3275 | | await Task.Delay(1000).ConfigureAwait(false); |
| | 3276 | | LibraryMonitor.Start(); |
| | 3277 | | } |
| | 3278 | | } |
| | 3279 | | } |
| | 3280 | |
|
| | 3281 | | private void RemoveContentTypeOverrides(string path) |
| | 3282 | | { |
| 0 | 3283 | | if (string.IsNullOrWhiteSpace(path)) |
| | 3284 | | { |
| 0 | 3285 | | throw new ArgumentNullException(nameof(path)); |
| | 3286 | | } |
| | 3287 | |
|
| 0 | 3288 | | List<NameValuePair>? removeList = null; |
| | 3289 | |
|
| 0 | 3290 | | foreach (var contentType in _configurationManager.Configuration.ContentTypes) |
| | 3291 | | { |
| 0 | 3292 | | if (string.IsNullOrWhiteSpace(contentType.Name) |
| 0 | 3293 | | || _fileSystem.AreEqual(path, contentType.Name) |
| 0 | 3294 | | || _fileSystem.ContainsSubPath(path, contentType.Name)) |
| | 3295 | | { |
| 0 | 3296 | | (removeList ??= new()).Add(contentType); |
| | 3297 | | } |
| | 3298 | | } |
| | 3299 | |
|
| 0 | 3300 | | if (removeList is not null) |
| | 3301 | | { |
| 0 | 3302 | | _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes |
| 0 | 3303 | | .Except(removeList) |
| 0 | 3304 | | .ToArray(); |
| | 3305 | |
|
| 0 | 3306 | | _configurationManager.SaveConfiguration(); |
| | 3307 | | } |
| 0 | 3308 | | } |
| | 3309 | |
|
| | 3310 | | public void RemoveMediaPath(string virtualFolderName, string mediaPath) |
| | 3311 | | { |
| 1 | 3312 | | ArgumentException.ThrowIfNullOrEmpty(mediaPath); |
| | 3313 | |
|
| 1 | 3314 | | var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; |
| 1 | 3315 | | var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); |
| | 3316 | |
|
| 1 | 3317 | | if (!Directory.Exists(virtualFolderPath)) |
| | 3318 | | { |
| 1 | 3319 | | throw new FileNotFoundException( |
| 1 | 3320 | | string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolder |
| | 3321 | | } |
| | 3322 | |
|
| 0 | 3323 | | var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true) |
| 0 | 3324 | | .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCa |
| 0 | 3325 | | .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, String |
| | 3326 | |
|
| 0 | 3327 | | if (!string.IsNullOrEmpty(shortcut)) |
| | 3328 | | { |
| 0 | 3329 | | _fileSystem.DeleteFile(shortcut); |
| | 3330 | | } |
| | 3331 | |
|
| 0 | 3332 | | var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath); |
| | 3333 | |
|
| 0 | 3334 | | libraryOptions.PathInfos = libraryOptions |
| 0 | 3335 | | .PathInfos |
| 0 | 3336 | | .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal)) |
| 0 | 3337 | | .ToArray(); |
| | 3338 | |
|
| 0 | 3339 | | CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions); |
| 0 | 3340 | | } |
| | 3341 | |
|
| | 3342 | | private static bool ItemIsVisible(BaseItem? item, User? user) |
| | 3343 | | { |
| 21 | 3344 | | if (item is null) |
| | 3345 | | { |
| 21 | 3346 | | return false; |
| | 3347 | | } |
| | 3348 | |
|
| 0 | 3349 | | if (user is null) |
| | 3350 | | { |
| 0 | 3351 | | return true; |
| | 3352 | | } |
| | 3353 | |
|
| 0 | 3354 | | return item is UserRootFolder || item.IsVisibleStandalone(user); |
| | 3355 | | } |
| | 3356 | | } |
| | 3357 | | } |