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