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